/*
 * IO for uncompress .zip files using zlib 
 * Version 0.15 beta, Mar 19th, 1998,
 * Copyright (C) 1998 Gilles Vollant
 *
 * Minor hacks 2002 Vladimir A. Smirnov
 */

/*
 * This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
 * WinZip, InfoZip tools and compatible.
 * Encryption and multi volume ZipFile (span) are not supported.
 * Old compressions used by old PKZip 1.x are not supported

 * THIS IS AN ALPHA VERSION. AT THIS STAGE OF DEVELOPPEMENT, SOMES API OR STRUCTURE
 * CAN CHANGE IN FUTURE VERSION !!
 
 * I WAIT FEEDBACK at mail info@winimage.com
 * Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution

 * Condition of use and distribution are the same than zlib :

 * This software is provided 'as-is', without any express or implied
 * warranty.  In no event will the authors be held liable for any damages
 * arising from the use of this software.

 * Permission is granted to anyone to use this software for any purpose,
 * including commercial applications, and to alter it and redistribute it
 * freely, subject to the following restrictions:

   1. The origin of this software must not be misrepresented; you must not
      claim that you wrote the original software. If you use this software
      in a product, an acknowledgment in the product documentation would be
      appreciated but is not required.
   2. Altered source versions must be plainly marked as such, and must not be
      misrepresented as being the original software.
   3. This notice may not be removed or altered from any source distribution.
 */

/*
 * For more info about .ZIP format, see 
 *   ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
 * PkWare has also a specification at :
 *   ftp://ftp.pkware.com/probdesc.zip
 */

#include <../source/TAL/objbase.h>
#include <../source/vfs/fbase.h>
#include <../source/vfs/fsbase.h>
#include <../source/vfs/drivers/vfscat.h>

#ifdef	CONFIG_VFS_ZIPFS

#ifndef	CONFIG_COMPRESSION_ZLIB
#error	zipfs needs zlib; #define CONFIG_COMPRESSION_ZLIB and recompile.
#endif

#include <../support/zlib/src/zlib.h>

#define UNZ_OK							(0)
#define UNZ_END_OF_LIST_OF_FILE			(-100)
#define UNZ_ERRNO               		(Z_ERRNO)
#define UNZ_EOF							(0)
#define UNZ_PARAMERROR                  (-102)
#define UNZ_BADZIPFILE                  (-103)
#define UNZ_INTERNALERROR               (-104)
#define UNZ_CRCERROR                    (-105)

/* tm_unz contain date/time info */
typedef struct tm_unz_s 
{
	uInt tm_sec;            /* seconds after the minute - [0,59] */
	uInt tm_min;            /* minutes after the hour - [0,59] */
	uInt tm_hour;           /* hours since midnight - [0,23] */
	uInt tm_mday;           /* day of the month - [1,31] */
	uInt tm_mon;            /* months since January - [0,11] */
	uInt tm_year;           /* years - [1980..2044] */
}	tm_unz;

/* unz_global_info structure contain global data about the ZIPfile
   These data comes from the end of central dir */
typedef struct unz_global_info_s
{
	/* total number of entries in the central dir on this disk */
	uLong number_entry;
	/* size of the global comment of the zipfile */         
	uLong size_comment;
}	unz_global_info;

/* unz_file_info contain information about a file in the zipfile */
typedef struct unz_file_info_s
{
    uLong version;              /* version made by                 2 bytes */
    uLong version_needed;       /* version needed to extract       2 bytes */
    uLong flag;                 /* general purpose bit flag        2 bytes */
    uLong compression_method;   /* compression method              2 bytes */
    uLong dosDate;              /* last mod file date in Dos fmt   4 bytes */
    uLong crc;                  /* crc-32                          4 bytes */
    uLong compressed_size;      /* compressed size                 4 bytes */ 
    uLong uncompressed_size;    /* uncompressed size               4 bytes */ 
    uLong size_filename;        /* filename length                 2 bytes */
    uLong size_file_extra;      /* extra field length              2 bytes */
    uLong size_file_comment;    /* file comment length             2 bytes */

    uLong disk_num_start;       /* disk number start               2 bytes */
    uLong internal_fa;          /* internal file attributes        2 bytes */
    uLong external_fa;          /* external file attributes        4 bytes */

    tm_unz tmu_date;
} unz_file_info;

#include <../source/TAL/objbase.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define SIZECENTRALDIRITEM (0x2e)
#define SIZEZIPLOCALHEADER (0x1e)

#ifndef UNZ_BUFSIZE
#define UNZ_BUFSIZE (16384)
#endif

#ifndef UNZ_MAXFILENAMEINZIP
#define UNZ_MAXFILENAMEINZIP (256)
#endif

#define ALLOC		memAlloc
#define TRYFREE		memFree

const char unz_copyright[] =
	"unzip 0.15 Copyright 1998 Gilles Vollant";

/*
 * unz_file_info_interntal contain internal info about a file in zipfile
 */
typedef struct unz_file_info_internal_s
{
	uLong offset_curfile;	/* relative offset of local header 4 bytes */
}	unz_file_info_internal;

/*
 * file_in_zip_read_info_s contain internal information
 * about a file in zipfile, when reading and decompress it
 */
typedef struct
{
	char  *read_buffer;         /* internal buffer for compressed data */
	z_stream stream;            /* zLib stream structure for inflate */

	uLong pos_in_zipfile;       /* position in byte on the zipfile, for fileSeek */
	uLong stream_initialised;   /* flag set if stream structure is initialised*/

	uLong offset_local_extrafield;	/* offset of the local extra field */
	uInt  size_local_extrafield;	/* size of the local extra field */
	uLong pos_local_extrafield;	/* position in the local extra field in read*/

	uLong crc32;                /* crc32 of all data uncompressed */
	uLong crc32_wait;           /* crc32 we must obtain after decompress all */
	uLong rest_read_compressed;	/* number of byte to be decompressed */
	uLong rest_read_uncompressed;	/*number of byte to be obtained after decomp*/
	vhandle_t file;					/* io structore of the zipfile */
	uLong compression_method;	/* compression method (0==store) */
	uLong byte_before_the_zipfile;	/* byte before the zipfile, (>0 for sfx)*/

}	file_in_zip_read_info_s;

/*
 * unz_s contain internal information about the zipfile
 */
typedef struct
{
	vhandle_t file;				/* io channel of the zipfile */
	unz_global_info gi;			/* public global information */
	uLong byte_before_the_zipfile; /* byte before the zipfile, (>0 for sfx) */
	uLong num_file;				/* number of the current file in the zipfile */
	uLong pos_in_central_dir;	/* pos of the current file in the central dir */
	uLong current_file_ok;		/* flag about the usability of the current file */
	uLong central_pos;			/* position of the beginning of the central dir */

	uLong size_central_dir;		/* size of the central directory  */
	uLong offset_central_dir;	/* offset of start of central directory with
								   respect to the starting disk number */

	unz_file_info cur_file_info;	/* public info about the current file in zip */
	unz_file_info_internal cur_file_info_internal;	/* private info about it */
    file_in_zip_read_info_s *pfile_in_zip_read;	/* structure about the current
	                                    		file if we are decompressing it */
}	unz_s, *unzFile;

#define BUFREADCOMMENT (0x400)

/*
 * Locate the Central directory of a zipfile (at the end, just before
 * the global comment)
 */
V_LOCAL uLong
unzlocal_SearchCentralDir(vhandle_t fin)
{
	unsigned char* buf;
	uLong uSizeFile;
	uLong uBackRead;
	uLong uMaxBack=0xffff; /* maximum size of global comment */
	uLong uPosFound=0;
	
	fileSeek(fin,0,SEEK_END);

	uSizeFile = fileTell( fin );
	
	if (uMaxBack > uSizeFile)
		uMaxBack = uSizeFile;
	buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
	if (buf==NULL)
		return 0;
	uBackRead = 4;
	while (uBackRead < uMaxBack)
	{
		int i;
		uLong uReadSize, uReadPos;
		if (uBackRead+BUFREADCOMMENT>uMaxBack) 
			uBackRead = uMaxBack;
		else
			uBackRead+=BUFREADCOMMENT;
		uReadPos = uSizeFile-uBackRead ;
		uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? 
                     (BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
		fileSeek(fin,uReadPos,SEEK_SET);
		if (fileRead(fin,buf,(uInt)uReadSize)!=(uInt)uReadSize)
			break;
		for (i=(int)uReadSize-3; (i--)>0;)
		{
			if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && 
				((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
			{
				uPosFound = uReadPos+i;
				break;
			}
		}
		if (uPosFound!=0)
			break;
	}
	TRYFREE(buf);
	return uPosFound;
}

V_LOCAL	int	unzGoToFirstFile(unzFile file);
V_LOCAL	int	unzGoToNextFile(unzFile file);

/*
 * Open a Zip file. Path contain the full pathname in UNIX format.
 * If the zipfile cannot be opened (file don't exist or in not valid), the
 * return value is NULL.
 * Else, the return value is a unzFile Handle, usable with other function
 * of this unzip package.
 */
V_LOCAL	unzFile
unzOpen(char_p path)
{
	unz_s us;
	unz_s *s;
	uLong central_pos;
	vhandle_t fin;

	uLong number_disk;          /* number of the current dist, used for 
								   spaning ZIP, unsupported, always 0*/
	uLong number_disk_with_CD;  /* number the the disk with central dir, used
								   for spaning ZIP, unsupported, always 0*/
	uLong number_entry_CD;      /* total number of entries in
	                               the central dir 
	                               (same than number_entry on nospan) */
    /*
    fin=fileOpenRead(path); -- this allows nested archives
    */
    fin = lfsCreateFile(path,file_mode_read);

	if (fin == NULL)
		return NULL;

	central_pos = unzlocal_SearchCentralDir(fin);
	if (central_pos==0)
	{
		fileClose(fin);
		return NULL;
	}

	fileSeek(fin,central_pos,SEEK_SET);

	/* the signature, already checked */
	fileGetLittleLong(fin);
	/* number of this disk */
	number_disk = fileGetLittleShort(fin);
	/* number of the disk with the start of the central directory */
	number_disk_with_CD = fileGetLittleShort(fin);
	/* total number of entries in the central dir on this disk */
	us.gi.number_entry = fileGetLittleShort(fin);
	/* total number of entries in the central dir */
	number_entry_CD = fileGetLittleShort(fin);
	
	if ((number_entry_CD!=us.gi.number_entry) ||
		(number_disk_with_CD!=0) ||
		(number_disk!=0))
	{
		fileClose(fin);
		return NULL;
	}

	/* size of the central directory */
	us.size_central_dir = fileGetLittleLong(fin);
	/* offset of start of central directory with respect to the 
	      starting disk number */
	us.offset_central_dir = fileGetLittleLong(fin);
	/* zipfile comment length */
	us.gi.size_comment = fileGetLittleShort(fin);

	if (central_pos < us.offset_central_dir+us.size_central_dir)
	{
		fileClose(fin);
		return NULL;
	}

	us.file=fin;
	
	us.byte_before_the_zipfile = 
		central_pos - (us.offset_central_dir+us.size_central_dir);
	
	us.central_pos = central_pos;
    us.pfile_in_zip_read = NULL;
	
	s=(unz_s*)ALLOC(sizeof(unz_s));
	memCopy(s,&us,sizeof(unz_s));

	unzGoToFirstFile((unzFile)s);	
	return s;	
}

V_LOCAL int unzCloseCurrentFile(unzFile file);

/*
 * Close a ZipFile opened with unzipOpen.
 * If there is files inside the .Zip opened with
 * unzOpenCurrentFile (see later), these files MUST be closed with
 * unzCloseCurrentFile before call unzClose.
 *
 * Returns UNZ_OK if there is no problem.
 */
V_LOCAL int
unzClose(unzFile file)
{
	V_ASSERT(file);
    if (file->pfile_in_zip_read != NULL)
        unzCloseCurrentFile(file);
	fileClose(file->file);
	TRYFREE(file);
	return UNZ_OK;
}

/*
 * Translate date/time from Dos format to tm_unz (readable more easilty)
 */
V_LOCAL void
unzlocal_DosDateToTmuDate (uLong ulDosDate,tm_unz* ptm)
{
    uLong uDate;
    uDate = (uLong)(ulDosDate>>16);
    ptm->tm_mday = (uInt)(uDate&0x1f) ;
    ptm->tm_mon =  (uInt)((((uDate)&0x1E0)/0x20)-1) ;
    ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;

    ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
    ptm->tm_min =  (uInt) ((ulDosDate&0x7E0)/0x20) ;
    ptm->tm_sec =  (uInt) (2*(ulDosDate&0x1f)) ;
}

/*
 * Get Info about the current file in the zipfile, with internal only info
 */
V_LOCAL int
unzlocal_GetCurrentFileInfoInternal(unzFile file,
	unz_file_info *pfile_info,
	unz_file_info_internal *pfile_info_internal,
	char *szFileName,
	uLong fileNameBufferSize,
	void *extraField,
	uLong extraFieldBufferSize,
	char *szComment,
	uLong commentBufferSize)
{
	unz_file_info file_info;
	unz_file_info_internal file_info_internal;
	int err=UNZ_OK;
	long lSeek=0;

	V_ASSERT(file);

	fileSeek(file->file,
		file->pos_in_central_dir + file->byte_before_the_zipfile,SEEK_SET);

	/* Check the magic */
	if (fileGetLittleLong(file->file) != 0x02014b50)
		return UNZ_BADZIPFILE;

	file_info.version = fileGetLittleShort(file->file);
	file_info.version_needed = fileGetLittleShort(file->file);
	file_info.flag = fileGetLittleShort(file->file);
	file_info.compression_method = fileGetLittleShort(file->file);
	file_info.dosDate = fileGetLittleLong(file->file);
    unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
	file_info.crc = fileGetLittleLong(file->file);
	file_info.compressed_size = fileGetLittleLong(file->file);
	file_info.uncompressed_size = fileGetLittleLong(file->file);
	file_info.size_filename = fileGetLittleShort(file->file);
	file_info.size_file_extra = fileGetLittleShort(file->file);
	file_info.size_file_comment = fileGetLittleShort(file->file);
	file_info.disk_num_start = fileGetLittleShort(file->file);
	file_info.internal_fa = fileGetLittleShort(file->file);
	file_info.external_fa = fileGetLittleLong(file->file);
	file_info_internal.offset_curfile = fileGetLittleLong(file->file);

	lSeek+=file_info.size_filename;
	if (szFileName!=NULL)
	{
		uLong uSizeRead ;
		if (file_info.size_filename<fileNameBufferSize)
		{
			*(szFileName+file_info.size_filename)='\0';
			uSizeRead = file_info.size_filename;
		}
		else
			uSizeRead = fileNameBufferSize;

		if ((file_info.size_filename>0) && (fileNameBufferSize>0))
			if (fileRead(file->file,szFileName,(uInt)uSizeRead)!=(uInt)uSizeRead)
				err=UNZ_ERRNO;
		lSeek -= uSizeRead;
	}
	
	if ((err==UNZ_OK) && (extraField!=NULL))
	{
		uLong uSizeRead ;
		if (file_info.size_file_extra<extraFieldBufferSize)
			uSizeRead = file_info.size_file_extra;
		else
			uSizeRead = extraFieldBufferSize;

		if (lSeek!=0)
			fileSeek(file->file,lSeek,SEEK_CUR);
		lSeek=0;
		if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
			if (fileRead(file->file,extraField,(uInt)uSizeRead)!=(uInt)uSizeRead)
				err=UNZ_ERRNO;
		lSeek += file_info.size_file_extra - uSizeRead;
	}
	else
		lSeek+=file_info.size_file_extra; 

	
	if ((err==UNZ_OK) && (szComment!=NULL))
	{
		uLong uSizeRead ;
		if (file_info.size_file_comment<commentBufferSize)
		{
			*(szComment+file_info.size_file_comment)='\0';
			uSizeRead = file_info.size_file_comment;
		}
		else
			uSizeRead = commentBufferSize;
		if (lSeek!=0)
			fileSeek(file->file,lSeek,SEEK_CUR);
		/* lSeek=0; */
		if ((file_info.size_file_comment>0) && (commentBufferSize>0))
			if (fileRead(file->file,szComment,(uInt)uSizeRead)!=(uInt)uSizeRead)
				err=UNZ_ERRNO;
		/* lSeek += file_info.size_file_comment - uSizeRead; */
	}

	if ((err==UNZ_OK) && (pfile_info!=NULL))
		*pfile_info=file_info;

	if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
		*pfile_info_internal=file_info_internal;

	return err;
}


/*
 * Writes info about the ZipFile in the *pglobal_info structure.
 * No preparation of the structure is needed
 * return UNZ_OK if there is no problem.
 */
V_LOCAL int
unzGetCurrentFileInfo (unzFile file,
	unz_file_info *pfile_info,
	char *szFileName,
	uLong fileNameBufferSize,
	void *extraField,
	uLong extraFieldBufferSize,
	char *szComment,
	uLong commentBufferSize)
{
	return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,
		szFileName,fileNameBufferSize,extraField,extraFieldBufferSize,
		szComment,commentBufferSize);
}

/*
 * Unzip package allow you browse the directory of the zipfile.
 * Sets the current file of the zipfile to the first file.
 * Returns UNZ_OK if there was no problem.
 */
V_LOCAL int
unzGoToFirstFile(unzFile file)
{
	int err;
	V_ASSERT(file);
	file->pos_in_central_dir = file->offset_central_dir;
	file->num_file = 0;
	err=unzlocal_GetCurrentFileInfoInternal(file,
		&file->cur_file_info,
		&file->cur_file_info_internal,
		NULL,0,NULL,0,NULL,0);
	file->current_file_ok = (err == UNZ_OK);
	return err;
}

/*
 * Sets the current file of the zipfile to the next file.
 * Returns UNZ_OK if there is no problem
 * Returns UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
 */
V_LOCAL int
unzGoToNextFile (unzFile file)
{
	int err;
	V_ASSERT(file);
	if (!file->current_file_ok)
		return UNZ_END_OF_LIST_OF_FILE;
	if (file->num_file+1 == file->gi.number_entry)
		return UNZ_END_OF_LIST_OF_FILE;

	file->pos_in_central_dir += SIZECENTRALDIRITEM + 
		file->cur_file_info.size_filename +
		file->cur_file_info.size_file_extra + 
		file->cur_file_info.size_file_comment;
	
	file->num_file++;
	
	err = unzlocal_GetCurrentFileInfoInternal(file,&file->cur_file_info,
		&file->cur_file_info_internal,NULL,0,NULL,0,NULL,0);

	file->current_file_ok = (err == UNZ_OK);
	return err;
}

/*
 * Reads the local header of the current zipfile
 * Checks the coherency of the local header and info in the end of central
 * directory about this file
 * Stores in *piSizeVar the size of extra info in local header
 * (filename and size of extra field data)
 */
V_LOCAL int
unzlocal_CheckCurrentFileCoherencyHeader(unz_s* s,
	uInt* piSizeVar,uLong *poffset_local_extrafield,
	uInt  *psize_local_extrafield)
{
	uLong uData,uFlags;
	uLong size_filename;
	uLong size_extra_field;
	*piSizeVar = 0;
	*poffset_local_extrafield = 0;
	*psize_local_extrafield = 0;
	fileSeek(s->file,s->cur_file_info_internal.offset_curfile +
		s->byte_before_the_zipfile,SEEK_SET);
	if(fileGetLittleLong(s->file)!=0x04034b50)
		return UNZ_BADZIPFILE;
	fileGetLittleShort(s->file);
	uFlags = fileGetLittleShort(s->file);
	uData = fileGetLittleShort(s->file);
	if(uData != s->cur_file_info.compression_method)
		return UNZ_BADZIPFILE;
    if((s->cur_file_info.compression_method !=0 ) &&
		(s->cur_file_info.compression_method != Z_DEFLATED))
		return UNZ_BADZIPFILE;
	fileGetLittleLong(s->file); /* date/time */
	uData = fileGetLittleLong(s->file); /* crc */
	if(uData != s->cur_file_info.crc && (uFlags & 8)==0)
		return UNZ_BADZIPFILE;
	uData = fileGetLittleLong(s->file); /* size compr */
	if(uData != s->cur_file_info.compressed_size && (uFlags & 8)==0)
		return UNZ_BADZIPFILE;
	uData = fileGetLittleLong(s->file); /* size uncompr */
	if(uData != s->cur_file_info.uncompressed_size && (uFlags & 8)==0)
		return UNZ_BADZIPFILE;
	size_filename = fileGetLittleShort(s->file);
	if(size_filename != s->cur_file_info.size_filename)
		return UNZ_BADZIPFILE;
	*piSizeVar += (uInt)size_filename;
	size_extra_field = fileGetLittleShort(s->file);
	*poffset_local_extrafield = s->cur_file_info_internal.offset_curfile +
		SIZEZIPLOCALHEADER + size_filename;
	*psize_local_extrafield = (uInt)size_extra_field;
	*piSizeVar += (uInt)size_extra_field;
	return UNZ_OK;
}
												
/*
 * Open for reading data the current file in the zipfile.
 * If there is no error and the file is opened, the return value is UNZ_OK.
 */
V_LOCAL int
unzOpenCurrentFile(unzFile file)
{
	int err;
	int Store;
	uInt iSizeVar;
	file_in_zip_read_info_s* pfile_in_zip_read_info;
	uLong offset_local_extrafield;  /* offset of the local extra field */
	uInt  size_local_extrafield;    /* size of the local extra field */

	V_ASSERT(file);

	if (!file->current_file_ok)
		return UNZ_PARAMERROR;

    if (file->pfile_in_zip_read != NULL)
        unzCloseCurrentFile(file);

	if (unzlocal_CheckCurrentFileCoherencyHeader(file,&iSizeVar,
				&offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
		return UNZ_BADZIPFILE;

	pfile_in_zip_read_info = (file_in_zip_read_info_s*)
		ALLOC(sizeof(file_in_zip_read_info_s));

	if (pfile_in_zip_read_info==NULL)
		return UNZ_INTERNALERROR;

	pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
	pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
	pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
	pfile_in_zip_read_info->pos_local_extrafield=0;

	if (pfile_in_zip_read_info->read_buffer==NULL)
	{
		TRYFREE(pfile_in_zip_read_info);
		return UNZ_INTERNALERROR;
	}

	pfile_in_zip_read_info->stream_initialised = 0;
	
	Store = file->cur_file_info.compression_method == 0;

	if (!Store && (file->cur_file_info.compression_method!=Z_DEFLATED))
	{
		TRYFREE(pfile_in_zip_read_info);
		return UNZ_BADZIPFILE;
	}

	pfile_in_zip_read_info->crc32_wait = file->cur_file_info.crc;
	pfile_in_zip_read_info->crc32 = 0;
	pfile_in_zip_read_info->compression_method =
		file->cur_file_info.compression_method;

	pfile_in_zip_read_info->file = file->file;
	/*
	 * By V. Smirnov: we can avoid locks:
	pfile_in_zip_read_info->file = ioDuplicateFileHandle(file->file);
	 */
	pfile_in_zip_read_info->byte_before_the_zipfile = file->byte_before_the_zipfile;

    pfile_in_zip_read_info->stream.total_out = 0;

	if(!Store)
	{
		pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
		pfile_in_zip_read_info->stream.zfree = (free_func)0;
		pfile_in_zip_read_info->stream.opaque = (voidpf)0; 
      
		err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
		if (err == Z_OK)
			pfile_in_zip_read_info->stream_initialised = 1;
		else
		{
			TRYFREE(pfile_in_zip_read_info);
			return UNZ_BADZIPFILE;
		}
        /* windowBits is passed < 0 to tell that there is no zlib header.
         * Note that in this case inflate *requires* an extra "dummy" byte
         * after the compressed stream in order to complete decompression and
         * return Z_STREAM_END. 
         * In unzip, i don't wait absolutely Z_STREAM_END because I known the 
         * size of both compressed and uncompressed data
         */
	}
	pfile_in_zip_read_info->rest_read_compressed = 
    	file->cur_file_info.compressed_size;
	pfile_in_zip_read_info->rest_read_uncompressed = 
        file->cur_file_info.uncompressed_size;
	pfile_in_zip_read_info->pos_in_zipfile = 
		file->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + 
		iSizeVar;
	pfile_in_zip_read_info->stream.avail_in = (uInt)0;
	file->pfile_in_zip_read = pfile_in_zip_read_info;
    return UNZ_OK;
}

/*
 * Read bytes from the current file.
 * buf contain buffer where data must be copied
 * len the size of buf.
 *
 * return the number of byte copied if somes bytes are copied
 * return 0 if the end of file was reached
 * return <0 with error code if there is an error
 * (UNZ_ERRNO for IO error, or zLib error for uncompress error)
 *
 * VS: TODO: rewrite this, performance can be significantly improved !
 */
V_LOCAL int
unzReadCurrentFile(unzFile file,voidp buf,unsigned len)
{
	int err=UNZ_OK;
	uInt iRead = 0;
	file_in_zip_read_info_s *pfile_in_zip_read_info;
	V_ASSERT(file);
    /*
     * TODO: store pfile_in_zip_read_info in zip_inode_t
     */
    pfile_in_zip_read_info = file->pfile_in_zip_read;

	if (pfile_in_zip_read_info==NULL)
		return UNZ_PARAMERROR;

	if ((pfile_in_zip_read_info->read_buffer == NULL))
		return UNZ_END_OF_LIST_OF_FILE;
	if (len==0)
		return 0;

	pfile_in_zip_read_info->stream.next_out = (Bytef*)buf;

	pfile_in_zip_read_info->stream.avail_out = (uInt)len;
	
	if (len>pfile_in_zip_read_info->rest_read_uncompressed)
		pfile_in_zip_read_info->stream.avail_out = 
		  (uInt)pfile_in_zip_read_info->rest_read_uncompressed;

	while (pfile_in_zip_read_info->stream.avail_out>0)
	{
		if ((pfile_in_zip_read_info->stream.avail_in==0) &&
            (pfile_in_zip_read_info->rest_read_compressed>0))
		{
			uInt uReadThis = UNZ_BUFSIZE, uReadOk;
			if (pfile_in_zip_read_info->rest_read_compressed < uReadThis)
				uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
			if (uReadThis == 0)
				return UNZ_EOF;	/* == 0 */
			fileSeek(pfile_in_zip_read_info->file,
				pfile_in_zip_read_info->pos_in_zipfile + 
                pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET);
            uReadOk = fileRead(pfile_in_zip_read_info->file,
            	pfile_in_zip_read_info->read_buffer,uReadThis);
			pfile_in_zip_read_info->pos_in_zipfile += uReadOk;
			if (uReadOk != uReadThis)
				return UNZ_ERRNO; /* < 0 */
			pfile_in_zip_read_info->rest_read_compressed -= uReadThis;
			pfile_in_zip_read_info->stream.next_in = 
                (Bytef*)pfile_in_zip_read_info->read_buffer;
			pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
		}

		if (pfile_in_zip_read_info->compression_method==0)
		{
			uInt uDoCopy, i;
			if (pfile_in_zip_read_info->stream.avail_out < 
                            pfile_in_zip_read_info->stream.avail_in)
				uDoCopy = pfile_in_zip_read_info->stream.avail_out;
			else
				uDoCopy = pfile_in_zip_read_info->stream.avail_in;
			
			/* VS: FIXME: can we use memcpy() ? */
			
			for (i=0;i<uDoCopy;i++)
				*(pfile_in_zip_read_info->stream.next_out+i) =
                        *(pfile_in_zip_read_info->stream.next_in+i);
					
			pfile_in_zip_read_info->crc32 = 
				crc32(pfile_in_zip_read_info->crc32,
				pfile_in_zip_read_info->stream.next_out,
				uDoCopy);

			pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
			pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
			pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
			pfile_in_zip_read_info->stream.next_out += uDoCopy;
			pfile_in_zip_read_info->stream.next_in += uDoCopy;
            pfile_in_zip_read_info->stream.total_out += uDoCopy;
			iRead += uDoCopy;
		}
		else
		{
			uLong uTotalOutBefore,uTotalOutAfter;
			const Bytef *bufBefore;
			uLong uOutThis;
			int flush=Z_SYNC_FLUSH;

			uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
			bufBefore = pfile_in_zip_read_info->stream.next_out;

			/*
			if ((pfile_in_zip_read_info->rest_read_uncompressed ==
			         pfile_in_zip_read_info->stream.avail_out) &&
				(pfile_in_zip_read_info->rest_read_compressed == 0))
				flush = Z_FINISH;
			*/

			err=inflate(&pfile_in_zip_read_info->stream,flush);

			uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
			uOutThis = uTotalOutAfter-uTotalOutBefore;
			
			pfile_in_zip_read_info->crc32 = 
                crc32(pfile_in_zip_read_info->crc32,bufBefore,
                        (uInt)(uOutThis));

			pfile_in_zip_read_info->rest_read_uncompressed -=
                uOutThis;

			iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
            
			if (err==Z_STREAM_END)
				return (iRead==0) ? UNZ_EOF : iRead;
			if (err!=Z_OK) 
				break;
		}
	}

	if (err == Z_OK)
		return iRead;

	return err;
}

/*
 * Close the file in zip opened with unzipOpenCurrentFile
 * Return UNZ_CRCERROR if all the file was read but the CRC is not good
 */
V_LOCAL int
unzCloseCurrentFile(unzFile file)
{
	int err=UNZ_OK;

	file_in_zip_read_info_s* pfile_in_zip_read_info;
	V_ASSERT(file);

    pfile_in_zip_read_info = file->pfile_in_zip_read;

	if (pfile_in_zip_read_info == NULL)
		return UNZ_PARAMERROR;

	if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
	{
		if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
			err = UNZ_CRCERROR;
	}

	TRYFREE(pfile_in_zip_read_info->read_buffer);
	pfile_in_zip_read_info->read_buffer = NULL;
	if (pfile_in_zip_read_info->stream_initialised)
		inflateEnd(&pfile_in_zip_read_info->stream);

	pfile_in_zip_read_info->stream_initialised = 0;
	TRYFREE(pfile_in_zip_read_info);

	file->pfile_in_zip_read = NULL;

	return err;
}

/*
 * VFS driver for zip archive, quick and dirty ...
 */
 
#include <../source/vfs/drivers/fslist.h>

/*
 * TODO: There is a better way to handle zip archives:
 *	1. At open, pct_map_ispace to fs->zip_base.
 *	2. At 2nd pass, for every non-directory entry:
 *		2.1. unzOpenCurrentFileEx(ex_dont_initialize_stream);
 *			if compression is 'store', goto 2.4.
 *		2.2. Copy decompress struct in inode, clear ino->dhandle
 *		2.3. Replace inode's port to new port, done.
 *		2.4. Store data base & data size in inode, done.
 *	3. In fs->create_file(): if 'store' create mapped_port, set base and
 *		size from inode; else create zipread_port:
 *		3.1. Copy decompress struct from inode to zipread_port;
 *			note - NO pointers and NO handles can be copied !
 *		3.2. Create io_section_t, set port->base to fs->zip_base,
 *			len to fs->zip_filelen; set zipread_port->decompress->file to
 *			new port.
 *		3.3. Initialize zipread_port->decompress.stream, done.
 *	4. In zipread_port->read(): pass zipread_port->decompress to
 *		unzReadCurrentFileDeflOnly().
 *
 *	Currently I'm (stupidly) using locks and decompress every individual
 *  file in memory. This will cause problems with large files.
 */

typedef struct zipfs_ino_s
{
	uLong num_file;
	uLong pos_in_central_dir;
	uLong current_file_ok;
	unz_file_info cur_file_info;
	unz_file_info_internal cur_file_info_internal;
	char	name[_MAX_PATH];
}	zipfs_ino_t, *zipfs_ino_p;

typedef struct vfs_zipfs_s
{
	vfs_dev_t	vtbl;
    unzFile		dhandle;
    mutex_t		dhandle_lock;
	u32_t		num_ino;
	char		volume_name[_MAX_PATH];
	zipfs_ino_t	*dir;
}	vfs_zipfs_t, *vfs_zipfs_p;

V_LOCAL	vhandle_t	V_CALL
zipfs_create_port(vfs_dev_t *self,u32_t inode)
{
	zipfs_ino_t *ino;
	vfs_mapport_p port;
	vfs_zipfs_t *fs=(vfs_zipfs_t*)self;
	if(inode >= fs->num_ino)
    	return NULL;
    ino = fs->dir + inode;
    port = vfsCreateMPort(self,ino->cur_file_info.uncompressed_size,
    	NULL,ino->cur_file_info.uncompressed_size);
	if(!port)
		return LIBV_INVALID_HANDLE;
    port->section.base = (u8_t*)(port + 1);
    /* BEGIN HACK */
    mutexLock(fs->dhandle_lock);
    fs->dhandle->num_file = ino->num_file;
	fs->dhandle->pos_in_central_dir = ino->pos_in_central_dir;
	fs->dhandle->current_file_ok = ino->current_file_ok;
	memCopy(&fs->dhandle->cur_file_info,&ino->cur_file_info,sizeof(unz_file_info));
	memCopy(&fs->dhandle->cur_file_info_internal,&ino->cur_file_info_internal,
		sizeof(unz_file_info_internal));
	/* Decompress all data */
	unzOpenCurrentFile(fs->dhandle);
	unzReadCurrentFile(fs->dhandle,port->section.base,port->section.size);
	unzCloseCurrentFile(fs->dhandle);
    mutexUnlock(fs->dhandle_lock);
    /* END HACK */
	return (vhandle_t)port;
}

V_LOCAL	u32_t V_CALL
zipfs_get_inode_count(vfs_dev_t *self)
{
	return ((vfs_zipfs_t*)self)->num_ino;
}

V_LOCAL	vboolean	V_CALL
zipfs_get_file_name(vfs_dev_t *self,u32_t inode,char *name_ret)
{
	if(inode>=((vfs_zipfs_t*)self)->num_ino)
    	return false;
	strCopy(name_ret,((vfs_zipfs_t*)self)->dir[inode].name,_MAX_PATH);
    return true;
}

/*
 * PAKFS destructor.
 * Note: we leave ref_count untouched !
 */
V_LOCAL	u32_t V_CALL
zipfs_destroy(vhandle_t handle)
{
	u32_t count, maxtries = 10;
	mutex_t m1, m2;
	vfs_zipfs_p self=(vfs_zipfs_p)handle;
	mutexLock(self->vtbl.vfs_lock);
	if(self->vtbl.base.ref_count > 1)
	{
		mutexUnlock(self->vtbl.vfs_lock);
		return self->vtbl.base.ref_count;
	}
	/*
	 * Now we must aquire dhandle_lock
	 */
	for(count=0;!mutexTryLock(self->dhandle_lock) && count<maxtries;count++)
	{
#ifdef	CHECKED_BUILD
		conlPrintf(LOG_WARNING,
			"zipfs::destroy(): volume busy (%u)...\n",count);
#endif	/* CHECKED_BUILD */
		timeDelay(1000);
	}
	if(count==maxtries)
	{
#ifdef	CHECKED_BUILD
		conlPrintf(LOG_ERROR,
			"zipfs::destroy(): volume busy (%u seconds).\n",maxtries);
#endif	/* CHECKED_BUILD */
		mutexUnlock(self->vtbl.vfs_lock);
		return self->vtbl.base.ref_count;
	}
	m1 = self->vtbl.vfs_lock;
	m2 = self->dhandle_lock;
	unzClose(self->dhandle);
	memFreeObject(self);
	mutexUnlock(m2);
	mutexDestroy(m2);
	mutexUnlock(m1);
	mutexDestroy(m1);
	return 0;
}

V_LOCAL	char_p V_CALL
zipfs_get_volume_name(vfs_dev_t *handle)
{
	return ((vfs_zipfs_t*)handle)->volume_name;
}

/*
 * PAKFS factory
 */
vfs_dev_p	V_CALL
vfsMountZip(char *volume_name)
{
	u32_t num_ino;
    vfs_zipfs_p dev;
	unzFile dhandle;
	unz_file_info info;
	char ext[_MAX_EXT];
	char filename_inzip[_MAX_PATH];
    fsSplitPath(volume_name,NULL,NULL,ext);
    if(strcasecmp(ext,"zip") && strcasecmp(ext,"pk3"))
    	return NULL;
#ifdef	CHECKED_BUILD
	conlPrintf(LOG_INFO,"vfsMountZip(): adding '%s' ...\n",volume_name);
#endif	/* CHECKED_BUILD */
	dhandle = unzOpen(volume_name);
	if(dhandle == NULL)
    {
#ifdef	CHECKED_BUILD
		conlPrintf(LOG_WARNING,"vfsMountZip('%s'): "
			"isn't ZIP archive.\n",volume_name);
#endif	/* CHECKED_BUILD */
		return NULL;
    }
    /* first pass */
    num_ino = 0;
    do
    {
    	char trail;
		unzGetCurrentFileInfo(dhandle,&info,filename_inzip,
			sizeof(filename_inzip),NULL,0,NULL,0);
    	trail = *(filename_inzip + strlen(filename_inzip) - 1);
    	if(trail != '/' && info.uncompressed_size > 0)
    		num_ino ++;
    } while(unzGoToNextFile(dhandle) == UNZ_OK);
	if(num_ino == 0)
	{
		unzClose(dhandle);
#ifdef	CHECKED_BUILD
		conlPrintf(LOG_WARNING,"vfsMountZip('%s'): "
			"no files in archive.\n",volume_name);
#endif	/* CHECKED_BUILD */
		return NULL;
    }
	dev=(vfs_zipfs_t*)vfsCreateFS(sizeof(vfs_zipfs_t) +
		num_ino * sizeof(zipfs_ino_t));
    dev->dir = (zipfs_ino_t*)(dev + 1);
    dev->vtbl.base.destroy = zipfs_destroy;
    dev->dhandle_lock = mutexCreate();
    dev->vtbl.create_file = zipfs_create_port;
	strCopy(dev->volume_name,volume_name,_MAX_PATH);
	dev->num_ino = num_ino;
	dev->dhandle = dhandle;
	dev->vtbl.get_volume_name = zipfs_get_volume_name;
	dev->vtbl.get_inode_count = zipfs_get_inode_count;
	dev->vtbl.get_file_name = zipfs_get_file_name;
    /*
     * Read in directory
     */
    unzGoToFirstFile(dhandle);
    num_ino = 0;
    do
    {
    	char trail;
		unzGetCurrentFileInfo(dhandle,&info,filename_inzip,
			sizeof(filename_inzip),NULL,0,NULL,0);
    	trail = *(filename_inzip + strlen(filename_inzip) - 1);
    	if(trail != '/' && info.uncompressed_size > 0)
    	{
    		zipfs_ino_t *ino = &dev->dir[num_ino++];
		    /* HACK */
		    ino->num_file = dhandle->num_file;
			ino->pos_in_central_dir = dhandle->pos_in_central_dir;
			ino->current_file_ok = dhandle->current_file_ok;
			memCopy(&ino->cur_file_info,&dhandle->cur_file_info,sizeof(unz_file_info));
			memCopy(&ino->cur_file_info_internal,&dhandle->cur_file_info_internal,
				sizeof(unz_file_info_internal));
    		strCopy(ino->name,filename_inzip,_MAX_PATH);
    	}
    } while(unzGoToNextFile(dhandle) == UNZ_OK);
#ifdef	CHECKED_BUILD
	conlPrintf(LOG_TRACE,"vfsMountZip('%s'): added %u files.\n",
			volume_name,num_ino);
#endif	/* CHECKED_BUILD */
	return (vfs_dev_p)dev;
}

#endif	/* CONFIG_VFS_ZIPFS */
