/**********************************************************************
 
	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"


XL_SEXP * xl_List2Matrix();

void
init_List2Matrix(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"List2Matrix"),
		get_func_prim(xl_List2Matrix,FO_APPLICATIVE,0,2,2));
}


double
get_cel(XL_SEXP ** ret,XL_SEXP * c,XL_FILE * file,int line)
{
	*ret = 0;
	switch ( get_type(c) ) {
	case XLT_INTEGER:
		return c->integer.data;
	case XLT_FLOAT:
		return c->floating.data;
	default:
		break;
	}
	*ret = get_error(
		file,
		line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"List2Matrix"),
		n_get_string("type missmatch"));
	return 0;
}

XL_SEXP *
xl_List2Matrix(XLISP_ENV * env,XL_SEXP * s)
{
EX_MATRIX * ret;
XL_SEXP * _ret;
int size;
L_CHAR * _size;
int i,j;
XL_SEXP * input, * c;
int v,h;

	input = get_el(s,1);
	v = list_length(input);
	if ( v < 0 )
		goto type_missmatch;

	c = car(input);
	if ( get_type(c) != XLT_PAIR ) {
		h = 1;
		ret = new_ex_matrix(v,h);
		for ( i = 0 ; i < v ; i ++ ) {
			XD(ret,i,0) = get_cel(&_ret,car(input),
				s->h.file,s->h.line);
			input = cdr(input);
		}
	}
	else {
		h = list_length(car(input));
		if ( h < 0 )
			goto type_missmatch;
		ret = new_ex_matrix(v,h);
		for ( i = 0 ; i < v ; i ++ ) {
			c = car(input);
			for ( j = 0 ; j < h ; j ++ ) {
				XD(ret,i,j) = get_cel(&_ret,car(c),
					s->h.file,s->h.line);
				if ( get_type(_ret) == XLT_ERROR )
					goto err;
				c = cdr(c);
			}
			input = cdr(input);
		}
	}

	_ret = get_sexp_from_ex(ret);
	free_ex_matrix(ret);
	return _ret;
err:
	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,"List2Matrix"),
		n_get_string("type missmatch(v/h error)"));
}

