/**********************************************************************
 
	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"

XL_SEXP * xl_ComposeURL();

void
init_ComposeURL(XLISP_ENV * env)
{
	set_env(env,l_string(std_cm,"ComposeURL"),
		get_func_prim(xl_ComposeURL,FO_APPLICATIVE,0,3,3));
}

XL_SEXP *
xl_ComposeURL(XLISP_ENV * env,XL_SEXP * s)
{
XL_SEXP * path1,* path2;
URL u1,u2,u3;
L_CHAR * _p;
XL_SEXP * ret;
	path1 = get_el(s,1);
	if ( get_type(path1) != XLT_STRING )
		goto type_missmatch;
	path2 = get_el(s,2);
	if ( get_type(path2) != XLT_STRING )
		goto type_missmatch;
	get_url2(&u1,path1->string.data);
	get_url2(&u2,path2->string.data);
	zero_url(&u3);
	if ( u1.proto == 0 && u1.server == 0 && u1.port == 0 )
		goto invalid_param;
	if ( u2.proto == 0 && u2.server == 0 && u2.port == 0 ) {
		u3.proto = ll_copy_str(u1.proto);
		u3.server = ll_copy_str(u1.server);
		u3.port = u1.port;
		if ( u2.db == 0 )
			u3.db = ll_copy_str(u1.db);
		else	u3.db = compose_path(u1.db,u2.db);
		if ( u3.db == 0 )
			goto invalid_param;
		u3.resource = ll_copy_str(u2.resource);
		ret = get_string(get_url_str2(&u3));
		free_url(&u1);
		free_url(&u2);
		free_url(&u3);
		return ret;
	}
	else if ( u2.proto && u2.server && u2.port ) {
		free_url(&u1);
		free_url(&u2);
		free_url(&u3);
		return path2;
	}
	else	goto invalid_param;
type_missmatch:
	return get_error(
		s->h.file,
		s->h.line,
		XLE_SEMANTICS_TYPE_MISSMATCH,
		l_string(std_cm,"ComposeURL"),
		0);
invalid_param:
	free_url(&u1);
	free_url(&u2);
	free_url(&u3);
	return get_error(
		s->h.file,
		s->h.line,
		XLE_PROTO_INV_PARAM,
		l_string(std_cm,"ComposeURL"),
		n_get_string("invalid path argments"));
}


