//
// testing of NeXT style object archiving and
// unarchiving.
//
#import <stdio.h>
#import <stdlib.h>
#import <libc.h>

#import <objc/List.h>

#import "RCString.h"

int
main(int c, char **v)
{
	char            buf[1024];
	RCString       *oBject;
	List           *oList, *oList2;
	int             icObject = c, j;
	id              idSomething;
	NXStream       *spStream;
	NXTypedStream  *spTypedStream;

	gets(buf);

	[(oList = [List alloc]) init];

	if (oList == NULL) {
		fprintf(stderr, "puked allocating List object\n");
		exit(19);
	}

	while (c--) {
		oBject = [RCString newFromString:v[c]];
		idSomething = [oList addObject:oBject];
		printf("added an RCString, \"%s\", 0x%x, %d\n",
			[oBject data], [oBject data], [oBject references]);
		idSomething = [oBject newFromObject];
		[oList addObject:idSomething];
		printf("added an RCString, \"%s\", 0x%x, %d\n",
			[idSomething data], [idSomething data], [idSomething references]);
	}


	printf("Should be %d objects in List, there are %d\n",
		icObject, [oList count]);

	gets(buf);

	printf("writing whole list to \"%s\"\n", *(v + 1));

	spTypedStream = NXOpenTypedStreamForFile(*(v + 1), NX_WRITEONLY);
	if (spTypedStream == NULL) {
		fprintf(stderr, "hosed opening typed stream for \"%s\"\n",
		*(v + 1));
		[[oList freeObjects] free];
		exit(13);
	}

	NXWriteRootObject(spTypedStream, oList);

	printf("wrote all objects.\n");

	NXCloseTypedStream(spTypedStream);

	printf("reading objects back in.\n");

	spStream = NXMapFile(*(v + 1), NX_READONLY);
	if (spStream) {
		spTypedStream = NXOpenTypedStream(spStream, NX_READONLY);
		if (spTypedStream == NULL) {
			fprintf(stderr, "couldn't convert to typedstream\n");
		} else {
			oList2 = NXReadObject(spTypedStream);
			if (oList2 == NULL) {
				fprintf(stderr, "failed to read 2nd list\n");
			} else {
				NXClose(spStream);
				NXCloseTypedStream(spTypedStream);
				printf("%d objects in new list\n", [oList2 count]);
			}
		}
	} else
		fprintf(stderr, "couldn't map in input file\n");

	for (j = 0; j < [oList2 count]; ++j) {
		RCString *oString = [oList2 objectAt:j];
		if (oString)
			printf("added an RCString, \"%s\", 0x%x, refs %d\n",
				[oString data], [oString data], [oString references]);
	}

	printf("first list %s second list\n",
		[oList isEqual:oList2]? "same as" : "different from");
	
	[[oList freeObjects] free];
	[[oList2 freeObjects] free];

	exit(0);
}
