/**********************************************************************
 
	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	"kyotodb.h"
#include	"favt.h"
#include	"dtree.h"

XL_SEXP * xl_set_entry();

void
init_set_entry(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"set-entry"),
		get_func_prim(xl_set_entry,FO_APPLICATIVE,0,3,3));
}

XL_SEXP *
xl_set_entry(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * name;
XL_SEXP * id;
L_CHAR * _name;
char * _id;
FAVT_ROOT * r;
unsigned int fofs;
FAVT_NODE * n, * n2;
IDS_NODE idsn, * idsp;
int er;
	name = get_el(s,1);
	id = get_el(s,2);
	switch ( get_type(name) ) {
	case XLT_STRING:
		_name = name->string.data;
		break;
	case XLT_NULL:
		return 0;
	}
	switch ( get_type(id) ) {
	case XLT_STRING:
		_id = n_string(std_cm,id->string.data);
		break;
	case XLT_NULL:
		return 0;
	}
	r = get_root(p,ids_root,dummy_endian);
	if ( strlen(_id) >= ID_SIZE )
		er_panic("set_entry(1)");
	strcpy(idsn.id,_id);
	n = favt_search(r,root_node(r),&idsn,cmp_string);
	if ( n ) {
		idsp = n->data;
		r = get_root(p,names_root,dtree_endian);
		er = insert_dtree(r,_name,0,idsp->fofs);
		if ( er < 0 )
			er_panic("set-entry(2)");
	}
	else {
		r = get_root(p,names_root,dtree_endian);
		fofs = search_dtree(0,r,_name,1);
		if ( fofs == 0 ) {
			fofs = set_k_table(0,_name,_id);
			er = insert_dtree(r,_name,0,fofs);
			if ( er < 0 )
				er_panic("set-entry");
			idsn.fofs = fofs;
		}
		else {
			idsn.fofs = set_k_table(fofs,_name,_id);
		}
		r = get_root(p,ids_root,dummy_endian);
		if ( strlen(_id) >= ID_SIZE )
			er_panic("set_entry(1)");
		strcpy(idsn.id,_id);
		n = favt_alloc_node(r,&idsn,sizeof(idsn));
		n2 = favt_insert(r,&r->node,n,cmp_string);
		if ( n2 != n )
			favt_free_node(n);
	}
	return 0;
}


