/**********************************************************************
 
	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"
#include	"associate.h"

XL_SEXP * xl_SetAS();

void
init_SetAS(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"SetAS"),
		get_func_prim(xl_SetAS,FO_APPLICATIVE,0,3,3));
}

XL_SEXP *
xl_SetAS(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
XL_SEXP * from, * data;
int key,index;
int er;

	key = -1;
	index = -1;
	for ( ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,l_string(std_cm,"key")) == 0 ) {
			sscanf(n_string(std_cm,sf->data),"%i",&key);
		}
		else if ( l_strcmp(sf->name,l_string(std_cm,"index")) == 0 ) {
			sscanf(n_string(std_cm,sf->data),"%i",&index);
		}
	}
	from = get_el(s,1);
	data = get_el(s,2);
	switch ( get_type(from) ) {
	case XLT_INTEGER:
		er = insert_associate(key,index,&from->integer.data,data);
		break;
	case XLT_STRING:
		er = insert_associate(key,index,from->string.data,data);
		break;
	default:
		goto type_missmatch;
	}
	if ( er < 0 )
		goto cannot_insert;

	return 0;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"SetAS"),
		n_get_string("type missmatch"));
cannot_insert:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"SetAS"),
		n_get_string("insert error"));
}

