/**********************************************************************
 
	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_DecodeURLString();


void
init_DecodeURLString(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"DecodeURLString"),
		get_func_prim(xl_DecodeURLString,FO_APPLICATIVE,0,2,2));
}

char
_dec_set_q(char ch)
{
	if ( '0' <= ch && ch <= '9' )
		return ch - '0';
	if ( 'a' <= ch && ch <= 'f' )
		return ch - 'a' + 10;
	if ( 'A' <= ch && ch <= 'F' )
		return ch - 'A' + 10;
	return 0;
}

char
dec_set_q(L_CHAR * p)
{
	return (_dec_set_q(p[1]&0xff)<<4)|_dec_set_q(p[2]&0xff);
}

XL_SEXP *
xl_DecodeURLString(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * str;
char * _str, * _ret, * q;
int len,i;
XL_SEXP * ret;
L_CHAR * p;
	str = get_el(s,1);
	if ( get_type(str) != XLT_STRING )
		goto type_missmatch;
	len = l_strlen(str->string.data);
	_ret = d_alloc(len+1);
	p = str->string.data;
	q = _ret;
	for ( ; *p ; ) {
		if ( *p == '%' ) {
			*q ++ = dec_set_q(p);
			p += 3;
		}
		else	*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,"DecodeURLString"),
		n_get_string("type missmatch"));
}


