/**********************************************************************
 
	Copyright (C) 2005- 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	"machine/include.h"
#include	"memory_debug.h"
#include	"pri_level.h"
#include	"lock_level.h"
#include	"utils.h"
#include	"task.h"
#include	"matrix.h"
#include	"xl.h"
#include	"xlerror.h"

XL_SEXP *
xl_mxLoad(XLISP_ENV * env,XL_SEXP * s,XLISP_ENV * a,XL_SYM_FIELD * sf);

void
init_mxLoad(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"mxLoad"),
		get_func_prim(xl_mxLoad,FO_APPLICATIVE,0,1,1));
}


XL_SEXP *
xl_mxLoad(XLISP_ENV * env,XL_SEXP * s,XLISP_ENV * a,XL_SYM_FIELD * sf)
{
L_CHAR * target;
int f;
MATRIX_TOKEN * t;
int ret;
	t = get_env_work(env);
	if ( t == 0 )
		return 0;
	target = get_sf_attribute(sf,l_string(std_cm,"target"));
	if ( target == 0 )
		f = 1;
	else if ( l_strcmp(target,l_string(std_cm,"file")) == 0 )
		f = 1;
	else if ( l_strcmp(target,l_string(std_cm,"file-n-create")) == 0 )
		f = 2;
	else if ( l_strcmp(target,l_string(std_cm,"net")) == 0 )
		f = 0;
	else 	goto inv_param;

//ss_printf("mxLoad %x %i\n",t,f);
	if ( f ) {
		if ( t->process_node->matrix->p.read_file )
			ret = (*t->process_node->matrix->p.read_file)(t);
		else 	goto no_support;
	}
	else {
		if ( t->process_node->matrix->p.read_net )
			ret = (*t->process_node->matrix->p.read_net)(t);
		else 	goto no_support;
	}
//ss_printf("RET %i\n",ret);
	if ( ret < 0 ) {
		if ( f == 2 ) {
			if ( t->process_node->matrix->p.write_file ) {
				lock_save(t->process_node);
				ret = (*t->process_node->matrix
					->p.write_file)(t);
			}
			else	goto no_support;
		}
		if ( ret < 0 )
			goto matrix_err;
	}
	if ( ret > 0 )
		return matrix_error("mxLoad",s,AME_INTERRUPT,0);
	return 0;
inv_param:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"mxLoad"),
		n_get_string("invalid parameter in mxLoad"));
no_support:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_UNSUPPORT_PROTO,
		l_string(std_cm,"mxLoad"),
		List(n_get_string("not support read_file operation"),
			get_integer((INTEGER64)(int)
				t->process_node->matrix->p.read_file,0),
			get_integer((INTEGER64)(int)
				t->process_node->matrix->p.read_net,0),
			get_integer((INTEGER64)(int)
				t->process_node->matrix->p.write_file,0),
			-1));
matrix_err:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_OBJECT,
		l_string(std_cm,"mxLoad"),
		List(n_get_string("invalid matrix loading"),
			get_integer(ret,0),
			-1));
}





