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


L_CHAR
get_proper_code(XL_SEXP * s,int str_max)
{
L_CHAR * encoding;
L_CHAR ret;
CS_WORK w;
CS_LIST * cs;
CODE_METHOD * cm;
int ret_cnt;
XL_SEXP * ss;
	for ( ss = s; get_type(ss) == XLT_PAIR ; ss = car(ss) );
	if ( get_type(ss) != XLT_SYMBOL )
		goto next1;
	if ( l_strcmp(ss->symbol.data,l_string(std_cm,"?xl")) == 0 )
		goto ok1;
	if ( l_strcmp(ss->symbol.data,l_string(std_cm,"?xml")) == 0 )
		goto ok1;
	goto next1;
ok1:
	encoding = get_sf_attribute(ss->symbol.field,
			l_string(std_cm,"encoding"));
	if ( encoding == 0 )
		goto next1;
	ret = search_lccode(n_string(std_cm,encoding));
	if ( ret == LCC_ERROR )
		goto next1;
	return ret;
next1:
	w.str_max = str_max;
	w.lst = 0;
	if ( str_max == -2 )
		cs_sexp(&w,s);
	else	cs_sexp_on_mem(&w,s);
	if ( w.lst == 0 )
		return LCC_ASCII;
	ret_cnt = 0;
	ret = LCC_ERROR;
	for ( cs = w.lst ; cs ; cs = cs->next )
		if ( cs->count > ret_cnt ) {
			ret_cnt = cs->count;
			ret = cs->code;
		}
	free_cs_work(&w);
	cm = search_cm_by_main_code(ret);
	if ( cm == 0 )
		er_panic("get_code(1)");
	return cm->lccode;
}
