/**********************************************************************
 
	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	"task.h"
#include	"lock_level.h"
#include	"resource.h"
#include	"memory_debug.h"

SEM		status_lock;
/*
RING_TYPE	resource_h;
RW_LOCK		resource_lock;
*/

SEM res_lock;

extern unsigned char resource_script[];
extern int resource_script_length;

RESOURCE **	res_entry_hash_table;
RESOURCE **	res_target_hash_table;
RESOURCE **	res_no_hash_table;


void
loading_resource_xl()
{
STREAM * st;
XL_SEXP * lst, * ret;

	set_env(gblisp_top_env0,l_string(std_cm,"rt-coordinate"),
		get_integer(RT_COORDINATE,0));
	set_env(gblisp_top_env0,l_string(std_cm,"rt-map"),
		get_integer(RT_MAP,0));
	set_env(gblisp_top_env0,l_string(std_cm,"rt-vector"),
		get_integer(RT_DRAW_GB,0));
	set_env(gblisp_top_env0,l_string(std_cm,"rt-luster.r64"),
		get_integer(RT_PIXEL_MAP_R64,0));

	st = s_open_string_read(
		resource_script,
		&utf8_cm,
		resource_script_length,
		0);

	gc_push(0,0,"loading_resource_xl");

	lst = init_parse(st,
			l_string(std_cm,"resource.xl"),
			l_string(std_cm,"resource.xl"));
	for ( ; get_type(lst) == XLT_PAIR ; lst = cdr(lst) ) {
		ret = eval(gblisp_top_env1,car(lst));
		if ( get_type(ret) == XLT_ERROR ) {
			print_sexp(s_stderr,ret,0);
			fprintf(stderr,"\n");
			exit(1);
		}
	}

	gc_pop(0,0);


}

void
init_resource()
{
	res_lock = new_lock(LL_LOAD_RES);

	res_entry_hash_table
		= d_alloc(sizeof(RESOURCE*)*RES_HASH_SIZE);
	res_target_hash_table 
		= d_alloc(sizeof(RESOURCE*)*RES_HASH_SIZE);
	res_no_hash_table
		= d_alloc(sizeof(int)*RES_HASH_SIZE);
	memset(res_entry_hash_table,0,sizeof(RESOURCE*)*RES_HASH_SIZE);
	memset(res_target_hash_table,0,sizeof(RESOURCE*)*RES_HASH_SIZE);
	memset(res_no_hash_table,0,sizeof(RESOURCE*)*RES_HASH_SIZE);

	init_coordinate_unit();

	init_gv_resource(gblisp_top_env0);
	init_map();
	init_coordinate();
	init_load_resource();

	status_lock = new_lock(LL_STATUS);

	loading_resource_xl();
	init_favt();
	init_rcache();
	init_routing();
}
