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

void
init_ConvertUnit(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"ConvertUnit"),
		get_func_prim(xl_ConvertUnit,FO_APPLICATIVE,0,3,3));
}

XL_SEXP *
xl_ConvertUnit(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * data;
XL_SEXP * from,* to;
L_CHAR * _from, * _to;
double _ret;
int er;
	data = get_el(s,1);
	to = get_el(s,2);
	switch ( get_type(to) ) {
	case XLT_ERROR:
		return to;
	case XLT_STRING:
		_to = to->string.data;
		break;
	case XLT_NULL:
		_to = 0;
		break;
	default:
		goto type_missmatch;
	}
	switch ( get_type(data) ) {
	case XLT_ERROR:
		return data;
	case XLT_INTEGER:
		_ret = conv_unit(&er,
			get_uenv(env),
			data->integer.data,
			data->integer.unit,
			_to);
		break;
	case XLT_FLOAT:
		_ret = conv_unit(&er,
			get_uenv(env),
			data->floating.data,
			data->floating.unit,
			_to);
		break;
	default:
		goto type_missmatch;
	}
	if ( er < 0 )
		return get_error(
			s->h.file,
			s->h.line,
			XLE_PROTO_INV_PARAM,
			l_string(std_cm,"ConvertUnit"),
			n_get_string("Cannot convert"));
	if ( _ret == ((int)_ret) )
		return get_integer(_ret,_to);
	else
		return get_floating(_ret,_to);
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"ConvertUnit"),
		n_get_string("type missmatch"));
}

