/**********************************************************************
 
	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	"memory_debug.h"
#include	"gbview.h"
#include	"xlerror.h"


XL_SEXP *
dgb_tile(XLISP_ENV * e,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
RESOURCE * r;
L_CHAR * tile_query;
XL_SEXP * ret;
	r = get_resource_ptr(&ret,e,s->h.file,s->h.line);
	if ( r == 0 )
		return ret;
	if ( r->h.type != RT_DRAW_GB )
		er_panic("dgb_polygon2d(2)");
	tile_query = get_sf_attribute(sf,
			l_string(std_cm,"tile-query"));
	if ( tile_query == 0 )
		r->draw_gb.tile_query = 'c';
	else if ( l_strcmp(tile_query,l_string(std_cm,"center")) == 0 )
		r->draw_gb.tile_query = 'c';
	else	r->draw_gb.tile_query = 'r';
	return 0;
/*no_obj: */
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_UNDEF_NAME,
		l_string(std_cm,"set-color-palette"),
		list(n_get_string("no object"),0));
}

int
tile_id_cmp(TILE_ID_LIST * tl1,TILE_ID_LIST * tl2)
{
	if ( tl1->code < tl2->code )
		return -1;
	if ( tl1->code > tl2->code )
		return 1;
	return 0;
}


void
_reset_tile_id(RESOURCE * r)
{
AVT_NODE * a;
	for ( ; r->draw_gb.tile_list ; ) {
		a = r->draw_gb.tile_list;
		a = avt_delete(&r->draw_gb.tile_list,a->data,tile_id_cmp);
		d_f_ree(a->data);
		d_f_ree(a);
	}
}

int
_new_tile_id(RESOURCE * r,int code)
{
int tile_id;
	tile_id = r->draw_gb.tile_id;
	tile_id += 256;
	if ( tile_id <= 0 )
		tile_id = 256;
	r->draw_gb.tile_id = tile_id;
	return tile_id;
}


int
_get_tile_id(RESOURCE * r,int code)
{
AVT_NODE * a;
TILE_ID_LIST * tlp;
TILE_ID_LIST tl;
	tl.code = code;
	a = avt_search(r->draw_gb.tile_list,&tl,tile_id_cmp);
	if ( a ) {
		tlp = a->data;
		return tlp->inner_id;
	}
	tlp = d_alloc(sizeof(*tlp));
	tlp->inner_id = _new_tile_id(r,code);
	tlp->code = code;
	a = d_alloc(sizeof(*a));
	a->data = tlp;
	avt_insert(&r->draw_gb.tile_list,a,tile_id_cmp);
	return tlp->inner_id;
}

