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

void
print_div_str(DIV_STR * str)
{
int i;
	printf("[");
	for ( i = 0; ; i ++ ) {
		if ( str[i].type == DST_STRING )
			printf("%s ",n_string(std_cm,str[i].d.str));
		else	print_div_str(str[i].d.ds);
		if ( str[i].term == 0 )
			break;
	}
	printf("]");
}

void
divide_string_str(DIV_STR * str,L_CHAR * div)
{
DIV_STR * ds;
L_CHAR * ss,* ss1;
int p1,p2,i;
int ptr;
int len;
	ss = str->d.str;
	ds = d_alloc(sizeof(*ds),650);
	ptr = 0;
	len = l_strlen(div);
	for ( p1 = 0 ; ss[p1] ; ) {
		for ( p2 = p1 ; ; p2 ++ ) {
			if ( ss[p2] == 0 )
				break;
			for ( i = 0 ; div[i] ; i ++ ) {
				if ( ss[p2+i] == 0 )
					goto err;
				if ( ss[p2+i] != div[i] )
					goto err;
			}
			break;
		err:	{}
		}
		ds = d_re_alloc(ds,(ptr+1)*sizeof(*ds));
		ds[ptr].d.str = d_alloc((p2-p1+1)*sizeof(L_CHAR),
				651);
		memcpy(ds[ptr].d.str,&ss[p1],(p2-p1)*sizeof(L_CHAR));
		ds[ptr].d.str[p2-p1] = 0;
		ds[ptr].type = DST_STRING;
		ds[ptr].flags = DSF_FREE;
		ptr ++;
		if ( ss[p2] == 0 )
			break;
		p1 = p2 + len;
	}
	if ( *ss == 0 ) {
		ds[0].d.str = d_alloc(sizeof(L_CHAR),
				651);
		ds[0].d.str[0] = 0;
		ds[0].type = DST_STRING;
		ds[0].flags = DSF_FREE;
		ptr = 1;
	}
	for ( i = 0 ; i < ptr ; i ++ )
		ds[i].term = DST_DATA;
	ds[ptr-1].term = DST_TERMINATE;
	if ( str->flags == DSF_FREE )
		d_f_ree(str->d.str);
	str->flags = DSF_FREE;
	str->type = DST_LIST;
	str->d.ds = ds;
}

void
divide_string(DIV_STR * str,L_CHAR * div)
{
int i;
	for ( i = 0 ; ; i ++ ) {
		if ( str[i].type == DST_STRING )
			divide_string_str(&str[i],div);
		else	divide_string(str[i].d.ds,div);
		if ( str[i].term == DST_TERMINATE )
			return;
	}
}


void free_div_str(DIV_STR);

void
free_div_str_list(DIV_STR ds)
{
DIV_STR * dsp;
	for ( dsp = ds.d.ds ; ; dsp ++ ) {
		free_div_str(*dsp);
		if ( dsp->term == DST_TERMINATE )
			break;
	}
}

void
free_div_str(DIV_STR ds)
{
	if ( ds.type == DST_LIST )
		free_div_str_list(ds);
	if ( ds.flags == DSF_FREE )
		d_f_ree(ds.d.str);
}
