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


L_CHAR *
compose_path(L_CHAR * d1,L_CHAR * d2)
{
L_CHAR * buf;
int p1,p2;
L_CHAR * ret;
	if ( d2 == 0 || d1 == 0 )
		return 0;
	if ( d2[0] == '/' ) {
		ret = ll_copy_str(d2);
		return ret;
	}
	buf = d_alloc((l_strlen(d1)+l_strlen(d2)+1)*sizeof(L_CHAR));
	l_strcpy(buf,d1);
	p1 = l_strlen(buf);
	if ( p1 > 0 && buf[p1-1] != '/' ) {
		p1 --;
		for ( ; p1 >= 0 && buf[p1] != '/' ; p1 -- );
		if ( p1 < 0 ) {
			d_f_ree(buf);
			ret = ll_copy_str(d2);
			return ret;
		}
		p1 ++;
	}
	for ( ; ; ) {
		if ( *d2 == 0 )
			break;
		if ( *d2 != '.' )
			break;
		d2 ++;
		if ( *d2 == '.' ) {
			d2 ++;
			if ( *d2 != '/' )
				return 0;
			d2 ++;

			p1 --;
			if ( buf[p1] == '/' )
				p1 --;
			for ( ; p1 >= 0 && buf[p1] != '/' ; p1 -- );
			p1 ++;
			if ( p1 <= 0 )
				return 0;
		}
		else {
			return 0;
		}
	}
	l_strcpy(&buf[p1],d2);
	buf = d_re_alloc(buf,(l_strlen(buf)+1)*sizeof(L_CHAR));
	return buf;
}


L_CHAR * 
compose_url(L_CHAR * path1,L_CHAR * path2)
{
URL u1,u2,u3;
L_CHAR * _p;
L_CHAR * ret;
	get_url2(&u1,path1);
	get_url2(&u2,path2);
	zero_url(&u3);
	if ( u1.proto == 0 && u1.server == 0 && u1.port == 0 )
		goto err;
	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 ) {
		}
		u3.resource = ll_copy_str(u2.resource);
		ret = ll_copy_str(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);
		ret = ll_copy_str(path2);
		return ret;
	}
	else	goto err;
err:
	free_url(&u1);
	free_url(&u2);
	free_url(&u3);
	return 0;
}


