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

typedef struct safety_entity {
	char		ch;
	char *		ent;
} SAFETY_ENTITY;

SAFETY_ENTITY se[] = {
	{'&' , "&amp;"},
	{'<' , "&lt;"},
	{'\\' ,"\\\\"},
	{'\n' ,"\\n"},
	{'\r' ,"\\n"},
	{0,0}
};

L_CHAR *
xx_safety_string(L_CHAR * str,
	char * __file,int __line)
{
L_CHAR * ret;
int i,cnt,len;
L_CHAR ch;
int max;
SAFETY_ENTITY * sep;
L_CHAR * p;
char * q;
	max = 0;
	for ( i = 0 ; se[i].ch ; i ++ ) {
		len = strlen(se[i].ent);
		if ( max < len )
			max = len;
	}
	cnt = 0;
	for ( i = 0 ; str[i] ; i ++ ) {
		for ( sep = &se[0] ; sep->ch ; sep ++ )
			if ( sep->ch == str[i] )
				cnt ++;
	}
	len = i;

	ret = xx_d_alloc((len + max*cnt + 1)*sizeof(L_CHAR),__file,__line);
	p = ret;
	for ( i = 0 ; i < len ; i ++ ) {
		ch = str[i];
		sep = &se[0];
		for ( ; sep->ch ; sep ++ ) {
			if ( sep->ch == ch )
				goto next;
		}
		*p ++ = ch;
		continue;
	next:
		for ( q = sep->ent ; *q ; )
			*p++ = *q++;
	}
	*p = 0;
	return ret;
}
