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

XL_SEXP * xl_GetHTMLQuery();

void
init_GetHTMLQuery(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"GetHTMLQuery"),
		get_func_prim(xl_GetHTMLQuery,FO_APPLICATIVE,0,2,2));
}


XL_SEXP *
xl_GetHTMLQuery(XLISP_ENV * e,XL_SEXP * s)
{
XL_SEXP * str, * ret;
unsigned char * buf;
int i,j;
int len;
unsigned char * out;
	str = get_el(s,1);
	if ( get_type(str) != XLT_STRING )
		goto type_missmatch;
	buf = n_string(std_cm,str->string.data);
	len = strlen(buf);
	out = d_alloc(len*4+1,23);
	j = 0;
	for ( i = 0 ; i < len ; i ++ ) {
		if ( '0' <= buf[i] && buf[i] <= '9' )
			goto no_conv;
		if ( 'a' <= buf[i] && buf[i] <= 'z' )
			goto no_conv;
		if ( 'A' <= buf[i] && buf[i] <= 'Z' )
			goto no_conv;
	conv:
		sprintf(&out[j],"%%%02X",buf[i]);
		j += 3;
		continue;
	no_conv:
		out[j] = buf[i];
		j ++;
	}
	out[j] = 0;
	ret = n_get_string(out);
	d_f_ree(out);
	return ret;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"GetHTMLQuery"),
		List(n_get_string(
			"type missmatch"),
			-1));
}
