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


XL_SEXP *
mul_int(XLISP_ENV * env,XL_SEXP * s1,XL_SEXP * s2)
{
double _i1,_i2;
DIMENSION d1[DIM],d2[DIM],dest1[DIM],dest2[DIM];
int ret;
int er;
int i;
	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 ++ ) {
		dest2[i] =dest1[i];
		dest1[i].p = d1[i].p;
		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);
	for ( i = 0 ; i < DIM ; i ++ ) {
		dest1[i].p += dest2[i].p;
		dest1[i].r *= dest2[i].r;
	}
	ret = _i1 * _i2;
	normalize_dim_integer(get_uenv(env),dest1,&ret);
	return get_integer(ret,dim2name(get_uenv(env),dest1));
}

XL_SEXP *
mul_float(XLISP_ENV * env,XL_SEXP * s1,XL_SEXP * s2)
{
double _i1,_i2;
DIMENSION d1[DIM],d2[DIM],dest1[DIM],dest2[DIM];
double ret;
int er;
int i;
	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 ++ ) {
		dest2[i] = dest1[i];
		dest1[i].p = d1[i].p;
		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);
	for ( i = 0 ; i < DIM ; i ++ ) {
		dest1[i].p += dest2[i].p;
		dest1[i].r *= dest2[i].r;
	}
	ret = _i1 * _i2;
	normalize_dim_floating(get_uenv(env),dest1,&ret);
	return get_floating(ret,dim2name(get_uenv(env),dest1));
}

XL_SEXP *
gb_mul(XLISP_ENV * e,XL_SEXP * s)
{
extern BINARY_TABLE mul_t[XLT_MAX][XLT_MAX];
XL_SEXP * rr;
XL_SEXP * ret;
	rr = cdr(cdr(s));
	ret = get_el(s,1);
	for ( ; get_type(rr) ; rr = cdr(rr) )
		ret = binary(
			mul_t,
			e,
			ret,
			car(rr));
	return ret;
}
