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

**********************************************************************/


#define STREAM_LIB

#include	"change_endian.h"
#include	"memory_debug.h"
#include	"xlerror.h"
#include	"xl.h"
#include	"stream.h"

extern S_TABLE s_chain_table;
XL_SEXP * xl_PrintChain();

void
init_PrintChain(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"PrintChain"),
		get_func_prim(xl_PrintChain,FO_APPLICATIVE,0,1,3));
}

void
entry_sync()
{
XL_INTERPRETER * xli;
	xli = get_my_xli();
	if ( xli->relay_thread != get_tid() )
		return;
	s_stdout = s_open_chain(xli->id,'o');
	s_stderr = s_open_chain(xli->id,'e');
}

void
exit_sync()
{
	s_flush(s_stdout);
	s_flush(s_stderr);
}

XL_SEXP *
xl_PrintChain(XLISP_ENV * env,XL_SEXP * s,XLISP_ENV * a,
	XL_SYM_FIELD * sf)
{
XL_SEXP * type,* d;
STREAM * out;
L_CHAR * tmp;
int i,size;
L_CHAR * sync;


	sync = get_sf_attribute(sf,l_string(std_cm,"sync"));
	if ( sync ) {
		if ( l_strcmp(sync,l_string(std_cm,"entry")) == 0 )
			entry_sync();
		if ( l_strcmp(sync,l_string(std_cm,"exit")) == 0 )
			exit_sync();
		return 0;
	}


	type = get_el(s,1);
	d = get_el(s,2);
	if ( get_type(type) != XLT_STRING )
		goto type_missmatch;
	if ( get_type(d) != XLT_RAW )
		goto type_missmatch;
	if ( l_strcmp(type->string.data,l_string(std_cm,"o")) == 0 ) {
		out = s_stdout;
	}
	else if ( l_strcmp(type->string.data,
			l_string(std_cm,"e")) == 0 ) {
		out = s_stderr;
	}
	else {
		goto param_error;
	}
	if ( out == 0 )
		goto system_error;
	if ( out->h.tbl == &s_chain_table ) {
		if ( s_write(out,d->raw.data,d->raw.size) < 0 )
			goto system_error;
	}
	else {
		tmp = d_alloc(d->raw.size+sizeof(L_CHAR));
		memcpy(tmp,d->raw.data,d->raw.size);
		size = d->raw.size;
		for ( i = 0 ; size > 0 ; i ++ , size -= sizeof(L_CHAR))
			change_endian_i(tmp[i]);
		tmp[i] = 0;
		if ( s_printf(out,"%ls",tmp) < 0 ) {
			d_f_ree(tmp);
			goto system_error;
		}
		d_f_ree(tmp);
	}
	return get_integer(d->raw.size,0);

type_missmatch:

	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"PrintChain"),
		n_get_string("type missmatch"));
param_error:

	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"PrintChain"),
		n_get_string("invalid parameter"));
system_error:

	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_ACCESS_STREAM,
		l_string(std_cm,"PrintChain"),
		n_get_string("access stream"));

}


