#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "ztypes.h"
#include "pickle.h"

/* This file is the source code for the PICKLE Reader Library. 
	Version 1. */

/* This library is a very simple one, intended for use in interpreters
	that want to support reading PICKLE files. This library does not
	have functions to write or analyze PICKLE files, just to read them
	in the rather limited way that interpreters should want to. */

#ifdef BIG_END_MODE
static char contentmessage[] = "\nPICKLE Reader Library 1.0.0 (big-endian)\n";
#endif

#ifdef LITTLE_END_MODE
static char contentmessage[] = "\nPICKLE Reader Library 1.0.0 (little-endian)\n";
#endif

#ifdef __STDC__
static char contentmessage2[] = "\nLibrary compiled with __STDC__\n";
#else
static char contentmessage2[] = "\nLibrary compiled without __STDC__\n";
#endif

#define pik_InitedMagic (0x18328EEB)

#if defined(BIG_END_MODE) || defined(LITTLE_END_MODE)

#ifdef BIG_END_MODE
#define pikNative(v) (v)
#endif

#ifdef LITTLE_END_MODE
#define pikNative(v) (   \
	  ((((long)(v)) >> 24) & 0x000000ff)   \
	| ((((long)(v)) >> 8)  & 0x0000ff00)   \
	| ((((long)(v)) << 8)  & 0x00ff0000)   \
	| ((((long)(v)) << 24) & 0xff000000)   \
)
#endif

#else

#define pikNative(v) (0)

#endif

struct pikDescriptorData {
	pikType use;
	pikLong number;
	pikType format;
	pikLong formatversion;
	pikLong startpos;
	pikLong length;
	
	void *data; /* (non-Mac systems) */
	/*Handle data;*/ /* (Mac only) */
};
typedef struct pikDescriptorData pikDescriptor;

struct pikMapData {
	pikLong inited; /* contains pik_InitedMagic while the map is in existence */
	FILE *file; /* (non-Mac systems) */
	/*short file;*/ /* (Mac only) */
	
	pikLong numchunks;
	pikLong filelength;
	
	pikDescriptor *chunks; /* pointer to an array of descriptors */
};
typedef struct pikMapData pikMap;

#ifdef __STDC__
short pikIsPickleHeader(char *header)
#else
short pikIsPickleHeader(header)
char *header;
#endif
{
	if (header[0] == 0x70
		&& header[1] == 0x69
		&& header[2] == 0x6b
		&& header[3] == 0x6c) {
		return TRUE;	
	}
	else {
		return FALSE;
	}
}

#ifdef __STDC__
pikErr pikCreateMap(FILE *file, pikMapPtr *newmap)
#else
pikErr pikCreateMap(file, newmap)
FILE *file;
pikMapPtr *newmap;
#endif
{
	pikMapPtr map;
	pikLong buffer[6];
	int err;
	long count;
	long lx;
	pikLong numchunks;
	pikLong filelength;
	pikDescriptor *chunks;
	
	if (sizeof(pikLong) != 4) {
		return pikerr_WrongSizeInts;
	}
	{
		pikLong testval;
		unsigned char *cx;
		cx = (unsigned char *)(&testval);
		cx[0] = 0x12;
		cx[1] = 0x34;
		cx[2] = 0x56;
		cx[3] = 0x78;
		if (pikNative(testval) != 0x12345678) {
			return pikerr_WrongEndian;
		}
	}
	
	if (!file) {
		return pikerr_BadOption;
	}
	
	err = fseek(file, 0, 0);
	if (err) {
		return pikerr_CantRead;
	}
	
	count = fread(buffer, 1, 16, file);
	if (count != 16) {
		return pikerr_CantRead;
	}
	
	if (pikNative(buffer[0]) != pikMakeType('p', 'i', 'k', 'l')
		|| pikNative(buffer[1]) != 1) {
		return pikerr_NotAMap;
	}
	
	numchunks = pikNative(buffer[2]);
	filelength = pikNative(buffer[3]);
	
	err = fseek(file, 0, 2);
	if (err) {
		return pikerr_CantRead;
	}
	count = ftell(file);
	if (count == (-1)) {
		return pikerr_CantRead;
	}
	if (count != filelength) {
		return pikerr_NotAMap;
	}
	err = fseek(file, 16, 0);
	if (err) {
		return pikerr_CantRead;
	}
		
	map = (pikMapPtr)malloc(sizeof(pikMap));
	if (!map) {
		return pikerr_Memory;
	}
	chunks = (pikDescriptor *)malloc(sizeof(pikDescriptor) * numchunks);
	if (!chunks) {
		free(map);
		return pikerr_Memory;
	}
	
	for (lx=0; lx<numchunks; lx++) {
	
		count = fread(buffer, 1, 24, file);
		if (count != 24) {
			free(chunks);
			free(map);
			return pikerr_CantRead;
		}
		
		chunks[lx].use = pikNative(buffer[0]);
		chunks[lx].number = pikNative(buffer[1]);
		chunks[lx].format = pikNative(buffer[2]);
		chunks[lx].formatversion = pikNative(buffer[3]);
		chunks[lx].startpos = pikNative(buffer[4]);
		chunks[lx].length = pikNative(buffer[5]);
		chunks[lx].data = NULL;
	}
	
	map->chunks = chunks;
	map->numchunks = numchunks;
	map->filelength = filelength;
	map->file = file;
	map->inited = pik_InitedMagic;
	
	*newmap = map;
	return pikerr_None;
}

#ifdef __STDC__
pikErr pikDestroyMap(pikMapPtr map)
#else
pikErr pikDestroyMap(map)
pikMapPtr map;
#endif
{
	pikLong lx;
	pikDescriptor *desc;
	
	if (!map || !map->chunks || map->inited != pik_InitedMagic) {
		return pikerr_NotAMap;
	}
	
	for (lx=0; lx<map->numchunks; lx++) {
		desc = (&(map->chunks[lx]));
		if (desc->data) {
			free(desc->data);
			desc->data = NULL;
		}
	}

	map->inited = 0;
	free(map->chunks);
	free(map);

	return pikerr_None;
}

#ifdef __STDC__
pikErr pikFindChunk(pikMapPtr map, pikType use, pikLong number, 
	short numformats, pikFormat *formatlist, pikChunkID *idfound)
#else
pikErr pikFindChunk(map, use, number, numformats, formatlist, idfound)
pikMapPtr map;
pikType use;
pikLong number;
short numformats;
pikFormat *formatlist;
pikChunkID *idfound;
#endif
{
	pikDescriptor *desc;
	pikLong id, bestid;
	short fx, sofar;
	
	if (!map || !map->chunks || map->inited != pik_InitedMagic) {
		return pikerr_NotAMap;
	}
	
	if (numformats < 0 || (numformats > 0 && !formatlist)) {
		return pikerr_BadOption;
	}
	
	sofar = (-1);
	for (id=0, desc=map->chunks; id<map->numchunks; id++, desc++) {
		if (desc->use == use && desc->number == number) {
			if (numformats == 0) {
				if (idfound)
					*idfound = id;
				return pikerr_None;
			}
			for (fx=0; fx<numformats; fx++) {
				if (desc->format == formatlist[fx].name && 
					desc->formatversion == formatlist[fx].version) {
					if (sofar < 0 || fx < sofar) {
						sofar = fx;
						bestid = id;
					}
				}
			}
		}
	}
	
	if (sofar >= 0) {
		if (idfound)
			*idfound = bestid;
		return pikerr_None;
	}
	
	if (idfound)
		*idfound = pik_NoChunk;
	return pikerr_NotFound;
}

#ifdef __STDC__
pikErr pikLoadChunk(pikMapPtr map, pikChunkID id, short method, pikChunk *found)
#else
pikErr pikLoadChunk(map, id, method, found)
pikMapPtr map;
pikChunkID id;
short method;
pikChunk *found;
#endif
{
	pikDescriptor *desc;
	
	if (!map || !map->chunks || map->inited != pik_InitedMagic) {
		return pikerr_NotAMap;
	}
	
	if (id < 0 || id >= map->numchunks) {
		return pikerr_BadOption;
	}	
	if (!found) {
		return pikerr_BadOption;
	}
	
	desc = (&(map->chunks[id]));
	switch (method) {
		case pikmethod_DontRead:
			break;
		case pikmethod_FilePos:
			found->data.startpos = desc->startpos;
			break;
		case pikmethod_Memory:
			if (!desc->data) {
				long count;
				int err;
				desc->data = malloc(desc->length);
				if (!desc->data) {
					return pikerr_Memory;
				}
				err = fseek(map->file, desc->startpos, 0);
				if (err) {
					return pikerr_CantRead;
				}
				count = fread(desc->data, 1, desc->length, map->file);
				if (count != desc->length) {
					return pikerr_CantRead;
				}
			}
			found->data.ptr = desc->data;
			break;
		default:
			return pikerr_BadOption;
	}

	found->length = desc->length;
	found->format.name = desc->format;
	found->format.version = desc->formatversion;
	
	return pikerr_None;
}

#ifdef __STDC__
pikErr pikUnloadChunk(pikMapPtr map, pikChunkID id)
#else
pikErr pikUnloadChunk(map, id)
pikMapPtr map;
pikChunkID id;
#endif
{
	pikDescriptor *desc;
	
	if (!map || !map->chunks || map->inited != pik_InitedMagic) {
		return pikerr_NotAMap;
	}
	
	if (id < 0 || id >= map->numchunks) {
		return pikerr_BadOption;
	}	
	
	desc = (&(map->chunks[id]));
	
	if (desc->data) {
		free(desc->data);
		desc->data = NULL;
		return pikerr_None;
	}
	else {
		return pikerr_NotFound;
	}
}

