/*****
 NAME
	clist-test.m - test program for CList class
 VERSION
	$Id$
 CHANGELOG
	$Log$
 */

#include <coconut/clist.h>
#include <coconut/cmemalloc.h>
#include <coconut/cindtstream.h>
#include <coconut/fbasic.h>
#include <stdio.h>
#include <stdlib.h>

static void deallocFunc(void * ptr)
{
	[CMemAlloc free: ptr] ;
}

const void * printElm(const void * data, const void * p1, const void * p2)
{
	id <PIndentStream>	stream = (id <PIndentStream>) p1 ;

	fflush(stdout) ;
	[stream putFormat: "element : \"%s\"\n", data] ;
	[stream flush] ;
	return NULL ;
}

void print_list(const char * msg, id <PIndentStream> stream, id <PDataList> list)
{
	const char * data ;
	printf("----- %s\n", msg) ;
	printf("elm num : %d\n", [list count]) ;
	[list foreach: &printElm with: stream with: NULL] ;
	data = (const char *) [list currentItem] ;
	printf("current data : %s\n", data ? data : "<null>") ;
	printf("----- end of %s\n", msg) ;
}

void print_each_elm(id <PDataList> list){
	const char *	str ;
	int		i ;

	printf("normal order:\n") ;
	str = (const char *) [list moveToHead] ; i = 0 ; 
	while(str){
		printf("[%d] \"%s\"\n", i, str) ;
		str = (const char *) [list moveNext] ;
		i++ ;
	}

	printf("reverse order:\n") ;
	str = (const char *) [list moveToTail] ; i-- ;
	while(str){
		printf("[%d] \"%s\"\n", i, str) ;
		str = (const char *) [list movePrev] ;
		i-- ;
	}
}

void print_each_elm2(id <PDataList> list){
	const char *	str ;
	u_int		i ;

	printf("indexed print:\n") ;
	for(i=0 ; (str = (const char *) [list item: i]) != NULL ; i++)
		printf("<%d> \"%s\"\n", i, str) ;
}

int main()
{
	id <PDataList>		list ;
	id <PIndentStream>	stream ;

	printf("*** test program for CList class\n");
	list = [[CList alloc] initList: &deallocFunc] ;
	stream = [[CIndtStream alloc] init] ;

	print_list("initial state", stream, list) ;

	[list append: strdup("hello, this is 1st data")] ;
	[list append: strdup("good morning, 2nd data !!")] ;
	print_list("2 data are appended", stream, list) ;

	[list prepend: strdup("hi, this is 3rd data")] ;
	[list prepend: strdup("whar do you think about 4th data?")];
	print_list("2 data are prepended", stream, list) ;

	print_each_elm(list);

	printf("remove 1st line:\n") ;
	[list moveToHead] ; [list remove] ;
	print_each_elm(list);

	printf("remove 3rd line:\n") ;
	[list moveNext] ; [list remove] ;
	print_each_elm(list);

	printf("remove last line:\n") ;
	[list moveToTail] ; [list remove] ;
	print_each_elm(list);

	printf("add lines:\n") ;
	[list add: strdup("additional line")] ;
	[list add: strdup("more additional line")] ;
	print_each_elm(list);

	printf("insert lines:\n") ;
	[list insert: strdup("inserted line")] ;
	[list moveToTail] ;
	[list insert: strdup("more inserted line")] ;
	print_each_elm(list);

	[list clear] ;
	print_list("cleared", stream, list) ;

	[list release] ;
	printf("bye.\n");
	return 0 ;
}

