/**********************************************************************
 
	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	"xl.h"
#include	"xlerror.h"
#include	"task.h"

extern SEM gb_env_lock;

int
set_op(XLISP_ENV * e,XL_SEXP * sym,XL_SEXP * data)
{
ELEMENT * el;
XLISP_ENV * ee;
int ret;
	for ( ee = e ; ee ; ) {
		switch ( ee->type ) {
		case GBET_ENV:
			lock_task(gb_env_lock); 
			el = search_env(ee,sym->symbol.data);
			if ( el ) {
				el->data = data;
				unlock_task(gb_env_lock,"gb_set"); 
				return 0;
			}
			unlock_task(gb_env_lock,"gb_set"); 
			ee = ee->e.parent;
			break;
		case GBET_PAIR:
			ret = set_op(ee->p.env[0],sym,data);
			if ( ret == 0 )
				return 0;
			ee = ee->p.env[1];
			break;
		default:
			er_panic("gb_set(1)");
		}
	}
	return -1;
}

XL_SEXP *
gb_set(XLISP_ENV * e,XL_SEXP * s)
{
XL_SEXP * sym;
XL_SEXP * data;
ELEMENT * el;
XLISP_ENV * ee;


	sym = get_el(s,1);
	switch ( get_type(sym) ) {
	case XLT_ERROR:
		return sym;
	case XLT_SYMBOL:
		break;
	default:
		return get_error(
			sym->h.file,
			sym->h.line,
			XLE_SEMANTICS_REQ_SYMBOL,
			l_string(std_cm,"set"),
			list(n_get_string(
			"symbol is required for 1st parameter"),
				0));
	}
	data = eval(e,get_el(s,2));
	if ( get_type(data) == XLT_ERROR )
		return data;
	if ( set_op(e,sym,data) < 0 )
		return get_error(
			sym->h.file,
			sym->h.line,
			XLE_SEMANTICS_UNDEF_SYMBOL,
			l_string(std_cm,"set"),
			List(n_get_string("symbol "),
				sym,
				n_get_string(" is undefined"),
				-1));
	return 0;
}

