/*****
 NAME
 	cwordlist.h - the string splited by spaces
 VERSION
 	$Id$
 CHANGELOG
 	$Log$
 */

#include <coconut/cwordlist.h>
#include <coconut/cidlist.h>
#include <coconut/cstring.h>
#include <stdlib.h>
#include <ctype.h>

#define	INT(C)		((int) C)

@implementation CWordList

- init
{
	word_list = [[CIdList alloc] init] ;
	return [super init] ;
}

- initWordList: (id <PString>) str keepSpaces: (boolean) dokeep
{
	word_list = [[CIdList alloc] init] ;
	[self setStr: str keepSpaces: dokeep] ;
	return [super init] ;
}

- initWordList: (const utf8_char *) str length: (u_int) len
    keepSpaces: (boolean) dokeep
{
	word_list = [[CIdList alloc] init] ;
	[self setPtr: str length: len keepSpaces: dokeep] ;
	return [super init] ;
}

- (void) dealloc
{
	[word_list release] ;
	[super dealloc] ;
}

- (u_int) setStr: (id <PString>) str keepSpaces: (boolean) dokeep
{
	return [self setPtr: [str ptr] length: [str length]
	  keepSpaces: dokeep] ;
}

- (u_int) setPtr: (const utf8_char *) ptr length: (u_int) len
    keepSpaces: (boolean) dokeep
{
	if(dokeep)
		return [self setWithSpaces: ptr length: len] ;
	else
		return [self setWithoutSpaces: ptr length: len] ;
}

- (u_int) setWithoutSpaces: (const utf8_char *) ptr length: (u_int) len
{
	const utf8_char *	last ;
	utf8_char *		buf ;
	utf8_char *		bufp ;
	id <PString>		str ;

	if(ptr == NULL || len == 0)
		return 0 ;

	[word_list clear] ;

	buf = alloca(sizeof(utf8_char) * len) ;
	last = ptr + len ;
	do {
		/* skipspaces */
		for( ; ptr<last ; ptr++)
			if(!isspace(INT(*ptr)))
				break ;
		if(ptr < last){
			bufp = buf ; *(bufp++) = *(ptr++) ;
			for( ; ptr<last ; ptr++){
				if(isspace(INT(*ptr)))
					break ;
				else {
					*(bufp++) = *ptr ;
				}
			}
			*(bufp++) = '\0' ;
			str = [[CString alloc] initStringWithPtr: buf 
			  length: bufp-buf];
			[word_list append: str] ;
			[str release] ;
		}
	} while(ptr < last) ;
	return [word_list count] ;
}

- (u_int) setWithSpaces: (const utf8_char *) ptr length: (u_int) len
{
	const utf8_char *	last ;
	utf8_char *		buf ;
	utf8_char *		bufp ;
	utf8_char 		c ;
	id <PString>		str ;

	if(ptr == NULL || len == 0)
		return 0 ;

	[word_list clear] ;

	buf = alloca(sizeof(utf8_char) * len) ;
	last = ptr + len ;
	c = *(ptr++) ;
	do {
		bufp = buf ; *(bufp++) = c ;
		if(isspace(INT(c))){
			while(ptr<last){
				c = *(ptr++) ;
				if(isspace(INT(c))){
					*(bufp++) = c ;
				} else
					break ;
			}
		} else {
			while(ptr < last){
				c = *(ptr++) ;
				if(!isspace(INT(c))){
					*(bufp++) = c ;
				} else
					break ;
			}
		}
		*bufp = '\0' ;
		str = [[CString alloc] initStringWithPtr: buf length: bufp-buf];
		[word_list append: str] ;
		[str release] ;
	} while(ptr < last) ;
	return [word_list count] ;
}

- (id <PString>) item: (u_int) no
{
	return (id <PString>) [word_list item: no] ;
}

- clear
{
	return [word_list clear] ;
}

@end

