#include <stdio.h>
#include <string.h>
#include "unzip.h"
#include "psp/psp.h"

static unzFile unzfile = NULL;

static char basedir[MAX_PATH];
char *basedirend;

int zip_open(const char *path)
{
	if ((unzfile = unzOpen(path)) != NULL)
		return (int)unzfile;

	strcpy(basedir, path);

	basedirend = basedir + strlen(basedir);
	*basedirend++ = '/';

	return -1;
}


int zip_close(void)
{
	if (unzfile)
	{
		unzClose(unzfile);
		unzfile = NULL;
	}
}


int zopen(const char *filename)
{
	if (unzfile == NULL)
	{
		FILE *fp;

		strcpy(basedirend, filename);
		return (fp = fopen(basedir, "rb")) ? (int)fp : -1;
	}

	if (unzLocateFile(unzfile, filename, 0) == UNZ_OK)
		if (unzOpenCurrentFile(unzfile) == UNZ_OK)
			return (int)unzfile;

	return -1;
}


int zread(int fp, void *buf, unsigned size)
{
	if (unzfile == NULL)
		return fread(buf, 1, size, (FILE *)fp);

	return unzReadCurrentFile(unzfile, buf, size);
}

int zclose(int fp)
{
	if (unzfile == NULL)
	{
		if (fp != -1) fclose((FILE *)fp);
		return 0;
	}
	return unzCloseCurrentFile(unzfile);
}


static int zsize(int fd)
{
	unz_file_info info;

	if (unzfile == NULL)
	{
    	FILE *fp = (FILE *)fd;
	    int len, pos = ftell(fp);

	    fseek(fp, 0, SEEK_END);
	    len = ftell(fp);
	    fseek(fp, pos, SEEK_SET);

	    return len;
	}

	unzGetCurrentFileInfo(unzfile, &info, NULL, 0, NULL, 0, NULL, 0);

	return info.uncompressed_size;
}


int zlength(const char *filename)
{
	int f;

	if ((f = zopen(filename)) != -1)
	{
		int length = zsize(f);
		zclose(f);
		return length;
	}
	return 0;
}
