/**********************************************************************
 
	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_RectResolution();

void
init_RectResolution(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"RectResolution"),
		get_func_prim(xl_RectResolution,FO_APPLICATIVE,0,4,5));
}

XL_SEXP *
xl_RectResolution(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * num;
int _num;
XL_SEXP * dist;
REAL1 _dist;
GB_RECT r;
REAL1 h,w,reso1,reso2;
XL_SEXP * mr;
REAL1 _mr;
int er;
L_CHAR * base_unit;
COORDINATE_UNIT cu,* cup;
XL_SEXP * 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	cup = 0;
	if ( get_minrect(cup,&r,get_el(s,1)) < 0 )
		goto type_missmatch;
	num = get_el(s,2);
	if ( get_type(num) != XLT_INTEGER )
		goto type_missmatch;
	_num = num->integer.data;
	dist = get_el(s,3);
	if ( get_type(dist) != XLT_INTEGER )
		goto type_missmatch;
	_dist = dist->integer.data;
	if ( list_length(s) == 5 ) {
		mr = get_el(s,4);
		switch ( get_type(mr) ) {
		case XLT_INTEGER:
			_mr = conv_unit(
				&er,
				cu.uenv,
				mr->integer.data,
				mr->integer.unit,
				base_unit);
			break;
		case XLT_FLOAT:
			_mr = conv_unit(
				&er,
				cu.uenv,
				mr->floating.data,
				mr->floating.unit,
				base_unit);
			break;
		default:
			goto type_missmatch;
		}
	}
	else	_mr = 0;
	w = r.br.x - r.tl.x;
	h = r.br.y - r.tl.y;
	if ( w < h )
		reso1 = 1/w;
	else	reso1 = 1/h;
	reso2 = _dist/sqrt(h*w/_num);
	if ( reso2 < reso1 )
		ret = get_floating(reso1,reso_c_unit(&cu));
	else if ( _mr != 0 && _mr < reso2 )
		ret = get_floating(_mr,reso_c_unit(&cu));
	else	ret = get_floating(reso2,reso_c_unit(&cu));
	return ret;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"RectResolution"),
		n_get_string("type missmatch"));
}

