//
//  StringStorage.h
//
//  Lennart Lovstrand, Rank Xerox EuroPARC, August 1991.
//

#import "StringStorage.h"
#import <stdlib.h>			// for free() etc
#import <strings.h>			// for strcasecmp()
#import <objc/hashtable.h>		// for NXCopyStringBuffer()

#define str_copy(str)	((str == NULL) ? NULL : NXCopyStringBuffer(str))
#define str_free(str)	{if (str != NULL) free(str);}

static int (*comparefn)(char *x, char *y);

static int docompare(void *x, void *y)
{
	return (*comparefn)(*(char **) x, *(char **) y);
}

@implementation StringStorage

- init;
{
	return [self initCount: 0];
}

- initCount: (int) count;
{
	return [self initCount: count elementSize: sizeof(char *)
		description: "!"];
}

- addElement: (char *) elem
{
	char *p = str_copy(elem);
	return [super addElement: &p];
}

- (char *) elementAt: (int) i
{
	return *(char **) [super elementAt: i];
}

- insert: (char *) elem at: (int) i
{
	char *p = str_copy(elem);
	return [super insert: &p at: i];
}

- removeAt: (int) i
{
	str_free([self elementAt: i]);
	return [super removeAt: i];
}

- replace: (char *) elem at: (int) i
{
	char *p = str_copy(elem);
	str_free([self elementAt: i]);
	return [super replace: &p at: i];
}

- sortUsing: (int (*)()) predfn
{
	char **strings;
	int i, count;

	count = [self count];
	strings = (char **) malloc(count * sizeof(char *));

	for (i = 0; i < count; i++)
	strings[i] = [self elementAt: i];

	comparefn = predfn;
	qsort(strings, count, sizeof(char *), docompare);

	for (i = 0; i < count; i++)
	[super replace: &strings[i] at: i];

	free(strings);

	return self;
}

- sort
{
	return [self sortUsing: strcasecmp];
}

@end
