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

XL_SEXP *
div_ff(XLISP_ENV * env,XL_SEXP * s1,XL_SEXP * s2)
{
double _i1,_i2;
DIMENSION d1[DIM],d2[DIM],dest1[DIM],dest2[DIM];
double ret,rate;
int er;
XL_SEXP * rets;
int i;

	if ( s2->floating.data == 0 )
		return get_error(
			s2->h.file,
			s2->h.line,
			XLE_SEMANTICS_DIV_ZERO,
			l_string(std_cm,"div"),
			n_get_string("divide by zero"));
	name2dim(get_uenv(env),d1,s1->floating.unit);
	name2dim(get_uenv(env),d2,s2->floating.unit);
	fit_dimension_floating(dest1,d1,d2);
	for ( i = 0 ; i < DIM ; i ++ ) {
		dest1[i].p = d1[i].p;
		dest2[i] = dest1[i];
		dest2[i].p = d2[i].p;
	}
	_i1 = conv_unit_floating(&er,get_uenv(env),s1->floating.data,d1,dest1);
	_i2 = conv_unit_floating(&er,get_uenv(env),s2->floating.data,d2,dest2);
	rate = 1;
	for ( i = 0 ; i < DIM ; i ++ ) {
		dest1[i].p -= dest2[i].p;
		rate /= dest2[i].r;
	}
	ret = _i1 / _i2 *rate;
	normalize_dim_floating(get_uenv(env),dest1,&ret);
	rets = get_floating(ret,dim2name(get_uenv(env),dest1));

	return rets;
}


XL_SEXP *
div_ii(XLISP_ENV * env,XL_SEXP * s1,XL_SEXP * s2)
{
double _i1,_i2,rate;
DIMENSION d1[DIM],d2[DIM],dest1[DIM],dest2[DIM];
int ret;
int er;
int i;
	if ( s2->integer.data == 0 )
		return get_error(
			s2->h.file,
			s2->h.line,
			XLE_SEMANTICS_DIV_ZERO,
			l_string(std_cm,"div"),
			n_get_string("divide by zero"));
	name2dim(get_uenv(env),d1,s1->integer.unit);
	name2dim(get_uenv(env),d2,s2->integer.unit);
	fit_dimension_integer(dest1,d1,d2);
	for ( i = 0 ; i < DIM ; i ++ ) {
		dest1[i].p = d1[i].p;
		dest2[i] = dest1[i];
		dest2[i].p = d2[i].p;
	}
	_i1 = conv_unit_integer(&er,get_uenv(env),s1->integer.data,d1,dest1);
	_i2 = conv_unit_integer(&er,get_uenv(env),s2->integer.data,d2,dest2);
	rate = 1;
	for ( i = 0 ; i < DIM ; i ++ ) {
		dest1[i].p -= dest2[i].p;
		rate /= dest2[i].r;
	}
	ret = _i1 / _i2 *rate;

	normalize_dim_integer(get_uenv(env),dest1,&ret);
	return get_integer(ret,dim2name(get_uenv(env),dest1));
}


XL_SEXP *
gb_div(XLISP_ENV * e,XL_SEXP * s)
{
extern BINARY_TABLE div_tt[XLT_MAX][XLT_MAX];
	return binary(
		div_tt,
		e,
		get_el(s,1),
		get_el(s,2));
}
