/**********************************************************************
 
	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_mxSave(XLISP_ENV * env,XL_SEXP * s,XLISP_ENV * a,XL_SYM_FIELD * sf);

void
init_mxSave(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"mxSave"),
		get_func_prim(xl_mxSave,FO_APPLICATIVE,0,1,1));
}


XL_SEXP *
xl_mxSave(XLISP_ENV * env,XL_SEXP * s,XLISP_ENV * a,XL_SYM_FIELD * sf)
{
MATRIX_TOKEN * t;
int ret;
	t = get_env_work(env);
	if ( t == 0 )
		return 0;
	if ( t->process_node->status != MS_OK )
		goto matrix_err;
	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_suppport;
	if ( ret < 0 )
		goto matrix_err;
	if ( ret > 0 )
		return matrix_error("mxSave",s,AME_INTERRUPT,0);
	return 0;
no_suppport:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_UNSUPPORT_PROTO,
		l_string(std_cm,"mxSave"),
		List(n_get_string("not support write_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,"mxSave"),
		List(n_get_string("invalid matrix saving"),
			get_integer(ret,0),
			-1));
}





