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

void
init_GetAS(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"GetAS"),
		get_func_prim(xl_GetAS,FO_APPLICATIVE,0,2,2));
}

XL_SEXP *
xl_GetAS(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
XL_SEXP * from, * data;
int key,index;
int er;
ASSOC_STRING_OPT s_opt;
int s_opt_f;
XL_SEXP * ret;
	key = -1;
	index = -1;
	s_opt_f = 0;

	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);
		}
		else if ( l_strcmp(sf->name,l_string(std_cm,"stropt")) == 0 ) {
			if ( l_strcmp(sf->data,
					l_string(std_cm,"fit")) == 0 ) {
				s_opt.flags = 1;
				s_opt_f = 1;
			}
			else {
				s_opt.flags = 0;
				s_opt_f = 1;
			}
		}
	}
	from = get_el(s,1);
	switch ( get_type(from) ) {
	case XLT_INTEGER:
		ret = search_associate(key,index,&from->integer.data,0);
		break;
	case XLT_STRING:
		ret = search_associate(key,index,from->string.data,&s_opt);
		break;
	default:
		goto type_missmatch;
	}

	if ( s_opt_f )
		return List(
			n_get_symbol("stropt"),
			ret,
			get_integer(s_opt.size,0),
			-1);
	else	return ret;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"GetAS"),
		n_get_string("type missmatch"));
cannot_insert:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"GetAS"),
		n_get_string("insert error"));
}

