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

void
init_ErrHandler(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"ErrHandler"),
		get_func_prim(xl_ErrHandler,FO_NORMAL,0,2,2));
}

XL_SEXP *
err_handler(XL_SEXP * e,XL_FILE * f,int line)
{
XL_SEXP * ret;
	if ( get_type(e) != XLT_ERROR ) {
		ret = 0;
		ret = cons(e,ret);
		ret = cons(get_integer(0,0),ret);
		ret = cons(n_get_string("ErrHandler"),ret);

		if ( f ) {
			ret = cons(get_string(f->name),ret);
			ret = cons(get_string(f->site),ret);
		}
		else {
			ret = cons(n_get_string("undefined"),ret);
			ret = cons(n_get_string("unknown"),ret);
		}
		ret = cons(get_integer(line,0),ret);
		ret = cons(n_get_symbol("Error"),ret);
		return ret;
	}
	ret = 0;
	ret = cons(e->err.data,ret);
	ret = cons(get_integer(e->err.code,0),ret);
	ret = cons(get_string(e->err.func),ret);
	ret = cons(get_string(e->err.filename),ret);
	ret = cons(get_string(e->err.site),ret);
	ret = cons(get_integer(e->err.line,0),ret);
	ret = cons(n_get_symbol("Error"),ret);
	return ret;
}

XL_SEXP *
xl_ErrHandler(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * e;
XL_SEXP * ee;
	ee = get_el(s,1);
	e = eval(env,ee);
	return err_handler(e,s->h.file,s->h.line);
}
