/**********************************************************************
 
	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	<math.h>
#include	"xlerror.h"
#include	"xl.h"
#include	"gbgraph.h"

XL_SEXP * xl_UnionRect();

void
init_UnionRect(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"UnionRect"),
		get_func_prim(xl_UnionRect,FO_APPLICATIVE,0,3,3));
}

XL_SEXP *
xl_UnionRect(XLISP_ENV * env,XL_SEXP * s)
{
GB_RECT r1,r2,ret;
L_CHAR * base_unit;
COORDINATE_UNIT cu,* cup;
XL_SEXP * s_ret;
	base_unit = get_base_unit(get_el(s,1));
	zero_c_unit(&cu);
	if ( base_unit ) {
		cu.unit = base_unit;
		cu.uenv = get_uenv(env);
		cup = &cu;
	}
	else {
		base_unit = get_base_unit(get_el(s,2));
		if ( base_unit ) {
			cu.unit = base_unit;
			cu.uenv = get_uenv(env);
			cup = &cu;
		}
		else 	cup = 0;
	}

	if ( get_minrect(cup,&r1,get_el(s,1)) < 0 )
		goto type_missmatch;
	if ( get_minrect(cup,&r2,get_el(s,2)) < 0 )
		goto type_missmatch;
	if ( r1.tl.x > r1.br.x ) {
		ret =  r2;
		goto end;
	}
	if ( r2.tl.x > r2.br.x ) {
		ret = r1;
		goto end;
	}
	ret = r1;
	insert_rect(&ret,r2.tl);
	insert_rect(&ret,r2.br);
end:
	s_ret = List(
		List(	get_floating(ret.tl.x,base_unit),
			get_floating(ret.tl.y,base_unit),
			-1),
		List(	get_floating(ret.br.x,base_unit),
			get_floating(ret.br.y,base_unit),
			-1),
		-1);
	return s_ret;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"UnionRect"),
		n_get_string("type missmatch"));
}

