/*****
 NAME
	carray-test.m - test program for CArray class
 VERSION
	$Id$
 CHANGELOG
	$Log$
 */

#include <coconut/carray.h>
#include <coconut/cindtstream.h>
#include <coconut/fobject.h>
#include <stdio.h>
#include <stdlib.h>

const void * printElm(const void * data, const void * p1, const void * p2)
{
	printf("v = %d\n", *((int *) data)) ;
	return NULL ;
}

void print_array(const char * msg, id <PIndentStream> stream, 
  id <PDataArray> arr)
{
	int *		first ;
	int *		last ;

	printf("%s -----\n", msg);
	printf("elm num : %d\n", [arr count]) ;
	fflush(stdout) ;

	[arr foreach: &printElm with: NULL with: NULL] ;
	[stream flush] ;

	first = (int *) [arr first] ; last = (int *) [arr last] ;

	if(first)
		printf("1st : %d\n", *first) ;
	if(last)
		printf("last : %d\n", *last) ;
	printf("end of %s -----\n", msg);
}

void appendArray(id <PDataArray> arr, int i)
{
	[arr append: &i] ;
}

void prependArray(id <PDataArray> arr, int i)
{
	[arr prepend: &i] ;
}

int compareIntPtr(const void * p1, const void * p2)
{
	return *((int *) p1) - *((int *) p2) ;
}

int main()
{
	id <PDataArray> 	arr ;
	id <PIndentStream>	stream ;
	int			cmpval ;
	int *			ptr ;
	u_int			idx ;

	printf("*** test program for CArray class\n");
	arr = [[CArray alloc] initArray: sizeof(int) dealloc: 
	  &remove_nothing_func] ;
	stream = [[CIndtStream alloc] init] ;

	print_array("initial state", stream, arr) ;

	appendArray(arr, 0) ;
	print_array("1st data added", stream, arr) ;

	appendArray(arr, 1) ;
	print_array("2nd data added", stream, arr) ;

	appendArray(arr, 2) ;
	print_array("3rd data added", stream, arr) ;

	appendArray(arr, 3) ;
	print_array("4th data added", stream, arr) ;

	prependArray(arr, 4) ;
	prependArray(arr, 5) ;
	print_array("4th and 5th data set", stream, arr) ;

	ptr = (int *) [arr item: 1] ; printf("slot[1] = %d\n", *ptr) ; 
	ptr = (int *) [arr item: 2] ; printf("slot[2] = %d\n", *ptr) ; 

	cmpval = 4 ;
	if([arr search: &idx compareFunc: &compareIntPtr by: &cmpval]){
		printf("search %d -> FOUND in %d \n", cmpval, idx) ;
	} else {
		printf("search %d -> NOT FOUND, this is error.\n", cmpval) ;
	}

	[stream flush] ;
	[stream release] ;
	[arr release] ;
	printf("bye.\n") ;
	exit(0) ;
}

