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

void
init_Msub(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"Msub"),
		get_func_prim(xl_Msub,FO_APPLICATIVE,0,2,3));
}

XL_SEXP *
xl_Msub(XLISP_ENV * env,XL_SEXP * s,
	XLISP_ENV * a,XL_SYM_FIELD * sf)
{
EX_MATRIX * m1, * m2;
EX_MATRIX * _ret;
XL_SEXP * ret;
int er;
	m1 = 0;
	m2 = 0;
	m1 = get_ex_from_sexp(get_el(s,1));
	if ( m1 == 0 ) {
		goto type_missmatch;
	}
	if ( list_length(s) == 3 ) {
		m2 = get_ex_from_sexp(get_el(s,2));
		if ( m2 == 0 ) {
			free_ex_matrix(m1);
			goto type_missmatch;
		}
	}
	else	m2 = 0;
	_ret = sub_ex(m1,m2);
	free_ex_matrix(m1);
	free_ex_matrix(m2);
	if ( _ret == 0 )
		goto invalid_sub;
	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,"Msub"),
		n_get_string("type missmatch"));
invalid_sub:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_DIV_ZERO,
		l_string(std_cm,"Msub"),
		n_get_string("invalid substract matrix"));
}

