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

XL_SEXP * xl_Trunc();

void
init_Trunc(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Trunc"),
		get_func_prim(xl_Trunc,FO_APPLICATIVE,0,3,3));
}

XL_SEXP *
xl_Trunc(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * path;
XL_SEXP * prefix;
L_CHAR * buf;
XL_SEXP * ret;
	path = get_el(s,1);
	switch ( get_type(path) ) {
	case XLT_ERROR:
		return path;
	case XLT_STRING:
		buf = ll_copy_str(path->string.data);
		break;
	default:
		goto type_missmatch;
	}
	prefix = get_el(s,2);
	switch ( get_type(prefix) ) {
	case XLT_ERROR:
		d_f_ree(buf);
		return prefix;
	case XLT_STRING:
		break;
	default:
		d_f_ree(buf);
		goto type_missmatch;
	}
	if ( l_strcmp(&buf[l_strlen(buf)-l_strlen(prefix->string.data)],
			prefix->string.data) == 0 ) {
		buf[l_strlen(buf)-l_strlen(prefix->string.data)]
			= 0;
	}
	ret = get_string(buf);
	return ret;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"Trunc"),
		0);
}
