/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	This program is distributed in the hope that it will be 
	useful, but WITHOUT ANY WARRANTY; without even the 
	implied warranty of MERCHANTABILITY or FITNESS FOR A 
	PARTICULAR PURPOSE.

**********************************************************************/




#include	"xlerror.h"
#include	"xl.h"


XL_SEXP * xl_If();

void
init_If(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"If"),
		get_func_prim(xl_If,FO_NORMAL,0,3,4));
}

XL_SEXP *
if_loop(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * ret;
void gc_gb_sexp();
	ret = 0; 
	for ( ; get_type(s) == XLT_PAIR ; s = cdr(s) ) {
		gc_push(0,0,"if_loop");
		ret = eval(env,car(s));
		gc_pop(ret,gc_gb_sexp);
		if ( get_type(ret) == XLT_ERROR )
			break;
	}
	return ret;
}

XL_SEXP *
xl_If(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * cond;
XL_SEXP * th,* el;
int _cond;
XL_SEXP * r, * r1, * rs;
int th_cnt,el_cnt;
	cond = eval(env,get_el(s,1));
	switch ( get_type(cond) ) {
	case XLT_ERROR:
		return cond;
	case XLT_INTEGER:
		if ( cond->integer.data == 0 )
			_cond = 0;
		else	_cond = 1;
		break;
	case XLT_FLOAT:
		if ( cond->floating.data == 0 )
			_cond = 0;
		else	_cond = 1;
		break;
	default:
		goto type_missmatch;
	}
	th_cnt = el_cnt = 0;
	for ( r = cdr(cdr(s)) ; get_type(r) ; r = cdr(r) ) {
		r1 = car(r);
		rs = car(r1);
		if ( get_type(rs) != XLT_SYMBOL )
			goto param_error;
		if ( l_strcmp(rs->symbol.data,l_string(std_cm,"Then")) == 0 ) {
			if ( th_cnt == 1 )
				goto param_error;
			th_cnt = 1;
			if ( _cond == 0 )
				continue;
			return if_loop(env,cdr(r1));
		}
		else if ( l_strcmp(rs->symbol.data,l_string(std_cm,"Else")) 
						== 0 ) {
			if ( el_cnt == 1 )
				goto param_error;
			el_cnt = 1;
			if ( _cond == 1 )
				continue;
			return if_loop(env,cdr(r1));
		}
		else 	goto param_error;
	}
	return 0;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"If"),
		n_get_string("type missmatch"));
param_error:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"If"),
		n_get_string("then else parameter error"));
}

