/**********************************************************************
 
	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_Switch();

void
init_Switch(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Switch"),
		get_func_prim(xl_Switch,FO_NORMAL,0,2,-1));
}

XL_SEXP *
xl_Switch(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * cond;
XL_SEXP * th,* el;
int _cond;
XL_SEXP * r, * r1, * rs, * ret;

	for ( r = cdr(s) ; get_type(r) ; r = cdr(r) ) {
		r1 = car(r);
		if ( list_length(r1) < 3 )
			goto param_error;
		rs = car(r1);
		if ( get_type(rs) != XLT_SYMBOL )
			goto param_error;
		if ( l_strcmp(rs->symbol.data,l_string(std_cm,"Case")) )
			goto param_error;
		cond = eval(env,get_el(r1,1));
		switch ( get_type(cond) ) {
		case XLT_ERROR:
			return cond;
		case XLT_INTEGER:
			_cond = cond->integer.data;
			break;
		case XLT_FLOAT:
			_cond = cond->floating.data;
			break;
		default:
			goto type_missmatch;
		}
		if ( _cond == 0 )
			continue;
		ret = 0;
		for ( r1 = cdr(cdr(r1)) ; get_type(r1) ; r1 = cdr(r1) ) {
			ret = eval(env,car(r1));
			if ( get_type(ret) == XLT_ERROR )
				return ret;
		}
		return ret;
	}
	return 0;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"Switch"),
		n_get_string("type missmatch"));
param_error:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"Switch"),
		n_get_string("then else parameter error"));
}

