/**********************************************************************
 
	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	"gbview.h"
#include	"xlerror.h"
#include	"memory_debug.h"
#include	"memory_routine.h"
#include	"xl.h"
#include	"v.h"
#include	"gif.h"
#include	"jpeg.h"

#define BACKGROUND_COLOR	COL(0x3ff,0x3ff,0x3ff)

XL_SEXP * xl_gv_flame_redraw();
XL_SEXP * xl_gv_flame_deq_seq();

extern char gv_flame_dirty_flag;

void
init_gv_flame_redraw(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"gv-flame-redraw"),
		get_func_prim(xl_gv_flame_redraw,FO_APPLICATIVE,0,5,5));
}

XL_SEXP *
xl_gv_flame_redraw(
	XLISP_ENV * e,
	XL_SEXP * s,
	XLISP_ENV * a_e,
	XL_SYM_FIELD * sf)
{
XL_SEXP *x1,*y1,*w1,*h1;
GBVIEW_STATUS sts;
GBVIEW_PLANE gbp;
int x,y,w,h,f1,f2;
XL_SEXP * ret;

	x1 = get_el(s,1);
	y1 = get_el(s,2);
	w1 = get_el(s,3);
	h1 = get_el(s,4);
	if ( get_type(x1) != XLT_INTEGER || get_type(y1) != XLT_INTEGER ||
			get_type(w1) != XLT_INTEGER || get_type(h1) != XLT_INTEGER )
		goto type_mismatch;
	x = x1->integer.data;
	y = y1->integer.data;
	w = w1->integer.data;
	h = h1->integer.data;

	wf_status(&sts);
	if ( x < 0 || y < 0 || x+w > sts.width || y+h > sts.height || w <= 0 || h <= 0 ) {
		wf_free_status(&sts);
		return get_error(
			s->h.file,
			s->h.line,
			XLE_PROTO_INV_PARAM,
			l_string(std_cm,"gv-flame-redraw"),
			List(n_get_string("invalid range"),
				-1));
	}

	gv_flame_dirty_flag = 0;

retry:
	if ( ! wf_redraw(&gbp,x,y,w,h) )
		return 0;

printf("REDRAW %d %d %d %d\n",
gbp.r.r.tl.x,
gbp.r.r.tl.y,
gbp.r.r.br.x,
gbp.r.r.br.y);

	ret = gbp2list(&gbp,sf);
	wf_free_plane(&gbp);
	wf_free_status(&sts);
	if ( ret )
		return ret;
	else
		return get_error(
			s->h.file,
			s->h.line,
			XLE_PROTO_INV_PARAM,
			l_string(std_cm,"gv-flame-redraw"),
			List(n_get_string("unknown format"),
			-1));

type_mismatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"gv-flame-redraw"),
		List(n_get_string("type missmatch"),
			-1));
}
