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


char *
n_string(CODE_METHOD * cm,L_CHAR * str)
{
char * ret;
int len,ptr;
int i;
void * work;
int rbyte;

	len = 4*l_strlen(str);
	ret = d_alloc(len+1,102);
	ptr = 0;
	work = (*cm->open)();
	for ( ; *str ; str ++ ) {
		if ( len-ptr < cm->max_ret ) {
			len = ptr+cm->max_ret;
			ret = d_re_alloc(ret,len+1);
		}
		rbyte = (*cm->to_external)(&ret[ptr],work,*str);
		if ( rbyte == 0 ) {
			if ( len-ptr < cm->max_ret ) {
				len = ptr+cm->max_ret;
				ret = d_re_alloc(ret,len+1);
			}
			rbyte = (*cm->close)(&ret[ptr],work);
			ptr += rbyte;
			if ( len-ptr < 13 ) {
				len = ptr + 13;
				ret = d_re_alloc(ret,len+1);
			}
			sprintf(&ret[ptr],"&Cx%x;",*str);
			ptr += strlen(&ret[ptr]);
			work = (*cm->open)();
		}
		else {
			ptr += rbyte;
		}
	}
	rbyte = (*cm->close)(&ret[ptr],work);
	ptr += rbyte;
	ret = d_re_alloc(ret,ptr+1);
	ret[ptr] = 0;
	set_buffer(ret);
	return ret;
}
