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

void
init_IndexAS(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"IndexAS"),
		get_func_prim(xl_IndexAS,FO_APPLICATIVE,0,3,3));
}

XL_SEXP *
xl_IndexAS(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
XL_SEXP * type,* name;
int key,index;
XL_SEXP * ret;
short _type;
short _name;
	key = -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);
		}
	}
	type = get_el(s,1);
	if ( get_type(type) != XLT_STRING )
		goto type_missmatch;
	if ( l_strcmp(type->string.data,l_string(std_cm,"string")) == 0 )
		_type = AIT_STRING;
	else if ( l_strcmp(type->string.data,l_string(std_cm,"integer")) == 0 )
		_type = AIT_INTEGER;
	else	goto inv_param;
	name = get_el(s,2);
	if ( get_type(name) != XLT_INTEGER )
		goto type_missmatch;
	_name = name->integer.data;
	index = new_index(key,_type,_name);
	if ( index < 0 ) {
		index = get_index(key,_name);
		if ( get_index_type(key,index) != _type )
			goto inv_param;
	}
	return get_integer(index,0);
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"IndexAS"),
		n_get_string("type missmatch"));
inv_param:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"IndexAS"),
		n_get_string("invalid parameter"));
}

