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

void
make_regular(L_CHAR ** str)
{
	if ( (*str)[0] )
		*str = d_re_alloc(*str,(l_strlen(*str)+1)*sizeof(L_CHAR));
	else {
		d_f_ree(*str);
		*str = 0;
	}
}

int
get_url(URL *	ret,
	L_CHAR * url)
{
int p1,rp,hp;
L_CHAR * p,* h,* d,* r;
int port_buf;
int len;
int er;
	er = 0;
	p1 = 0;
	len = l_strlen(url)+1;
	p = d_alloc(len*sizeof(L_CHAR),121);
	h = d_alloc(len*sizeof(L_CHAR),122);
	d = d_alloc(len*sizeof(L_CHAR),123);
	r = d_alloc(len*sizeof(L_CHAR),124);
	p[0] = 0;
	h[0] = 0;
	d[0] = 0;
	r[0] = 0;
	ret->proto = p;
	ret->server = h;
	ret->port = GBP_PORT;
	ret->db = d;
	ret->resource = r;
	ret->user = 0;
	ret->passwd = 0;
start:
	rp = 0;
	switch ( url[p1++] ) {
	case 0:
		goto err;
	case '/':
		goto d1;
	}
pr1:
	switch ( url[p1++] ) {
	case 0:
		l_strcpy(ret->resource,url);
		goto end;
	case ':':
		memcpy(ret->proto,url,(p1-1)*sizeof(L_CHAR));
		ret->proto[p1-1] = 0;
		break;
	case '/':
		hp = 0;
		rp = p1;
		goto d2;
	default:
		goto pr1;
	}
pr2:
	switch ( url[p1++] ) {
	case '/':
		break;
	case 0:
	default:
		goto err;
	}
pr3:
	switch ( url[p1++]) {
	case '/':
		break;
	case 0:
	default:
		goto err;
	}
h1:
	switch ( url[p1++] ) {
	case 0:
		goto err;
	case '/':
		goto err;
	default:
		*h++ = url[p1-1];
	}
h2:
	switch ( url[p1++] ) {
	case '/':
		*h = 0;
		ret->port = GBP_PORT;
		goto d1;
	case ':':
		*h = 0;
		break;
	case 0:
		goto err;
	default:
		*h++ = url[p1-1];
		goto h2;
	}
port1:
	port_buf = 0;
port2:
	if ( url[p1] == '/' ) {
		p1 ++;
		ret->port = port_buf;
	}
	else if ( '0' <= url[p1] && url[p1] <= '9' ) {
		port_buf *= 10;
		port_buf += url[p1]-'0';
		p1 ++;
		goto port2;
	}
	else	goto err;
d1:
	rp = p1;
	hp = p1;
d2:
	switch ( url[p1++] ) {
	case 0:
		goto err;
	case '/':
		goto err;
	default:
		break;
	}
d3:
	switch ( url[p1++] ) {
	case 0:
		if ( hp < rp ) {
			memcpy(d,&url[hp],(rp-hp-1)*sizeof(L_CHAR));
			d[rp-hp-1] = 0;
		}
		l_strcpy(r,&url[rp]);
		goto end;
	case '/':
		rp = p1;
		goto d2;
	default:
		goto d3;
	}
err:
	er = -1;
end:

	make_regular(&ret->server);
	make_regular(&ret->proto);
	make_regular(&ret->db);
	make_regular(&ret->resource);
	return er;
}

