/**********************************************************************
 
	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	"ex_matrix.h"
#include	"xlerror.h"
#include	"xl.h"
#include	"associate.h"

XL_SEXP * xl_Madd();

void
init_Madd(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Madd"),
		get_func_prim(xl_Madd,FO_APPLICATIVE,0,3,-1));
}

XL_SEXP *
xl_Madd(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
EX_MATRIX * ret,* m1, * m2;
XL_SEXP * _ret;
	m1 = 0;
	m2 = 0;
	s = cdr(s);
	ret = get_ex_from_sexp(car(s));
	if ( ret == 0 )
		goto type_missmatch;
	s = cdr(s);
	for ( ; get_type(s) == XLT_PAIR ; s = cdr(s) ) {
		m1 = get_ex_from_sexp(car(s));
		if ( m1 == 0 ) {
			free_ex_matrix(ret);
			goto type_missmatch;
		}
		m2 = add_ex(ret,m1);
		free_ex_matrix(m1);
		if ( m2 == 0 ) {
			free_ex_matrix(ret);
			goto invalid_add;
		}
		free_ex_matrix(ret);
		ret = m2;
	}
	_ret = get_sexp_from_ex(ret);
	free_ex_matrix(ret);
	return _ret;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"Madd"),
		n_get_string("type missmatch"));
invalid_add:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_DIV_ZERO,
		l_string(std_cm,"Madd"),
		n_get_string("invalid add matrix"));
}

