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


HTTP_ELEMENT *
http_parser(HTTP_ENV * he)
{
char ch;
HTTP_ELEMENT * elm, ** elp, * e1;
int ch_ptr;
int ret_cnt;
	elm = 0;
	elp = &elm;
	e1 = 0;
retry:
	if ( s_read(he->key->s,&ch,1) < 1 )
		return 0;
/*
printf("%c",ch);
*/
	switch ( ch ) {
	case ' ':
	case '\t':
		if ( e1 == 0 )
			goto retry;
		*elp = e1;
		elp = &e1->next;
		e1->next = 0;
		e1 = 0;
		goto retry;
	case '\r':
		goto retry;
	case '\n':
		if ( e1 ) {
			*elp = e1;
			e1->next = 0;
		}
		return elm;
	default:
		if ( e1 == 0 ) {
			e1 = d_alloc(sizeof(*e1));
			e1->next = 0;
			e1->data = d_alloc(1);
			e1->data[0] = 0;
			ch_ptr = 0;
		}
		e1->data = d_re_alloc(e1->data,ch_ptr+2);
		e1->data[ch_ptr] = ch;
		ch_ptr ++;
		e1->data[ch_ptr] = 0;
		goto retry;
	}
}

void
free_http_element(HTTP_ELEMENT * el)
{
HTTP_ELEMENT * el1;
	for ( ; el ; ) {
		el1 = el;
		el = el->next;
		if ( el1->data )
			d_f_ree(el1->data);
		d_f_ree(el1);
	}
}
