/**********************************************************************
 
	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	"xl.h"
#include	"long_char.h"

void
init__q_xml(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"?xml"),
		get_func_prim(_q_xml,FO_APPLICATIVE,0,1,1));
	set_env(env,l_string(std_cm,"?xl"),
		get_func_prim(_q_xml,FO_APPLICATIVE,0,1,1));
}

void
_q_xml_encoding(XL_SEXP * s,L_CHAR * code)
{
CODE_METHOD * cm;
XL_FILE * f;
	cm = search_cm(n_string(std_cm,code));
	if ( cm == 0 )
		cm = std_cm;
	f = s->h.file;
	(*f->cm->close)(0,f->cm_work);
	f->cm = cm;
	f->cm_work = (*f->cm->open)();
}

/*
void
_q_xml_encoding_st(STREAM * st,L_CHAR * code)
{
CODE_METHOD * cm;
	cm = search_cm(n_string(std_cm,code));
	if ( cm == 0 )
		cm = std_cm;
	s_set_cm(st,cm);
}
*/

void
set_encoding_st(STREAM * st,L_CHAR * code)
{
CODE_METHOD * cm;
	cm = search_cm(n_string(std_cm,code));
	if ( cm == 0 )
		cm = std_cm;
	s_set_cm(st,cm);
}


XL_SEXP *
_q_xml(XLISP_ENV * env,XL_SEXP * s,XLISP_ENV * args_env,XL_SYM_FIELD * sf)
{
XL_INTERPRETER * xli;
L_CHAR * chain;
XL_SYM_FIELD * sff;

	xli = get_my_xli();
	if ( xli->front_thread != get_tid() )
		return 0;
	if ( s->h.file == 0 )
		return 0;
	if ( s->h.file->st == 0 )
		return 0;
	if ( s->h.file->st != xli->inp )
		return 0;
	sff = sf;
	for ( ; sf ; sf = sf->next ) {
		if ( l_strcmp(sf->name,l_string(std_cm,"encoding")) == 0 )
			_q_xml_encoding(s,sf->data);
	}
	sf = sff;
	chain = get_sf_attribute(sf,l_string(std_cm,"stdout"));
	if ( chain ) {
		if ( l_strcmp(chain,l_string(std_cm,"chain")) == 0 ) {
			s_stdout = s_open_chain(xli->id,'o');
		}
		else {
			s_stdout = s->h.file->st;
		}
	}
	chain = get_sf_attribute(sf,l_string(std_cm,"stderr"));
	if ( chain ) {
		if ( l_strcmp(chain,l_string(std_cm,"chain")) == 0 ) {
			s_stderr = s_open_chain(xli->id,'e');
		}
		else {
			s_stderr = s->h.file->st;
		}
	}
	return 0;
}
