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

void
init_SetAttribute(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"SetAttribute"),
		get_func_prim(xl_SetAttribute,FO_APPLICATIVE,0,4,4));
}

XL_SEXP *
set_attribute_symbol(XL_SEXP * target,L_CHAR * attr,L_CHAR * data)
{
XL_SEXP * ret;
XL_SYM_FIELD * sf;
	ret = get_symbol(target->symbol.data);
	for ( sf = target->symbol.field ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,attr) == 0 )
			continue;
		set_attribute(ret,
			sf->name,
			sf->data);
	}
	set_attribute(ret,
		attr,data);
	return ret;
}

XL_SEXP *
set_attribute_pair(XL_SEXP * target,L_CHAR * attr,L_CHAR * data)
{
XL_SEXP * ret;
	ret = set_attribute_symbol(car(target),attr,data);
	return cons(ret,cdr(target));
}

XL_SEXP *
xl_SetAttribute(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * target;
XL_SEXP * attr;
XL_SEXP * data;
L_CHAR * _attr, * _data;
char buf[10];
	target = get_el(s,1);
	attr = get_el(s,2);
	data = get_el(s,3);
	if ( get_type(attr) != XLT_STRING )
		goto type_missmatch;
	_attr = attr->string.data;
	switch ( get_type(data) ) {
	case XLT_SYMBOL:
		_data = data->symbol.data;
		break;
	case XLT_STRING:
		_data = data->string.data;
		break;
	case XLT_INTEGER:
		if ( data->integer.unit )
			sprintf(buf,"%i%s",data->integer.data,
				n_string(std_cm,data->integer.unit));
		else	sprintf(buf,"%i",data->integer.data);
		_data = l_string(std_cm,buf);
		break;
	case XLT_FLOAT:
		if ( data->floating.unit )
			sprintf(buf,"%lf%s",data->floating.data,
				n_string(std_cm,data->floating.unit));
		else	sprintf(buf,"%lf",data->floating.data);
		_data = l_string(std_cm,buf);
		break;
	default:
		goto type_missmatch;
	}
	switch ( get_type(target) ) {
	case XLT_SYMBOL:
		return set_attribute_symbol(target,_attr,_data);
	case XLT_PAIR:
		if ( get_type(car(target)) != XLT_SYMBOL )
			goto type_missmatch;
		return set_attribute_pair(target,_attr,_data);
	}
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"SetAttribute"),
		list(	n_get_string("type missmatch"),
			0));
}
