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

XL_SEXP * xl_URLStringCode();


void
init_URLStringCode(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"URLStringCode"),
		get_func_prim(xl_URLStringCode,FO_APPLICATIVE,0,2,2));
}

char *
set_q(char * q,char ch)
{
static char fg[17] = "0123456789ABCDEF";
	q[0] = '%';
	q[1] = fg[(ch>>4)&0xf];
	q[2] = fg[ch&0xf];
	return q + 3;
}

XL_SEXP *
xl_URLStringCode(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * str;
char * _str, * _ret, * p, * q;
int len,i;
XL_SEXP * ret;
	str = get_el(s,1);
	if ( get_type(str) != XLT_STRING )
		goto type_missmatch;
	_str = n_string(std_cm,str->string.data);
	len = strlen(_str)*4;
	_ret = d_alloc(len);
	p = _str;
	q = _ret;
	for ( ; *p ; *p ++ ) {
		if ( *p < 0x20 ) {
			q = set_q(q,*p);
		}
		else switch ( *p ) {
		case ' ':
		case '/':
		case '?':
		case '*':
		case '#':
		case '%':
		case ':':
			q = set_q(q,*p);
			break;
		default:
			*q ++ = *p;
		}
	}
	*q = 0;
	ret = n_get_string(_ret);
	d_f_ree(_ret);
	return ret;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"URLStringCode"),
		n_get_string("type missmatch"));
}


