/**********************************************************************
 
	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"

XL_SEXP *
rem_ff(XLISP_ENV * env,XL_SEXP * s1,XL_SEXP * s2)
{
L_CHAR * unit;
int cnt;
double a,b;
	if ( s1->floating.unit )
		unit = s1->floating.unit;
	else	unit = s2->floating.unit;
	if ( s2->floating.data == 0 )
		return get_error(
			s2->h.file,
			s2->h.line,
			XLE_SEMANTICS_DIV_ZERO,
			l_string(std_cm,"rem"),
			n_get_string("divide by zero"));
	a = s1->floating.data;
	b = s2->floating.data;
	if ( a > 0 ) {
		if ( b > 0 ) {
			cnt = 0;
			for ( ; a >= b*cnt ; cnt ++ );
			a = a - b*(cnt-1);
		}
		else {
			cnt = 0;
			for ( ; a >= b*cnt ; cnt -- );
			a = a - b*(cnt+1);
		}
	}
	else {
		if ( b > 0 ) {
			cnt = 0;
			for ( ; a < b*cnt ; cnt -- );
			a = a - b*cnt;
		}
		else {
			cnt = 0;
			for ( ; a < b*cnt ; cnt ++ );
			a = a - b*cnt;
		}
	}
	return get_floating(a,unit);
}


XL_SEXP *
rem_ii(XLISP_ENV * env,XL_SEXP * s1,XL_SEXP * s2)
{
L_CHAR * unit;
	if ( s1->floating.unit )
		unit = s1->integer.unit;
	else	unit = s2->integer.unit;
	if ( s2->integer.data == 0 )
		return get_error(
			s2->h.file,
			s2->h.line,
			XLE_SEMANTICS_DIV_ZERO,
			l_string(std_cm,"rem"),
			n_get_string("divide by zero"));
	return get_integer(
		s1->integer.data%s2->integer.data,
		unit);
}


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