Main Page | Class Hierarchy | Alphabetical List | Data Structures | Directories | File List | Data Fields | Globals

unzip.c

Go to the documentation of this file.
00001 /*****************************************************************************
00002  * name:        unzip.c
00003  *
00004  * desc:        IO on .zip files using portions of zlib 
00005  *
00006  * $Archive: /MissionPack/code/qcommon/unzip.c $
00007  *
00008  *****************************************************************************/
00009 
00010 #include "../client/client.h"
00011 #include "unzip.h"
00012 
00013 /* unzip.h -- IO for uncompress .zip files using zlib 
00014    Version 0.15 beta, Mar 19th, 1998,
00015 
00016    Copyright (C) 1998 Gilles Vollant
00017 
00018    This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
00019      WinZip, InfoZip tools and compatible.
00020    Encryption and multi volume ZipFile (span) are not supported.
00021    Old compressions used by old PKZip 1.x are not supported
00022 
00023    THIS IS AN ALPHA VERSION. AT THIS STAGE OF DEVELOPPEMENT, SOMES API OR STRUCTURE
00024    CAN CHANGE IN FUTURE VERSION !!
00025    I WAIT FEEDBACK at mail info@winimage.com
00026    Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
00027 
00028    Condition of use and distribution are the same than zlib :
00029 
00030   This software is provided 'as-is', without any express or implied
00031   warranty.  In no event will the authors be held liable for any damages
00032   arising from the use of this software.
00033 
00034   Permission is granted to anyone to use this software for any purpose,
00035   including commercial applications, and to alter it and redistribute it
00036   freely, subject to the following restrictions:
00037 
00038   1. The origin of this software must not be misrepresented; you must not
00039      claim that you wrote the original software. If you use this software
00040      in a product, an acknowledgment in the product documentation would be
00041      appreciated but is not required.
00042   2. Altered source versions must be plainly marked as such, and must not be
00043      misrepresented as being the original software.
00044   3. This notice may not be removed or altered from any source distribution.
00045 
00046 
00047 */
00048 /* for more info about .ZIP format, see 
00049       ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
00050    PkWare has also a specification at :
00051       ftp://ftp.pkware.com/probdesc.zip */
00052 
00053 /* zlib.h -- interface of the 'zlib' general purpose compression library
00054   version 1.1.3, July 9th, 1998
00055 
00056   Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
00057 
00058   This software is provided 'as-is', without any express or implied
00059   warranty.  In no event will the authors be held liable for any damages
00060   arising from the use of this software.
00061 
00062   Permission is granted to anyone to use this software for any purpose,
00063   including commercial applications, and to alter it and redistribute it
00064   freely, subject to the following restrictions:
00065 
00066   1. The origin of this software must not be misrepresented; you must not
00067      claim that you wrote the original software. If you use this software
00068      in a product, an acknowledgment in the product documentation would be
00069      appreciated but is not required.
00070   2. Altered source versions must be plainly marked as such, and must not be
00071      misrepresented as being the original software.
00072   3. This notice may not be removed or altered from any source distribution.
00073 
00074   Jean-loup Gailly        Mark Adler
00075   jloup@gzip.org          madler@alumni.caltech.edu
00076 
00077 
00078   The data format used by the zlib library is described by RFCs (Request for
00079   Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
00080   (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
00081 */
00082 
00083 /* zconf.h -- configuration of the zlib compression library
00084  * Copyright (C) 1995-1998 Jean-loup Gailly.
00085  * For conditions of distribution and use, see copyright notice in zlib.h 
00086  */
00087 
00088 
00089 #ifndef _ZCONF_H
00090 #define _ZCONF_H
00091 
00092 /* Maximum value for memLevel in deflateInit2 */
00093 #ifndef MAX_MEM_LEVEL
00094 #  ifdef MAXSEG_64K
00095 #    define MAX_MEM_LEVEL 8
00096 #  else
00097 #    define MAX_MEM_LEVEL 9
00098 #  endif
00099 #endif
00100 
00101 /* Maximum value for windowBits in deflateInit2 and inflateInit2.
00102  * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
00103  * created by gzip. (Files created by minigzip can still be extracted by
00104  * gzip.)
00105  */
00106 #ifndef MAX_WBITS
00107 #  define MAX_WBITS   15 /* 32K LZ77 window */
00108 #endif
00109 
00110 /* The memory requirements for deflate are (in bytes):
00111             (1 << (windowBits+2)) +  (1 << (memLevel+9))
00112  that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
00113  plus a few kilobytes for small objects. For example, if you want to reduce
00114  the default memory requirements from 256K to 128K, compile with
00115      make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
00116  Of course this will generally degrade compression (there's no free lunch).
00117 
00118    The memory requirements for inflate are (in bytes) 1 << windowBits
00119  that is, 32K for windowBits=15 (default value) plus a few kilobytes
00120  for small objects.
00121 */
00122 
00123                         /* Type declarations */
00124 
00125 #ifndef OF /* function prototypes */
00126 #define OF(args)  args
00127 #endif
00128 
00129 typedef unsigned char  Byte;  /* 8 bits */
00130 typedef unsigned int   uInt;  /* 16 bits or more */
00131 typedef unsigned long  uLong; /* 32 bits or more */
00132 typedef Byte    *voidp;
00133 
00134 #ifndef SEEK_SET
00135 #  define SEEK_SET        0       /* Seek from beginning of file.  */
00136 #  define SEEK_CUR        1       /* Seek from current position.  */
00137 #  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
00138 #endif
00139 
00140 #endif /* _ZCONF_H */
00141 
00142 #define ZLIB_VERSION "1.1.3"
00143 
00144 /* 
00145      The 'zlib' compression library provides in-memory compression and
00146   decompression functions, including integrity checks of the uncompressed
00147   data.  This version of the library supports only one compression method
00148   (deflation) but other algorithms will be added later and will have the same
00149   stream interface.
00150 
00151      Compression can be done in a single step if the buffers are large
00152   enough (for example if an input file is mmap'ed), or can be done by
00153   repeated calls of the compression function.  In the latter case, the
00154   application must provide more input and/or consume the output
00155   (providing more output space) before each call.
00156 
00157      The library also supports reading and writing files in gzip (.gz) format
00158   with an interface similar to that of stdio.
00159 
00160      The library does not install any signal handler. The decoder checks
00161   the consistency of the compressed data, so the library should never
00162   crash even in case of corrupted input.
00163 */
00164 
00165 /*
00166    The application must update next_in and avail_in when avail_in has
00167    dropped to zero. It must update next_out and avail_out when avail_out
00168    has dropped to zero. The application must initialize zalloc, zfree and
00169    opaque before calling the init function. All other fields are set by the
00170    compression library and must not be updated by the application.
00171 
00172    The opaque value provided by the application will be passed as the first
00173    parameter for calls of zalloc and zfree. This can be useful for custom
00174    memory management. The compression library attaches no meaning to the
00175    opaque value.
00176 
00177    zalloc must return Z_NULL if there is not enough memory for the object.
00178    If zlib is used in a multi-threaded application, zalloc and zfree must be
00179    thread safe.
00180 
00181    On 16-bit systems, the functions zalloc and zfree must be able to allocate
00182    exactly 65536 bytes, but will not be required to allocate more than this
00183    if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
00184    pointers returned by zalloc for objects of exactly 65536 bytes *must*
00185    have their offset normalized to zero. The default allocation function
00186    provided by this library ensures this (see zutil.c). To reduce memory
00187    requirements and avoid any allocation of 64K objects, at the expense of
00188    compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
00189 
00190    The fields total_in and total_out can be used for statistics or
00191    progress reports. After compression, total_in holds the total size of
00192    the uncompressed data and may be saved for use in the decompressor
00193    (particularly if the decompressor wants to decompress everything in
00194    a single step).
00195 */
00196 
00197                         /* constants */
00198 
00199 #define Z_NO_FLUSH      0
00200 #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
00201 #define Z_SYNC_FLUSH    2
00202 #define Z_FULL_FLUSH    3
00203 #define Z_FINISH        4
00204 /* Allowed flush values; see deflate() below for details */
00205 
00206 #define Z_OK            0
00207 #define Z_STREAM_END    1
00208 #define Z_NEED_DICT     2
00209 #define Z_ERRNO        (-1)
00210 #define Z_STREAM_ERROR (-2)
00211 #define Z_DATA_ERROR   (-3)
00212 #define Z_MEM_ERROR    (-4)
00213 #define Z_BUF_ERROR    (-5)
00214 #define Z_VERSION_ERROR (-6)
00215 /* Return codes for the compression/decompression functions. Negative
00216  * values are errors, positive values are used for special but normal events.
00217  */
00218 
00219 #define Z_NO_COMPRESSION         0
00220 #define Z_BEST_SPEED             1
00221 #define Z_BEST_COMPRESSION       9
00222 #define Z_DEFAULT_COMPRESSION  (-1)
00223 /* compression levels */
00224 
00225 #define Z_FILTERED            1
00226 #define Z_HUFFMAN_ONLY        2
00227 #define Z_DEFAULT_STRATEGY    0
00228 /* compression strategy; see deflateInit2() below for details */
00229 
00230 #define Z_BINARY   0
00231 #define Z_ASCII    1
00232 #define Z_UNKNOWN  2
00233 /* Possible values of the data_type field */
00234 
00235 #define Z_DEFLATED   8
00236 /* The deflate compression method (the only one supported in this version) */
00237 
00238 #define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
00239 
00240 #define zlib_version zlibVersion()
00241 /* for compatibility with versions < 1.0.2 */
00242 
00243                         /* basic functions */
00244 
00245 // static const char * zlibVersion OF((void));
00246 /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
00247    If the first character differs, the library code actually used is
00248    not compatible with the zlib.h header file used by the application.
00249    This check is automatically made by deflateInit and inflateInit.
00250  */
00251 
00252 /* 
00253 int deflateInit OF((z_streamp strm, int level));
00254 
00255      Initializes the internal stream state for compression. The fields
00256    zalloc, zfree and opaque must be initialized before by the caller.
00257    If zalloc and zfree are set to Z_NULL, deflateInit updates them to
00258    use default allocation functions.
00259 
00260      The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
00261    1 gives best speed, 9 gives best compression, 0 gives no compression at
00262    all (the input data is simply copied a block at a time).
00263    Z_DEFAULT_COMPRESSION requests a default compromise between speed and
00264    compression (currently equivalent to level 6).
00265 
00266      deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
00267    enough memory, Z_STREAM_ERROR if level is not a valid compression level,
00268    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
00269    with the version assumed by the caller (ZLIB_VERSION).
00270    msg is set to null if there is no error message.  deflateInit does not
00271    perform any compression: this will be done by deflate().
00272 */
00273 
00274 
00275 // static int deflate OF((z_streamp strm, int flush));
00276 /*
00277     deflate compresses as much data as possible, and stops when the input
00278   buffer becomes empty or the output buffer becomes full. It may introduce some
00279   output latency (reading input without producing any output) except when
00280   forced to flush.
00281 
00282     The detailed semantics are as follows. deflate performs one or both of the
00283   following actions:
00284 
00285   - Compress more input starting at next_in and update next_in and avail_in
00286     accordingly. If not all input can be processed (because there is not
00287     enough room in the output buffer), next_in and avail_in are updated and
00288     processing will resume at this point for the next call of deflate().
00289 
00290   - Provide more output starting at next_out and update next_out and avail_out
00291     accordingly. This action is forced if the parameter flush is non zero.
00292     Forcing flush frequently degrades the compression ratio, so this parameter
00293     should be set only when necessary (in interactive applications).
00294     Some output may be provided even if flush is not set.
00295 
00296   Before the call of deflate(), the application should ensure that at least
00297   one of the actions is possible, by providing more input and/or consuming
00298   more output, and updating avail_in or avail_out accordingly; avail_out
00299   should never be zero before the call. The application can consume the
00300   compressed output when it wants, for example when the output buffer is full
00301   (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
00302   and with zero avail_out, it must be called again after making room in the
00303   output buffer because there might be more output pending.
00304 
00305     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
00306   flushed to the output buffer and the output is aligned on a byte boundary, so
00307   that the decompressor can get all input data available so far. (In particular
00308   avail_in is zero after the call if enough output space has been provided
00309   before the call.)  Flushing may degrade compression for some compression
00310   algorithms and so it should be used only when necessary.
00311 
00312     If flush is set to Z_FULL_FLUSH, all output is flushed as with
00313   Z_SYNC_FLUSH, and the compression state is reset so that decompression can
00314   restart from this point if previous compressed data has been damaged or if
00315   random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
00316   the compression.
00317 
00318     If deflate returns with avail_out == 0, this function must be called again
00319   with the same value of the flush parameter and more output space (updated
00320   avail_out), until the flush is complete (deflate returns with non-zero
00321   avail_out).
00322 
00323     If the parameter flush is set to Z_FINISH, pending input is processed,
00324   pending output is flushed and deflate returns with Z_STREAM_END if there
00325   was enough output space; if deflate returns with Z_OK, this function must be
00326   called again with Z_FINISH and more output space (updated avail_out) but no
00327   more input data, until it returns with Z_STREAM_END or an error. After
00328   deflate has returned Z_STREAM_END, the only possible operations on the
00329   stream are deflateReset or deflateEnd.
00330   
00331     Z_FINISH can be used immediately after deflateInit if all the compression
00332   is to be done in a single step. In this case, avail_out must be at least
00333   0.1% larger than avail_in plus 12 bytes.  If deflate does not return
00334   Z_STREAM_END, then it must be called again as described above.
00335 
00336     deflate() sets strm->adler to the adler32 checksum of all input read
00337   so (that is, total_in bytes).
00338 
00339     deflate() may update data_type if it can make a good guess about
00340   the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
00341   binary. This field is only for information purposes and does not affect
00342   the compression algorithm in any manner.
00343 
00344     deflate() returns Z_OK if some progress has been made (more input
00345   processed or more output produced), Z_STREAM_END if all input has been
00346   consumed and all output has been produced (only when flush is set to
00347   Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
00348   if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
00349   (for example avail_in or avail_out was zero).
00350 */
00351 
00352 
00353 // static int deflateEnd OF((z_streamp strm));
00354 /*
00355      All dynamically allocated data structures for this stream are freed.
00356    This function discards any unprocessed input and does not flush any
00357    pending output.
00358 
00359      deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
00360    stream state was inconsistent, Z_DATA_ERROR if the stream was freed
00361    prematurely (some input or output was discarded). In the error case,
00362    msg may be set but then points to a static string (which must not be
00363    deallocated).
00364 */
00365 
00366 
00367 /* 
00368 int inflateInit OF((z_streamp strm));
00369 
00370      Initializes the internal stream state for decompression. The fields
00371    next_in, avail_in, zalloc, zfree and opaque must be initialized before by
00372    the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
00373    value depends on the compression method), inflateInit determines the
00374    compression method from the zlib header and allocates all data structures
00375    accordingly; otherwise the allocation will be deferred to the first call of
00376    inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
00377    use default allocation functions.
00378 
00379      inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
00380    memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
00381    version assumed by the caller.  msg is set to null if there is no error
00382    message. inflateInit does not perform any decompression apart from reading
00383    the zlib header if present: this will be done by inflate().  (So next_in and
00384    avail_in may be modified, but next_out and avail_out are unchanged.)
00385 */
00386 
00387 
00388 static int inflate OF((z_streamp strm, int flush));
00389 /*
00390     inflate decompresses as much data as possible, and stops when the input
00391   buffer becomes empty or the output buffer becomes full. It may some
00392   introduce some output latency (reading input without producing any output)
00393   except when forced to flush.
00394 
00395   The detailed semantics are as follows. inflate performs one or both of the
00396   following actions:
00397 
00398   - Decompress more input starting at next_in and update next_in and avail_in
00399     accordingly. If not all input can be processed (because there is not
00400     enough room in the output buffer), next_in is updated and processing
00401     will resume at this point for the next call of inflate().
00402 
00403   - Provide more output starting at next_out and update next_out and avail_out
00404     accordingly.  inflate() provides as much output as possible, until there
00405     is no more input data or no more space in the output buffer (see below
00406     about the flush parameter).
00407 
00408   Before the call of inflate(), the application should ensure that at least
00409   one of the actions is possible, by providing more input and/or consuming
00410   more output, and updating the next_* and avail_* values accordingly.
00411   The application can consume the uncompressed output when it wants, for
00412   example when the output buffer is full (avail_out == 0), or after each
00413   call of inflate(). If inflate returns Z_OK and with zero avail_out, it
00414   must be called again after making room in the output buffer because there
00415   might be more output pending.
00416 
00417     If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
00418   output as possible to the output buffer. The flushing behavior of inflate is
00419   not specified for values of the flush parameter other than Z_SYNC_FLUSH
00420   and Z_FINISH, but the current implementation actually flushes as much output
00421   as possible anyway.
00422 
00423     inflate() should normally be called until it returns Z_STREAM_END or an
00424   error. However if all decompression is to be performed in a single step
00425   (a single call of inflate), the parameter flush should be set to
00426   Z_FINISH. In this case all pending input is processed and all pending
00427   output is flushed; avail_out must be large enough to hold all the
00428   uncompressed data. (The size of the uncompressed data may have been saved
00429   by the compressor for this purpose.) The next operation on this stream must
00430   be inflateEnd to deallocate the decompression state. The use of Z_FINISH
00431   is never required, but can be used to inform inflate that a faster routine
00432   may be used for the single inflate() call.
00433 
00434      If a preset dictionary is needed at this point (see inflateSetDictionary
00435   below), inflate sets strm-adler to the adler32 checksum of the
00436   dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise 
00437   it sets strm->adler to the adler32 checksum of all output produced
00438   so (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
00439   an error code as described below. At the end of the stream, inflate()
00440   checks that its computed adler32 checksum is equal to that saved by the
00441   compressor and returns Z_STREAM_END only if the checksum is correct.
00442 
00443     inflate() returns Z_OK if some progress has been made (more input processed
00444   or more output produced), Z_STREAM_END if the end of the compressed data has
00445   been reached and all uncompressed output has been produced, Z_NEED_DICT if a
00446   preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
00447   corrupted (input stream not conforming to the zlib format or incorrect
00448   adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
00449   (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
00450   enough memory, Z_BUF_ERROR if no progress is possible or if there was not
00451   enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
00452   case, the application may then call inflateSync to look for a good
00453   compression block.
00454 */
00455 
00456 
00457 static int inflateEnd OF((z_streamp strm));
00458 /*
00459      All dynamically allocated data structures for this stream are freed.
00460    This function discards any unprocessed input and does not flush any
00461    pending output.
00462 
00463      inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
00464    was inconsistent. In the error case, msg may be set but then points to a
00465    static string (which must not be deallocated).
00466 */
00467 
00468                         /* Advanced functions */
00469 
00470 /*
00471     The following functions are needed only in some special applications.
00472 */
00473 
00474 /*   
00475 int deflateInit2 OF((z_streamp strm,
00476                                      int  level,
00477                                      int  method,
00478                                      int  windowBits,
00479                                      int  memLevel,
00480                                      int  strategy));
00481 
00482      This is another version of deflateInit with more compression options. The
00483    fields next_in, zalloc, zfree and opaque must be initialized before by
00484    the caller.
00485 
00486      The method parameter is the compression method. It must be Z_DEFLATED in
00487    this version of the library.
00488 
00489      The windowBits parameter is the base two logarithm of the window size
00490    (the size of the history buffer).  It should be in the range 8..15 for this
00491    version of the library. Larger values of this parameter result in better
00492    compression at the expense of memory usage. The default value is 15 if
00493    deflateInit is used instead.
00494 
00495      The memLevel parameter specifies how much memory should be allocated
00496    for the internal compression state. memLevel=1 uses minimum memory but
00497    is slow and reduces compression ratio; memLevel=9 uses maximum memory
00498    for optimal speed. The default value is 8. See zconf.h for total memory
00499    usage as a function of windowBits and memLevel.
00500 
00501      The strategy parameter is used to tune the compression algorithm. Use the
00502    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
00503    filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
00504    string match).  Filtered data consists mostly of small values with a
00505    somewhat random distribution. In this case, the compression algorithm is
00506    tuned to compress them better. The effect of Z_FILTERED is to force more
00507    Huffman coding and less string matching; it is somewhat intermediate
00508    between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
00509    the compression ratio but not the correctness of the compressed output even
00510    if it is not set appropriately.
00511 
00512       deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
00513    memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
00514    method). msg is set to null if there is no error message.  deflateInit2 does
00515    not perform any compression: this will be done by deflate().
00516 */
00517                             
00518 /*
00519 static int deflateSetDictionary OF((z_streamp strm,
00520                                              const Byte *dictionary,
00521                                              uInt  dictLength));
00522 */
00523 /*
00524      Initializes the compression dictionary from the given byte sequence
00525    without producing any compressed output. This function must be called
00526    immediately after deflateInit, deflateInit2 or deflateReset, before any
00527    call of deflate. The compressor and decompressor must use exactly the same
00528    dictionary (see inflateSetDictionary).
00529 
00530      The dictionary should consist of strings (byte sequences) that are likely
00531    to be encountered later in the data to be compressed, with the most commonly
00532    used strings preferably put towards the end of the dictionary. Using a
00533    dictionary is most useful when the data to be compressed is short and can be
00534    predicted with good accuracy; the data can then be compressed better than
00535    with the default empty dictionary.
00536 
00537      Depending on the size of the compression data structures selected by
00538    deflateInit or deflateInit2, a part of the dictionary may in effect be
00539    discarded, for example if the dictionary is larger than the window size in
00540    deflate or deflate2. Thus the strings most likely to be useful should be
00541    put at the end of the dictionary, not at the front.
00542 
00543      Upon return of this function, strm->adler is set to the Adler32 value
00544    of the dictionary; the decompressor may later use this value to determine
00545    which dictionary has been used by the compressor. (The Adler32 value
00546    applies to the whole dictionary even if only a subset of the dictionary is
00547    actually used by the compressor.)
00548 
00549      deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
00550    parameter is invalid (such as NULL dictionary) or the stream state is
00551    inconsistent (for example if deflate has already been called for this stream
00552    or if the compression method is bsort). deflateSetDictionary does not
00553    perform any compression: this will be done by deflate().
00554 */
00555 
00556 /*
00557 static int deflateCopy OF((z_streamp dest,
00558                                     z_streamp source));
00559 */
00560 /*
00561      Sets the destination stream as a complete copy of the source stream.
00562 
00563      This function can be useful when several compression strategies will be
00564    tried, for example when there are several ways of pre-processing the input
00565    data with a filter. The streams that will be discarded should then be freed
00566    by calling deflateEnd.  Note that deflateCopy duplicates the internal
00567    compression state which can be quite large, so this strategy is slow and
00568    can consume lots of memory.
00569 
00570      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
00571    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
00572    (such as zalloc being NULL). msg is left unchanged in both source and
00573    destination.
00574 */
00575 
00576 // static int deflateReset OF((z_streamp strm));
00577 /*
00578      This function is equivalent to deflateEnd followed by deflateInit,
00579    but does not free and reallocate all the internal compression state.
00580    The stream will keep the same compression level and any other attributes
00581    that may have been set by deflateInit2.
00582 
00583       deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
00584    stream state was inconsistent (such as zalloc or state being NULL).
00585 */
00586 
00587 /*
00588 static int deflateParams OF((z_streamp strm,
00589                       int level,
00590                       int strategy));
00591 */
00592 /*
00593      Dynamically update the compression level and compression strategy.  The
00594    interpretation of level and strategy is as in deflateInit2.  This can be
00595    used to switch between compression and straight copy of the input data, or
00596    to switch to a different kind of input data requiring a different
00597    strategy. If the compression level is changed, the input available so far
00598    is compressed with the old level (and may be flushed); the new level will
00599    take effect only at the next call of deflate().
00600 
00601      Before the call of deflateParams, the stream state must be set as for
00602    a call of deflate(), since the currently available input may have to
00603    be compressed and flushed. In particular, strm->avail_out must be non-zero.
00604 
00605      deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
00606    stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
00607    if strm->avail_out was zero.
00608 */
00609 
00610 /*   
00611 int inflateInit2 OF((z_streamp strm,
00612                                      int  windowBits));
00613 
00614      This is another version of inflateInit with an extra parameter. The
00615    fields next_in, avail_in, zalloc, zfree and opaque must be initialized
00616    before by the caller.
00617 
00618      The windowBits parameter is the base two logarithm of the maximum window
00619    size (the size of the history buffer).  It should be in the range 8..15 for
00620    this version of the library. The default value is 15 if inflateInit is used
00621    instead. If a compressed stream with a larger window size is given as
00622    input, inflate() will return with the error code Z_DATA_ERROR instead of
00623    trying to allocate a larger window.
00624 
00625       inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
00626    memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
00627    memLevel). msg is set to null if there is no error message.  inflateInit2
00628    does not perform any decompression apart from reading the zlib header if
00629    present: this will be done by inflate(). (So next_in and avail_in may be
00630    modified, but next_out and avail_out are unchanged.)
00631 */
00632 
00633 /*
00634 static int inflateSetDictionary OF((z_streamp strm,
00635                                              const Byte *dictionary,
00636                                              uInt  dictLength));
00637 */
00638 /*
00639      Initializes the decompression dictionary from the given uncompressed byte
00640    sequence. This function must be called immediately after a call of inflate
00641    if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
00642    can be determined from the Adler32 value returned by this call of
00643    inflate. The compressor and decompressor must use exactly the same
00644    dictionary (see deflateSetDictionary).
00645 
00646      inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
00647    parameter is invalid (such as NULL dictionary) or the stream state is
00648    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
00649    expected one (incorrect Adler32 value). inflateSetDictionary does not
00650    perform any decompression: this will be done by subsequent calls of
00651    inflate().
00652 */
00653 
00654 // static int inflateSync OF((z_streamp strm));
00655 /* 
00656     Skips invalid compressed data until a full flush point (see above the
00657   description of deflate with Z_FULL_FLUSH) can be found, or until all
00658   available input is skipped. No output is provided.
00659 
00660     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
00661   if no more input was provided, Z_DATA_ERROR if no flush point has been found,
00662   or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
00663   case, the application may save the current current value of total_in which
00664   indicates where valid compressed data was found. In the error case, the
00665   application may repeatedly call inflateSync, providing more input each time,
00666   until success or end of the input data.
00667 */
00668 
00669 static int inflateReset OF((z_streamp strm));
00670 /*
00671      This function is equivalent to inflateEnd followed by inflateInit,
00672    but does not free and reallocate all the internal decompression state.
00673    The stream will keep attributes that may have been set by inflateInit2.
00674 
00675       inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
00676    stream state was inconsistent (such as zalloc or state being NULL).
00677 */
00678 
00679 
00680                         /* utility functions */
00681 
00682 /*
00683      The following utility functions are implemented on top of the
00684    basic stream-oriented functions. To simplify the interface, some
00685    default options are assumed (compression level and memory usage,
00686    standard memory allocation functions). The source code of these
00687    utility functions can easily be modified if you need special options.
00688 */
00689 
00690 /*
00691 static int compress OF((Byte *dest,   uLong *destLen,
00692                                  const Byte *source, uLong sourceLen));
00693 */
00694 /*
00695      Compresses the source buffer into the destination buffer.  sourceLen is
00696    the byte length of the source buffer. Upon entry, destLen is the total
00697    size of the destination buffer, which must be at least 0.1% larger than
00698    sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
00699    compressed buffer.
00700      This function can be used to compress a whole file at once if the
00701    input file is mmap'ed.
00702      compress returns Z_OK if success, Z_MEM_ERROR if there was not
00703    enough memory, Z_BUF_ERROR if there was not enough room in the output
00704    buffer.
00705 */
00706 
00707 /*
00708 static int compress2 OF((Byte *dest,   uLong *destLen,
00709                                   const Byte *source, uLong sourceLen,
00710                                   int level));
00711 */
00712 /*
00713      Compresses the source buffer into the destination buffer. The level
00714    parameter has the same meaning as in deflateInit.  sourceLen is the byte
00715    length of the source buffer. Upon entry, destLen is the total size of the
00716    destination buffer, which must be at least 0.1% larger than sourceLen plus
00717    12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
00718 
00719      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
00720    memory, Z_BUF_ERROR if there was not enough room in the output buffer,
00721    Z_STREAM_ERROR if the level parameter is invalid.
00722 */
00723 
00724 /*
00725 static int uncompress OF((Byte *dest,   uLong *destLen,
00726                                    const Byte *source, uLong sourceLen));
00727 */                                   
00728 /*
00729      Decompresses the source buffer into the destination buffer.  sourceLen is
00730    the byte length of the source buffer. Upon entry, destLen is the total
00731    size of the destination buffer, which must be large enough to hold the
00732    entire uncompressed data. (The size of the uncompressed data must have
00733    been saved previously by the compressor and transmitted to the decompressor
00734    by some mechanism outside the scope of this compression library.)
00735    Upon exit, destLen is the actual size of the compressed buffer.
00736      This function can be used to decompress a whole file at once if the
00737    input file is mmap'ed.
00738 
00739      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
00740    enough memory, Z_BUF_ERROR if there was not enough room in the output
00741    buffer, or Z_DATA_ERROR if the input data was corrupted.
00742 */
00743 
00744 
00745 typedef voidp gzFile;
00746 
00747 gzFile gzopen  OF((const char *path, const char *mode));
00748 /*
00749      Opens a gzip (.gz) file for reading or writing. The mode parameter
00750    is as in fopen ("rb" or "wb") but can also include a compression level
00751    ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
00752    Huffman only compression as in "wb1h". (See the description
00753    of deflateInit2 for more information about the strategy parameter.)
00754 
00755      gzopen can be used to read a file which is not in gzip format; in this
00756    case gzread will directly read from the file without decompression.
00757 
00758      gzopen returns NULL if the file could not be opened or if there was
00759    insufficient memory to allocate the (de)compression state; errno
00760    can be checked to distinguish the two cases (if errno is zero, the
00761    zlib error is Z_MEM_ERROR).  */
00762 
00763 gzFile gzdopen  OF((int fd, const char *mode));
00764 /*
00765      gzdopen() associates a gzFile with the file descriptor fd.  File
00766    descriptors are obtained from calls like open, dup, creat, pipe or
00767    fileno (in the file has been previously opened with fopen).
00768    The mode parameter is as in gzopen.
00769      The next call of gzclose on the returned gzFile will also close the
00770    file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
00771    descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
00772      gzdopen returns NULL if there was insufficient memory to allocate
00773    the (de)compression state.
00774 */
00775 
00776 int gzsetparams OF((gzFile file, int level, int strategy));
00777 /*
00778      Dynamically update the compression level or strategy. See the description
00779    of deflateInit2 for the meaning of these parameters.
00780      gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
00781    opened for writing.
00782 */
00783 
00784 int    gzread  OF((gzFile file, voidp buf, unsigned len));
00785 /*
00786      Reads the given number of uncompressed bytes from the compressed file.
00787    If the input file was not in gzip format, gzread copies the given number
00788    of bytes into the buffer.
00789      gzread returns the number of uncompressed bytes actually read (0 for
00790    end of file, -1 for error). */
00791 
00792 int    gzwrite OF((gzFile file, 
00793                    const voidp buf, unsigned len));
00794 /*
00795      Writes the given number of uncompressed bytes into the compressed file.
00796    gzwrite returns the number of uncompressed bytes actually written
00797    (0 in case of error).
00798 */
00799 
00800 int    QDECL gzprintf OF((gzFile file, const char *format, ...));
00801 /*
00802      Converts, formats, and writes the args to the compressed file under
00803    control of the format string, as in fprintf. gzprintf returns the number of
00804    uncompressed bytes actually written (0 in case of error).
00805 */
00806 
00807 int gzputs OF((gzFile file, const char *s));
00808 /*
00809       Writes the given null-terminated string to the compressed file, excluding
00810    the terminating null character.
00811       gzputs returns the number of characters written, or -1 in case of error.
00812 */
00813 
00814 char * gzgets OF((gzFile file, char *buf, int len));
00815 /*
00816       Reads bytes from the compressed file until len-1 characters are read, or
00817    a newline character is read and transferred to buf, or an end-of-file
00818    condition is encountered.  The string is then terminated with a null
00819    character.
00820       gzgets returns buf, or Z_NULL in case of error.
00821 */
00822 
00823 int    gzputc OF((gzFile file, int c));
00824 /*
00825       Writes c, converted to an unsigned char, into the compressed file.
00826    gzputc returns the value that was written, or -1 in case of error.
00827 */
00828 
00829 int    gzgetc OF((gzFile file));
00830 /*
00831       Reads one byte from the compressed file. gzgetc returns this byte
00832    or -1 in case of end of file or error.
00833 */
00834 
00835 int    gzflush OF((gzFile file, int flush));
00836 /*
00837      Flushes all pending output into the compressed file. The parameter
00838    flush is as in the deflate() function. The return value is the zlib
00839    error number (see function gzerror below). gzflush returns Z_OK if
00840    the flush parameter is Z_FINISH and all output could be flushed.
00841      gzflush should be called only when strictly necessary because it can
00842    degrade compression.
00843 */
00844 
00845 long gzseek OF((gzFile file,
00846                       long offset, int whence));
00847 /* 
00848       Sets the starting position for the next gzread or gzwrite on the
00849    given compressed file. The offset represents a number of bytes in the
00850    uncompressed data stream. The whence parameter is defined as in lseek(2);
00851    the value SEEK_END is not supported.
00852      If the file is opened for reading, this function is emulated but can be
00853    extremely slow. If the file is opened for writing, only forward seeks are
00854    supported; gzseek then compresses a sequence of zeroes up to the new
00855    starting position.
00856 
00857       gzseek returns the resulting offset location as measured in bytes from
00858    the beginning of the uncompressed stream, or -1 in case of error, in
00859    particular if the file is opened for writing and the new starting position
00860    would be before the current position.
00861 */
00862 
00863 int    gzrewind OF((gzFile file));
00864 /*
00865      Rewinds the given file. This function is supported only for reading.
00866 
00867    gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
00868 */
00869 
00870 long    gztell OF((gzFile file));
00871 /*
00872      Returns the starting position for the next gzread or gzwrite on the
00873    given compressed file. This position represents a number of bytes in the
00874    uncompressed data stream.
00875 
00876    gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
00877 */
00878 
00879 int gzeof OF((gzFile file));
00880 /*
00881      Returns 1 when EOF has previously been detected reading the given
00882    input stream, otherwise zero.
00883 */
00884 
00885 int    gzclose OF((gzFile file));
00886 /*
00887      Flushes all pending output if necessary, closes the compressed file
00888    and deallocates all the (de)compression state. The return value is the zlib
00889    error number (see function gzerror below).
00890 */
00891 
00892 // static const char * gzerror OF((gzFile file, int *errnum));
00893 /*
00894      Returns the error message for the last error which occurred on the
00895    given compressed file. errnum is set to zlib error number. If an
00896    error occurred in the file system and not in the compression library,
00897    errnum is set to Z_ERRNO and the application may consult errno
00898    to get the exact error code.
00899 */
00900 
00901                         /* checksum functions */
00902 
00903 /*
00904      These functions are not related to compression but are exported
00905    anyway because they might be useful in applications using the
00906    compression library.
00907 */
00908 
00909 static uLong adler32 OF((uLong adler, const Byte *buf, uInt len));
00910 
00911 /*
00912      Update a running Adler-32 checksum with the bytes buf[0..len-1] and
00913    return the updated checksum. If buf is NULL, this function returns
00914    the required initial value for the checksum.
00915    An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
00916    much faster. Usage example:
00917 
00918      uLong adler = adler32(0L, Z_NULL, 0);
00919 
00920      while (read_buffer(buffer, length) != EOF) {
00921        adler = adler32(adler, buffer, length);
00922      }
00923      if (adler != original_adler) error();
00924 */
00925 
00926                         /* various hacks, don't look :) */
00927 
00928 /* deflateInit and inflateInit are macros to allow checking the zlib version
00929  * and the compiler's view of z_stream:
00930  */
00931 /*
00932 static int deflateInit_ OF((z_streamp strm, int level,
00933                                      const char *version, int stream_size));
00934 static int inflateInit_ OF((z_streamp strm,
00935                                      const char *version, int stream_size));
00936 static int deflateInit2_ OF((z_streamp strm, int  level, int  method,
00937                                       int windowBits, int memLevel,
00938                                       int strategy, const char *version,
00939                                       int stream_size));
00940 */
00941 static int inflateInit2_ OF((z_streamp strm, int  windowBits,
00942                                       const char *version, int stream_size));
00943 
00944 #define deflateInit(strm, level) \
00945         deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
00946 #define inflateInit(strm) \
00947         inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
00948 #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
00949         deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
00950                       (strategy),           ZLIB_VERSION, sizeof(z_stream))
00951 #define inflateInit2(strm, windowBits) \
00952         inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
00953 
00954 
00955 // static const char   * zError           OF((int err));
00956 // static int            inflateSyncPoint OF((z_streamp z));
00957 // static const uLong * get_crc_table    OF((void));
00958 
00959 typedef unsigned char  uch;
00960 typedef unsigned short ush;
00961 typedef unsigned long  ulg;
00962 
00963 // static const char *z_errmsg[10]; /* indexed by 2-zlib_error */
00964 /* (size given to avoid silly warnings with Visual C++) */
00965 
00966 #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
00967 
00968 #define ERR_RETURN(strm,err) \
00969   return (strm->msg = (char*)ERR_MSG(err), (err))
00970 /* To be used only when the state is known to be valid */
00971 
00972         /* common constants */
00973 
00974 #ifndef DEF_WBITS
00975 #  define DEF_WBITS MAX_WBITS
00976 #endif
00977 /* default windowBits for decompression. MAX_WBITS is for compression only */
00978 
00979 #if MAX_MEM_LEVEL >= 8
00980 #  define DEF_MEM_LEVEL 8
00981 #else
00982 #  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
00983 #endif
00984 /* default memLevel */
00985 
00986 #define STORED_BLOCK 0
00987 #define STATIC_TREES 1
00988 #define DYN_TREES    2
00989 /* The three kinds of block type */
00990 
00991 #define MIN_MATCH  3
00992 #define MAX_MATCH  258
00993 /* The minimum and maximum match lengths */
00994 
00995 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
00996 
00997         /* target dependencies */
00998 
00999         /* Common defaults */
01000 
01001 #ifndef OS_CODE
01002 #  define OS_CODE  0x03  /* assume Unix */
01003 #endif
01004 
01005 #ifndef F_OPEN
01006 #  define F_OPEN(name, mode) fopen((name), (mode))
01007 #endif
01008 
01009          /* functions */
01010 
01011 #ifdef HAVE_STRERROR
01012    extern char *strerror OF((int));
01013 #  define zstrerror(errnum) strerror(errnum)
01014 #else
01015 #  define zstrerror(errnum) ""
01016 #endif
01017 
01018 #define zmemcpy Com_Memcpy
01019 #define zmemcmp memcmp
01020 #define zmemzero(dest, len) Com_Memset(dest, 0, len)
01021 
01022 /* Diagnostic functions */
01023 #ifdef _ZIP_DEBUG_
01024    int z_verbose = 0;
01025 #  define Assert(cond,msg) assert(cond);
01026    //{if(!(cond)) Sys_Error(msg);}
01027 #  define Trace(x) {if (z_verbose>=0) Sys_Error x ;}
01028 #  define Tracev(x) {if (z_verbose>0) Sys_Error x ;}
01029 #  define Tracevv(x) {if (z_verbose>1) Sys_Error x ;}
01030 #  define Tracec(c,x) {if (z_verbose>0 && (c)) Sys_Error x ;}
01031 #  define Tracecv(c,x) {if (z_verbose>1 && (c)) Sys_Error x ;}
01032 #else
01033 #  define Assert(cond,msg)
01034 #  define Trace(x)
01035 #  define Tracev(x)
01036 #  define Tracevv(x)
01037 #  define Tracec(c,x)
01038 #  define Tracecv(c,x)
01039 #endif
01040 
01041 
01042 typedef uLong (*check_func) OF((uLong check, const Byte *buf, uInt len));
01043 static voidp zcalloc OF((voidp opaque, unsigned items, unsigned size));
01044 static void   zcfree  OF((voidp opaque, voidp ptr));
01045 
01046 #define ZALLOC(strm, items, size) \
01047            (*((strm)->zalloc))((strm)->opaque, (items), (size))
01048 #define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidp)(addr))
01049 #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
01050 
01051 
01052 #if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) && \
01053                       !defined(CASESENSITIVITYDEFAULT_NO)
01054 #define CASESENSITIVITYDEFAULT_NO
01055 #endif
01056 
01057 
01058 #ifndef UNZ_BUFSIZE
01059 #define UNZ_BUFSIZE (65536)
01060 #endif
01061 
01062 #ifndef UNZ_MAXFILENAMEINZIP
01063 #define UNZ_MAXFILENAMEINZIP (256)
01064 #endif
01065 
01066 #ifndef ALLOC
01067 # define ALLOC(size) (Z_Malloc(size))
01068 #endif
01069 #ifndef TRYFREE
01070 # define TRYFREE(p) {if (p) Z_Free(p);}
01071 #endif
01072 
01073 #define SIZECENTRALDIRITEM (0x2e)
01074 #define SIZEZIPLOCALHEADER (0x1e)
01075 
01076 
01077 
01078 /* ===========================================================================
01079      Read a byte from a gz_stream; update next_in and avail_in. Return EOF
01080    for end of file.
01081    IN assertion: the stream s has been sucessfully opened for reading.
01082 */
01083 
01084 /*
01085 static int unzlocal_getByte(FILE *fin,int *pi)
01086 {
01087     unsigned char c;
01088     int err = fread(&c, 1, 1, fin);
01089     if (err==1)
01090     {
01091         *pi = (int)c;
01092         return UNZ_OK;
01093     }
01094     else
01095     {
01096         if (ferror(fin)) 
01097             return UNZ_ERRNO;
01098         else
01099             return UNZ_EOF;
01100     }
01101 }
01102 */
01103 
01104 /* ===========================================================================
01105    Reads a long in LSB order from the given gz_stream. Sets 
01106 */
01107 static int unzlocal_getShort (FILE* fin, uLong *pX)
01108 {
01109     short   v;
01110 
01111     fread( &v, sizeof(v), 1, fin );
01112 
01113     *pX = LittleShort( v);
01114     return UNZ_OK;
01115 
01116 /*
01117     uLong x ;
01118     int i;
01119     int err;
01120 
01121     err = unzlocal_getByte(fin,&i);
01122     x = (uLong)i;
01123     
01124     if (err==UNZ_OK)
01125         err = unzlocal_getByte(fin,&i);
01126     x += ((uLong)i)<<8;
01127    
01128     if (err==UNZ_OK)
01129         *pX = x;
01130     else
01131         *pX = 0;
01132     return err;
01133 */
01134 }
01135 
01136 static int unzlocal_getLong (FILE *fin, uLong *pX)
01137 {
01138     int     v;
01139 
01140     fread( &v, sizeof(v), 1, fin );
01141 
01142     *pX = LittleLong( v);
01143     return UNZ_OK;
01144 
01145 /*
01146     uLong x ;
01147     int i;
01148     int err;
01149 
01150     err = unzlocal_getByte(fin,&i);
01151     x = (uLong)i;
01152     
01153     if (err==UNZ_OK)
01154         err = unzlocal_getByte(fin,&i);
01155     x += ((uLong)i)<<8;
01156 
01157     if (err==UNZ_OK)
01158         err = unzlocal_getByte(fin,&i);
01159     x += ((uLong)i)<<16;
01160 
01161     if (err==UNZ_OK)
01162         err = unzlocal_getByte(fin,&i);
01163     x += ((uLong)i)<<24;
01164    
01165     if (err==UNZ_OK)
01166         *pX = x;
01167     else
01168         *pX = 0;
01169     return err;
01170 */
01171 }
01172 
01173 
01174 /* My own strcmpi / strcasecmp */
01175 static int strcmpcasenosensitive_internal (const char* fileName1,const char* fileName2)
01176 {
01177     for (;;)
01178     {
01179         char c1=*(fileName1++);
01180         char c2=*(fileName2++);
01181         if ((c1>='a') && (c1<='z'))
01182             c1 -= 0x20;
01183         if ((c2>='a') && (c2<='z'))
01184             c2 -= 0x20;
01185         if (c1=='\0')
01186             return ((c2=='\0') ? 0 : -1);
01187         if (c2=='\0')
01188             return 1;
01189         if (c1<c2)
01190             return -1;
01191         if (c1>c2)
01192             return 1;
01193     }
01194 }
01195 
01196 
01197 #ifdef  CASESENSITIVITYDEFAULT_NO
01198 #define CASESENSITIVITYDEFAULTVALUE 2
01199 #else
01200 #define CASESENSITIVITYDEFAULTVALUE 1
01201 #endif
01202 
01203 #ifndef STRCMPCASENOSENTIVEFUNCTION
01204 #define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
01205 #endif
01206 
01207 /* 
01208    Compare two filename (fileName1,fileName2).
01209    If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
01210    If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
01211                                                                 or strcasecmp)
01212    If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
01213         (like 1 on Unix, 2 on Windows)
01214 
01215 */
01216 extern  int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity)
01217 {
01218     if (iCaseSensitivity==0)
01219         iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE;
01220 
01221     if (iCaseSensitivity==1)
01222         return strcmp(fileName1,fileName2);
01223 
01224     return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2);
01225 } 
01226 
01227 #define BUFREADCOMMENT (0x400)
01228 
01229 /*
01230   Locate the Central directory of a zipfile (at the end, just before
01231     the global comment)
01232 */
01233 extern uLong unzlocal_SearchCentralDir(FILE *fin)
01234 {
01235     unsigned char* buf;
01236     uLong uSizeFile;
01237     uLong uBackRead;
01238     uLong uMaxBack=0xffff; /* maximum size of global comment */
01239     uLong uPosFound=0;
01240     
01241     if (fseek(fin,0,SEEK_END) != 0)
01242         return 0;
01243 
01244 
01245     uSizeFile = ftell( fin );
01246     
01247     if (uMaxBack>uSizeFile)
01248         uMaxBack = uSizeFile;
01249 
01250     buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
01251     if (buf==NULL)
01252         return 0;
01253 
01254     uBackRead = 4;
01255     while (uBackRead<uMaxBack)
01256     {
01257         uLong uReadSize,uReadPos ;
01258         int i;
01259         if (uBackRead+BUFREADCOMMENT>uMaxBack) 
01260             uBackRead = uMaxBack;
01261         else
01262             uBackRead+=BUFREADCOMMENT;
01263         uReadPos = uSizeFile-uBackRead ;
01264         
01265         uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? 
01266                      (BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
01267         if (fseek(fin,uReadPos,SEEK_SET)!=0)
01268             break;
01269 
01270         if (fread(buf,(uInt)uReadSize,1,fin)!=1)
01271             break;
01272 
01273                 for (i=(int)uReadSize-3; (i--)>0;)
01274             if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && 
01275                 ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
01276             {
01277                 uPosFound = uReadPos+i;
01278                 break;
01279             }
01280 
01281         if (uPosFound!=0)
01282             break;
01283     }
01284     TRYFREE(buf);
01285     return uPosFound;
01286 }
01287 
01288 extern unzFile unzReOpen (const char* path, unzFile file)
01289 {
01290     unz_s *s;
01291     FILE * fin;
01292 
01293     fin=fopen(path,"rb");
01294     if (fin==NULL)
01295         return NULL;
01296 
01297     s=(unz_s*)ALLOC(sizeof(unz_s));
01298     Com_Memcpy(s, (unz_s*)file, sizeof(unz_s));
01299 
01300     s->file = fin;
01301     return (unzFile)s;  
01302 }
01303 
01304 /*
01305   Open a Zip file. path contain the full pathname (by example,
01306      on a Windows NT computer "c:\\test\\zlib109.zip" or on an Unix computer
01307      "zlib/zlib109.zip".
01308      If the zipfile cannot be opened (file don't exist or in not valid), the
01309        return value is NULL.
01310      Else, the return value is a unzFile Handle, usable with other function
01311        of this unzip package.
01312 */
01313 extern unzFile unzOpen (const char* path)
01314 {
01315     unz_s us;
01316     unz_s *s;
01317     uLong central_pos,uL;
01318     FILE * fin ;
01319 
01320     uLong number_disk;          /* number of the current dist, used for 
01321                                    spaning ZIP, unsupported, always 0*/
01322     uLong number_disk_with_CD;  /* number the the disk with central dir, used
01323                                    for spaning ZIP, unsupported, always 0*/
01324     uLong number_entry_CD;      /* total number of entries in
01325                                    the central dir 
01326                                    (same than number_entry on nospan) */
01327 
01328     int err=UNZ_OK;
01329 
01330     fin=fopen(path,"rb");
01331     if (fin==NULL)
01332         return NULL;
01333 
01334     central_pos = unzlocal_SearchCentralDir(fin);
01335     if (central_pos==0)
01336         err=UNZ_ERRNO;
01337 
01338     if (fseek(fin,central_pos,SEEK_SET)!=0)
01339         err=UNZ_ERRNO;
01340 
01341     /* the signature, already checked */
01342     if (unzlocal_getLong(fin,&uL)!=UNZ_OK)
01343         err=UNZ_ERRNO;
01344 
01345     /* number of this disk */
01346     if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK)
01347         err=UNZ_ERRNO;
01348 
01349     /* number of the disk with the start of the central directory */
01350     if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK)
01351         err=UNZ_ERRNO;
01352 
01353     /* total number of entries in the central dir on this disk */
01354     if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK)
01355         err=UNZ_ERRNO;
01356 
01357     /* total number of entries in the central dir */
01358     if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK)
01359         err=UNZ_ERRNO;
01360 
01361     if ((number_entry_CD!=us.gi.number_entry) ||
01362         (number_disk_with_CD!=0) ||
01363         (number_disk!=0))
01364         err=UNZ_BADZIPFILE;
01365 
01366     /* size of the central directory */
01367     if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK)
01368         err=UNZ_ERRNO;
01369 
01370     /* offset of start of central directory with respect to the 
01371           starting disk number */
01372     if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK)
01373         err=UNZ_ERRNO;
01374 
01375     /* zipfile comment length */
01376     if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK)
01377         err=UNZ_ERRNO;
01378 
01379     if ((central_pos<us.offset_central_dir+us.size_central_dir) && 
01380         (err==UNZ_OK))
01381         err=UNZ_BADZIPFILE;
01382 
01383     if (err!=UNZ_OK)
01384     {
01385         fclose(fin);
01386         return NULL;
01387     }
01388 
01389     us.file=fin;
01390     us.byte_before_the_zipfile = central_pos -
01391                             (us.offset_central_dir+us.size_central_dir);
01392     us.central_pos = central_pos;
01393     us.pfile_in_zip_read = NULL;
01394     
01395 
01396     s=(unz_s*)ALLOC(sizeof(unz_s));
01397     *s=us;
01398 //  unzGoToFirstFile((unzFile)s);   
01399     return (unzFile)s;  
01400 }
01401 
01402 
01403 /*
01404   Close a ZipFile opened with unzipOpen.
01405   If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
01406     these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
01407   return UNZ_OK if there is no problem. */
01408 extern int unzClose (unzFile file)
01409 {
01410     unz_s* s;
01411     if (file==NULL)
01412         return UNZ_PARAMERROR;
01413     s=(unz_s*)file;
01414 
01415     if (s->pfile_in_zip_read!=NULL)
01416         unzCloseCurrentFile(file);
01417 
01418     fclose(s->file);
01419     TRYFREE(s);
01420     return UNZ_OK;
01421 }
01422 
01423 
01424 /*
01425   Write info about the ZipFile in the *pglobal_info structure.
01426   No preparation of the structure is needed
01427   return UNZ_OK if there is no problem. */
01428 extern int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info)
01429 {
01430     unz_s* s;
01431     if (file==NULL)
01432         return UNZ_PARAMERROR;
01433     s=(unz_s*)file;
01434     *pglobal_info=s->gi;
01435     return UNZ_OK;
01436 }
01437 
01438 
01439 /*
01440    Translate date/time from Dos format to tm_unz (readable more easilty)
01441 */
01442 static void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm)
01443 {
01444     uLong uDate;
01445     uDate = (uLong)(ulDosDate>>16);
01446     ptm->tm_mday = (uInt)(uDate&0x1f) ;
01447     ptm->tm_mon =  (uInt)((((uDate)&0x1E0)/0x20)-1) ;
01448     ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
01449 
01450     ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
01451     ptm->tm_min =  (uInt) ((ulDosDate&0x7E0)/0x20) ;
01452     ptm->tm_sec =  (uInt) (2*(ulDosDate&0x1f)) ;
01453 }
01454 
01455 /*
01456   Get Info about the current file in the zipfile, with internal only info
01457 */
01458 static int unzlocal_GetCurrentFileInfoInternal (unzFile file,
01459                                                   unz_file_info *pfile_info,
01460                                                   unz_file_info_internal 
01461                                                   *pfile_info_internal,
01462                                                   char *szFileName,
01463                                                   uLong fileNameBufferSize,
01464                                                   void *extraField,
01465                                                   uLong extraFieldBufferSize,
01466                                                   char *szComment,
01467                                                   uLong commentBufferSize)
01468 {
01469     unz_s* s;
01470     unz_file_info file_info;
01471     unz_file_info_internal file_info_internal;
01472     int err=UNZ_OK;
01473     uLong uMagic;
01474     long lSeek=0;
01475 
01476     if (file==NULL)
01477         return UNZ_PARAMERROR;
01478     s=(unz_s*)file;
01479     if (fseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0)
01480         err=UNZ_ERRNO;
01481 
01482 
01483     /* we check the magic */
01484     if (err==UNZ_OK) {
01485         if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
01486             err=UNZ_ERRNO;
01487         else if (uMagic!=0x02014b50)
01488             err=UNZ_BADZIPFILE;
01489     }
01490     if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK)
01491         err=UNZ_ERRNO;
01492 
01493     if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK)
01494         err=UNZ_ERRNO;
01495 
01496     if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK)
01497         err=UNZ_ERRNO;
01498 
01499     if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK)
01500         err=UNZ_ERRNO;
01501 
01502     if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK)
01503         err=UNZ_ERRNO;
01504 
01505     unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
01506 
01507     if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK)
01508         err=UNZ_ERRNO;
01509 
01510     if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK)
01511         err=UNZ_ERRNO;
01512 
01513     if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK)
01514         err=UNZ_ERRNO;
01515 
01516     if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK)
01517         err=UNZ_ERRNO;
01518 
01519     if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK)
01520         err=UNZ_ERRNO;
01521 
01522     if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK)
01523         err=UNZ_ERRNO;
01524 
01525     if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK)
01526         err=UNZ_ERRNO;
01527 
01528     if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK)
01529         err=UNZ_ERRNO;
01530 
01531     if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK)
01532         err=UNZ_ERRNO;
01533 
01534     if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
01535         err=UNZ_ERRNO;
01536 
01537     lSeek+=file_info.size_filename;
01538     if ((err==UNZ_OK) && (szFileName!=NULL))
01539     {
01540         uLong uSizeRead ;
01541         if (file_info.size_filename<fileNameBufferSize)
01542         {
01543             *(szFileName+file_info.size_filename)='\0';
01544             uSizeRead = file_info.size_filename;
01545         }
01546         else
01547             uSizeRead = fileNameBufferSize;
01548 
01549         if ((file_info.size_filename>0) && (fileNameBufferSize>0))
01550             if (fread(szFileName,(uInt)uSizeRead,1,s->file)!=1)
01551                 err=UNZ_ERRNO;
01552         lSeek -= uSizeRead;
01553     }
01554 
01555     
01556     if ((err==UNZ_OK) && (extraField!=NULL))
01557     {
01558         uLong uSizeRead ;
01559         if (file_info.size_file_extra<extraFieldBufferSize)
01560             uSizeRead = file_info.size_file_extra;
01561         else
01562             uSizeRead = extraFieldBufferSize;
01563 
01564         if (lSeek!=0) {
01565             if (fseek(s->file,lSeek,SEEK_CUR)==0)
01566                 lSeek=0;
01567             else
01568                 err=UNZ_ERRNO;
01569         }
01570         if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0)) {
01571             if (fread(extraField,(uInt)uSizeRead,1,s->file)!=1)
01572                 err=UNZ_ERRNO;
01573         }
01574         lSeek += file_info.size_file_extra - uSizeRead;
01575     }
01576     else
01577         lSeek+=file_info.size_file_extra; 
01578 
01579     
01580     if ((err==UNZ_OK) && (szComment!=NULL))
01581     {
01582         uLong uSizeRead ;
01583         if (file_info.size_file_comment<commentBufferSize)
01584         {
01585             *(szComment+file_info.size_file_comment)='\0';
01586             uSizeRead = file_info.size_file_comment;
01587         }
01588         else
01589             uSizeRead = commentBufferSize;
01590 
01591         if (lSeek!=0) {
01592             if (fseek(s->file,lSeek,SEEK_CUR)==0)
01593                 lSeek=0;
01594             else
01595                 err=UNZ_ERRNO;
01596         }
01597         if ((file_info.size_file_comment>0) && (commentBufferSize>0)) {
01598             if (fread(szComment,(uInt)uSizeRead,1,s->file)!=1)
01599                 err=UNZ_ERRNO;
01600         }
01601         lSeek+=file_info.size_file_comment - uSizeRead;
01602     }
01603     else
01604         lSeek+=file_info.size_file_comment;
01605 
01606     if ((err==UNZ_OK) && (pfile_info!=NULL))
01607         *pfile_info=file_info;
01608 
01609     if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
01610         *pfile_info_internal=file_info_internal;
01611 
01612     return err;
01613 }
01614 
01615 
01616 
01617 /*
01618   Write info about the ZipFile in the *pglobal_info structure.
01619   No preparation of the structure is needed
01620   return UNZ_OK if there is no problem.
01621 */
01622 extern int unzGetCurrentFileInfo (  unzFile file, unz_file_info *pfile_info,
01623                                     char *szFileName, uLong fileNameBufferSize,
01624                                     void *extraField, uLong extraFieldBufferSize,
01625                                     char *szComment, uLong commentBufferSize)
01626 {
01627     return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,
01628                                                 szFileName,fileNameBufferSize,
01629                                                 extraField,extraFieldBufferSize,
01630                                                 szComment,commentBufferSize);
01631 }
01632 
01633 /*
01634   Set the current file of the zipfile to the first file.
01635   return UNZ_OK if there is no problem
01636 */
01637 extern int unzGoToFirstFile (unzFile file)
01638 {
01639     int err=UNZ_OK;
01640     unz_s* s;
01641     if (file==NULL)
01642         return UNZ_PARAMERROR;
01643     s=(unz_s*)file;
01644     s->pos_in_central_dir=s->offset_central_dir;
01645     s->num_file=0;
01646     err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
01647                                              &s->cur_file_info_internal,
01648                                              NULL,0,NULL,0,NULL,0);
01649     s->current_file_ok = (err == UNZ_OK);
01650     return err;
01651 }
01652 
01653 
01654 /*
01655   Set the current file of the zipfile to the next file.
01656   return UNZ_OK if there is no problem
01657   return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
01658 */
01659 extern int unzGoToNextFile (unzFile file)
01660 {
01661     unz_s* s;   
01662     int err;
01663 
01664     if (file==NULL)
01665         return UNZ_PARAMERROR;
01666     s=(unz_s*)file;
01667     if (!s->current_file_ok)
01668         return UNZ_END_OF_LIST_OF_FILE;
01669     if (s->num_file+1==s->gi.number_entry)
01670         return UNZ_END_OF_LIST_OF_FILE;
01671 
01672     s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
01673             s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
01674     s->num_file++;
01675     err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
01676                                                &s->cur_file_info_internal,
01677                                                NULL,0,NULL,0,NULL,0);
01678     s->current_file_ok = (err == UNZ_OK);
01679     return err;
01680 }
01681 
01682 /*
01683   Get the position of the info of the current file in the zip.
01684   return UNZ_OK if there is no problem
01685 */
01686 extern int unzGetCurrentFileInfoPosition (unzFile file, unsigned long *pos )
01687 {
01688     unz_s* s;   
01689 
01690     if (file==NULL)
01691         return UNZ_PARAMERROR;
01692     s=(unz_s*)file;
01693 
01694     *pos = s->pos_in_central_dir;
01695     return UNZ_OK;
01696 }
01697 
01698 /*
01699   Set the position of the info of the current file in the zip.
01700   return UNZ_OK if there is no problem
01701 */
01702 extern int unzSetCurrentFileInfoPosition (unzFile file, unsigned long pos )
01703 {
01704     unz_s* s;   
01705     int err;
01706 
01707     if (file==NULL)
01708         return UNZ_PARAMERROR;
01709     s=(unz_s*)file;
01710 
01711     s->pos_in_central_dir = pos;
01712     err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
01713                                                &s->cur_file_info_internal,
01714                                                NULL,0,NULL,0,NULL,0);
01715     s->current_file_ok = (err == UNZ_OK);
01716     return UNZ_OK;
01717 }
01718 
01719 /*
01720   Try locate the file szFileName in the zipfile.
01721   For the iCaseSensitivity signification, see unzipStringFileNameCompare
01722 
01723   return value :
01724   UNZ_OK if the file is found. It becomes the current file.
01725   UNZ_END_OF_LIST_OF_FILE if the file is not found
01726 */
01727 extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
01728 {
01729     unz_s* s;   
01730     int err;
01731 
01732     
01733     uLong num_fileSaved;
01734     uLong pos_in_central_dirSaved;
01735 
01736 
01737     if (file==NULL)
01738         return UNZ_PARAMERROR;
01739 
01740     if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
01741         return UNZ_PARAMERROR;
01742 
01743     s=(unz_s*)file;
01744     if (!s->current_file_ok)
01745         return UNZ_END_OF_LIST_OF_FILE;
01746 
01747     num_fileSaved = s->num_file;
01748     pos_in_central_dirSaved = s->pos_in_central_dir;
01749 
01750     err = unzGoToFirstFile(file);
01751 
01752     while (err == UNZ_OK)
01753     {
01754         char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
01755         unzGetCurrentFileInfo(file,NULL,
01756                                 szCurrentFileName,sizeof(szCurrentFileName)-1,
01757                                 NULL,0,NULL,0);
01758         if (unzStringFileNameCompare(szCurrentFileName,
01759                                         szFileName,iCaseSensitivity)==0)
01760             return UNZ_OK;
01761         err = unzGoToNextFile(file);
01762     }
01763 
01764     s->num_file = num_fileSaved ;
01765     s->pos_in_central_dir = pos_in_central_dirSaved ;
01766     return err;
01767 }
01768 
01769 
01770 /*
01771   Read the static header of the current zipfile
01772   Check the coherency of the static header and info in the end of central
01773         directory about this file
01774   store in *piSizeVar the size of extra info in static header
01775         (filename and size of extra field data)
01776 */
01777 static int unzlocal_CheckCurrentFileCoherencyHeader (unz_s* s, uInt* piSizeVar,
01778                                                     uLong *poffset_local_extrafield,
01779                                                     uInt *psize_local_extrafield)
01780 {
01781     uLong uMagic,uData,uFlags;
01782     uLong size_filename;
01783     uLong size_extra_field;
01784     int err=UNZ_OK;
01785 
01786     *piSizeVar = 0;
01787     *poffset_local_extrafield = 0;
01788     *psize_local_extrafield = 0;
01789 
01790     if (fseek(s->file,s->cur_file_info_internal.offset_curfile +
01791                                 s->byte_before_the_zipfile,SEEK_SET)!=0)
01792         return UNZ_ERRNO;
01793 
01794 
01795     if (err==UNZ_OK) {
01796         if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
01797             err=UNZ_ERRNO;
01798         else if (uMagic!=0x04034b50)
01799             err=UNZ_BADZIPFILE;
01800     }
01801     if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
01802         err=UNZ_ERRNO;
01803 /*
01804     else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
01805         err=UNZ_BADZIPFILE;
01806 */
01807     if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK)
01808         err=UNZ_ERRNO;
01809 
01810     if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
01811         err=UNZ_ERRNO;
01812     else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
01813         err=UNZ_BADZIPFILE;
01814 
01815     if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
01816                          (s->cur_file_info.compression_method!=Z_DEFLATED))
01817         err=UNZ_BADZIPFILE;
01818 
01819     if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* date/time */
01820         err=UNZ_ERRNO;
01821 
01822     if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* crc */
01823         err=UNZ_ERRNO;
01824     else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) &&
01825                               ((uFlags & 8)==0))
01826         err=UNZ_BADZIPFILE;
01827 
01828     if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size compr */
01829         err=UNZ_ERRNO;
01830     else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) &&
01831                               ((uFlags & 8)==0))
01832         err=UNZ_BADZIPFILE;
01833 
01834     if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size uncompr */
01835         err=UNZ_ERRNO;
01836     else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && 
01837                               ((uFlags & 8)==0))
01838         err=UNZ_BADZIPFILE;
01839 
01840 
01841     if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK)
01842         err=UNZ_ERRNO;
01843     else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
01844         err=UNZ_BADZIPFILE;
01845 
01846     *piSizeVar += (uInt)size_filename;
01847 
01848     if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK)
01849         err=UNZ_ERRNO;
01850     *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
01851                                     SIZEZIPLOCALHEADER + size_filename;
01852     *psize_local_extrafield = (uInt)size_extra_field;
01853 
01854     *piSizeVar += (uInt)size_extra_field;
01855 
01856     return err;
01857 }
01858                                                 
01859 /*
01860   Open for reading data the current file in the zipfile.
01861   If there is no error and the file is opened, the return value is UNZ_OK.
01862 */
01863 extern int unzOpenCurrentFile (unzFile file)
01864 {
01865     int err=UNZ_OK;
01866     int Store;
01867     uInt iSizeVar;
01868     unz_s* s;
01869     file_in_zip_read_info_s* pfile_in_zip_read_info;
01870     uLong offset_local_extrafield;  /* offset of the static extra field */
01871     uInt  size_local_extrafield;    /* size of the static extra field */
01872 
01873     if (file==NULL)
01874         return UNZ_PARAMERROR;
01875     s=(unz_s*)file;
01876     if (!s->current_file_ok)
01877         return UNZ_PARAMERROR;
01878 
01879     if (s->pfile_in_zip_read != NULL)
01880         unzCloseCurrentFile(file);
01881 
01882     if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar,
01883                 &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
01884         return UNZ_BADZIPFILE;
01885 
01886     pfile_in_zip_read_info = (file_in_zip_read_info_s*)
01887                                         ALLOC(sizeof(file_in_zip_read_info_s));
01888     if (pfile_in_zip_read_info==NULL)
01889         return UNZ_INTERNALERROR;
01890 
01891     pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
01892     pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
01893     pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
01894     pfile_in_zip_read_info->pos_local_extrafield=0;
01895 
01896     if (pfile_in_zip_read_info->read_buffer==NULL)
01897     {
01898         TRYFREE(pfile_in_zip_read_info);
01899         return UNZ_INTERNALERROR;
01900     }
01901 
01902     pfile_in_zip_read_info->stream_initialised=0;
01903     
01904     if ((s->cur_file_info.compression_method!=0) &&
01905         (s->cur_file_info.compression_method!=Z_DEFLATED))
01906         err=UNZ_BADZIPFILE;
01907     Store = s->cur_file_info.compression_method==0;
01908 
01909     pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
01910     pfile_in_zip_read_info->crc32=0;
01911     pfile_in_zip_read_info->compression_method =
01912             s->cur_file_info.compression_method;
01913     pfile_in_zip_read_info->file=s->file;
01914     pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
01915 
01916     pfile_in_zip_read_info->stream.total_out = 0;
01917 
01918     if (!Store)
01919     {
01920       pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
01921       pfile_in_zip_read_info->stream.zfree = (free_func)0;
01922       pfile_in_zip_read_info->stream.opaque = (voidp)0; 
01923       
01924       err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
01925       if (err == Z_OK)
01926         pfile_in_zip_read_info->stream_initialised=1;
01927         /* windowBits is passed < 0 to tell that there is no zlib header.
01928          * Note that in this case inflate *requires* an extra "dummy" byte
01929          * after the compressed stream in order to complete decompression and
01930          * return Z_STREAM_END. 
01931          * In unzip, i don't wait absolutely Z_STREAM_END because I known the 
01932          * size of both compressed and uncompressed data
01933          */
01934     }
01935     pfile_in_zip_read_info->rest_read_compressed = 
01936             s->cur_file_info.compressed_size ;
01937     pfile_in_zip_read_info->rest_read_uncompressed = 
01938             s->cur_file_info.uncompressed_size ;
01939 
01940     
01941     pfile_in_zip_read_info->pos_in_zipfile = 
01942             s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + 
01943               iSizeVar;
01944     
01945     pfile_in_zip_read_info->stream.avail_in = (uInt)0;
01946 
01947 
01948     s->pfile_in_zip_read = pfile_in_zip_read_info;
01949     return UNZ_OK;
01950 }
01951 
01952 
01953 /*
01954   Read bytes from the current file.
01955   buf contain buffer where data must be copied
01956   len the size of buf.
01957 
01958   return the number of byte copied if somes bytes are copied
01959   return 0 if the end of file was reached
01960   return <0 with error code if there is an error
01961     (UNZ_ERRNO for IO error, or zLib error for uncompress error)
01962 */
01963 extern int unzReadCurrentFile  (unzFile file, void *buf, unsigned len)
01964 {
01965     int err=UNZ_OK;
01966     uInt iRead = 0;
01967     unz_s* s;
01968     file_in_zip_read_info_s* pfile_in_zip_read_info;
01969     if (file==NULL)
01970         return UNZ_PARAMERROR;
01971     s=(unz_s*)file;
01972     pfile_in_zip_read_info=s->pfile_in_zip_read;
01973 
01974     if (pfile_in_zip_read_info==NULL)
01975         return UNZ_PARAMERROR;
01976 
01977 
01978     if ((pfile_in_zip_read_info->read_buffer == NULL))
01979         return UNZ_END_OF_LIST_OF_FILE;
01980     if (len==0)
01981         return 0;
01982 
01983     pfile_in_zip_read_info->stream.next_out = (Byte*)buf;
01984 
01985     pfile_in_zip_read_info->stream.avail_out = (uInt)len;
01986     
01987     if (len>pfile_in_zip_read_info->rest_read_uncompressed)
01988         pfile_in_zip_read_info->stream.avail_out = 
01989           (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
01990 
01991     while (pfile_in_zip_read_info->stream.avail_out>0)
01992     {
01993         if ((pfile_in_zip_read_info->stream.avail_in==0) &&
01994             (pfile_in_zip_read_info->rest_read_compressed>0))
01995         {
01996             uInt uReadThis = UNZ_BUFSIZE;
01997             if (pfile_in_zip_read_info->rest_read_compressed<uReadThis)
01998                 uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
01999             if (uReadThis == 0)
02000                 return UNZ_EOF;
02001             if (s->cur_file_info.compressed_size == pfile_in_zip_read_info->rest_read_compressed)
02002                 if (fseek(pfile_in_zip_read_info->file,
02003                           pfile_in_zip_read_info->pos_in_zipfile + 
02004                              pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0)
02005                     return UNZ_ERRNO;
02006             if (fread(pfile_in_zip_read_info->read_buffer,uReadThis,1,
02007                          pfile_in_zip_read_info->file)!=1)
02008                 return UNZ_ERRNO;
02009             pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
02010 
02011             pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
02012             
02013             pfile_in_zip_read_info->stream.next_in = 
02014                 (Byte*)pfile_in_zip_read_info->read_buffer;
02015             pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
02016         }
02017 
02018         if (pfile_in_zip_read_info->compression_method==0)
02019         {
02020             uInt uDoCopy,i ;
02021             if (pfile_in_zip_read_info->stream.avail_out < 
02022                             pfile_in_zip_read_info->stream.avail_in)
02023                 uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
02024             else
02025                 uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
02026                 
02027             for (i=0;i<uDoCopy;i++)
02028                 *(pfile_in_zip_read_info->stream.next_out+i) =
02029                         *(pfile_in_zip_read_info->stream.next_in+i);
02030                     
02031 //          pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,
02032 //                              pfile_in_zip_read_info->stream.next_out,
02033 //                              uDoCopy);
02034             pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
02035             pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
02036             pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
02037             pfile_in_zip_read_info->stream.next_out += uDoCopy;
02038             pfile_in_zip_read_info->stream.next_in += uDoCopy;
02039             pfile_in_zip_read_info->stream.total_out += uDoCopy;
02040             iRead += uDoCopy;
02041         }
02042         else
02043         {
02044             uLong uTotalOutBefore,uTotalOutAfter;
02045             const Byte *bufBefore;
02046             uLong uOutThis;
02047             int flush=Z_SYNC_FLUSH;
02048 
02049             uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
02050             bufBefore = pfile_in_zip_read_info->stream.next_out;
02051 
02052             /*
02053             if ((pfile_in_zip_read_info->rest_read_uncompressed ==
02054                      pfile_in_zip_read_info->stream.avail_out) &&
02055                 (pfile_in_zip_read_info->rest_read_compressed == 0))
02056                 flush = Z_FINISH;
02057             */
02058             err=inflate(&pfile_in_zip_read_info->stream,flush);
02059 
02060             uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
02061             uOutThis = uTotalOutAfter-uTotalOutBefore;
02062             
02063 //          pfile_in_zip_read_info->crc32 = 
02064 //                crc32(pfile_in_zip_read_info->crc32,bufBefore,
02065 //                        (uInt)(uOutThis));
02066 
02067             pfile_in_zip_read_info->rest_read_uncompressed -=
02068                 uOutThis;
02069 
02070             iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
02071             
02072             if (err==Z_STREAM_END)
02073                 return (iRead==0) ? UNZ_EOF : iRead;
02074             if (err!=Z_OK) 
02075                 break;
02076         }
02077     }
02078 
02079     if (err==Z_OK)
02080         return iRead;
02081     return err;
02082 }
02083 
02084 
02085 /*
02086   Give the current position in uncompressed data
02087 */
02088 extern long unztell (unzFile file)
02089 {
02090     unz_s* s;
02091     file_in_zip_read_info_s* pfile_in_zip_read_info;
02092     if (file==NULL)
02093         return UNZ_PARAMERROR;
02094     s=(unz_s*)file;
02095     pfile_in_zip_read_info=s->pfile_in_zip_read;
02096 
02097     if (pfile_in_zip_read_info==NULL)
02098         return UNZ_PARAMERROR;
02099 
02100     return (long)pfile_in_zip_read_info->stream.total_out;
02101 }
02102 
02103 
02104 /*
02105   return 1 if the end of file was reached, 0 elsewhere 
02106 */
02107 extern int unzeof (unzFile file)
02108 {
02109     unz_s* s;
02110     file_in_zip_read_info_s* pfile_in_zip_read_info;
02111     if (file==NULL)
02112         return UNZ_PARAMERROR;
02113     s=(unz_s*)file;
02114     pfile_in_zip_read_info=s->pfile_in_zip_read;
02115 
02116     if (pfile_in_zip_read_info==NULL)
02117         return UNZ_PARAMERROR;
02118     
02119     if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
02120         return 1;
02121     else
02122         return 0;
02123 }
02124 
02125 
02126 
02127 /*
02128   Read extra field from the current file (opened by unzOpenCurrentFile)
02129   This is the static-header version of the extra field (sometimes, there is
02130     more info in the static-header version than in the central-header)
02131 
02132   if buf==NULL, it return the size of the static extra field that can be read
02133 
02134   if buf!=NULL, len is the size of the buffer, the extra header is copied in
02135     buf.
02136   the return value is the number of bytes copied in buf, or (if <0) 
02137     the error code
02138 */
02139 extern int unzGetLocalExtrafield (unzFile file,void *buf,unsigned len)
02140 {
02141     unz_s* s;
02142     file_in_zip_read_info_s* pfile_in_zip_read_info;
02143     uInt read_now;
02144     uLong size_to_read;
02145 
02146     if (file==NULL)
02147         return UNZ_PARAMERROR;
02148     s=(unz_s*)file;
02149     pfile_in_zip_read_info=s->pfile_in_zip_read;
02150 
02151     if (pfile_in_zip_read_info==NULL)
02152         return UNZ_PARAMERROR;
02153 
02154     size_to_read = (pfile_in_zip_read_info->size_local_extrafield - 
02155                 pfile_in_zip_read_info->pos_local_extrafield);
02156 
02157     if (buf==NULL)
02158         return (int)size_to_read;
02159     
02160     if (len>size_to_read)
02161         read_now = (uInt)size_to_read;
02162     else
02163         read_now = (uInt)len ;
02164 
02165     if (read_now==0)
02166         return 0;
02167     
02168     if (fseek(pfile_in_zip_read_info->file,
02169               pfile_in_zip_read_info->offset_local_extrafield + 
02170               pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0)
02171         return UNZ_ERRNO;
02172 
02173     if (fread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1)
02174         return UNZ_ERRNO;
02175 
02176     return (int)read_now;
02177 }
02178 
02179 /*
02180   Close the file in zip opened with unzipOpenCurrentFile
02181   Return UNZ_CRCERROR if all the file was read but the CRC is not good
02182 */
02183 extern int unzCloseCurrentFile (unzFile file)
02184 {
02185     int err=UNZ_OK;
02186 
02187     unz_s* s;
02188     file_in_zip_read_info_s* pfile_in_zip_read_info;
02189     if (file==NULL)
02190         return UNZ_PARAMERROR;
02191     s=(unz_s*)file;
02192     pfile_in_zip_read_info=s->pfile_in_zip_read;
02193 
02194     if (pfile_in_zip_read_info==NULL)
02195         return UNZ_PARAMERROR;
02196 
02197 /*
02198     if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
02199     {
02200         if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
02201             err=UNZ_CRCERROR;
02202     }
02203 */
02204 
02205     TRYFREE(pfile_in_zip_read_info->read_buffer);
02206     pfile_in_zip_read_info->read_buffer = NULL;
02207     if (pfile_in_zip_read_info->stream_initialised)
02208         inflateEnd(&pfile_in_zip_read_info->stream);
02209 
02210     pfile_in_zip_read_info->stream_initialised = 0;
02211     TRYFREE(pfile_in_zip_read_info);
02212 
02213     s->pfile_in_zip_read=NULL;
02214 
02215     return err;
02216 }
02217 
02218 
02219 /*
02220   Get the global comment string of the ZipFile, in the szComment buffer.
02221   uSizeBuf is the size of the szComment buffer.
02222   return the number of byte copied or an error code <0
02223 */
02224 extern int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf)
02225 {
02226     unz_s* s;
02227     uLong uReadThis ;
02228     if (file==NULL)
02229         return UNZ_PARAMERROR;
02230     s=(unz_s*)file;
02231 
02232     uReadThis = uSizeBuf;
02233     if (uReadThis>s->gi.size_comment)
02234         uReadThis = s->gi.size_comment;
02235 
02236     if (fseek(s->file,s->central_pos+22,SEEK_SET)!=0)
02237         return UNZ_ERRNO;
02238 
02239     if (uReadThis>0)
02240     {
02241       *szComment='\0';
02242       if (fread(szComment,(uInt)uReadThis,1,s->file)!=1)
02243         return UNZ_ERRNO;
02244     }
02245 
02246     if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment))
02247         *(szComment+s->gi.size_comment)='\0';
02248     return (int)uReadThis;
02249 }
02250 
02251 /* infblock.h -- header to use infblock.c
02252  * Copyright (C) 1995-1998 Mark Adler
02253  * For conditions of distribution and use, see copyright notice in zlib.h 
02254  */
02255 
02256 /* WARNING: this file should *not* be used by applications. It is
02257    part of the implementation of the compression library and is
02258    subject to change. Applications should only use zlib.h.
02259  */
02260 
02261 struct inflate_blocks_state;
02262 typedef struct inflate_blocks_state inflate_blocks_statef;
02263 
02264 static inflate_blocks_statef * inflate_blocks_new OF((
02265     z_streamp z,
02266     check_func c,               /* check function */
02267     uInt w));                   /* window size */
02268 
02269 static int inflate_blocks OF((
02270     inflate_blocks_statef *,
02271     z_streamp ,
02272     int));                      /* initial return code */
02273 
02274 static void inflate_blocks_reset OF((
02275     inflate_blocks_statef *,
02276     z_streamp ,
02277     uLong *));                  /* check value on output */
02278 
02279 static int inflate_blocks_free OF((
02280     inflate_blocks_statef *,
02281     z_streamp));
02282 
02283 #if 0
02284 static void inflate_set_dictionary OF((
02285     inflate_blocks_statef *s,
02286     const Byte *d,  /* dictionary */
02287     uInt  n));       /* dictionary length */
02288 
02289 static int inflate_blocks_sync_point OF((
02290     inflate_blocks_statef *s));
02291 #endif
02292 
02293 /* simplify the use of the inflate_huft type with some defines */
02294 #define exop word.what.Exop
02295 #define bits word.what.Bits
02296 
02297 /* Table for deflate from PKZIP's appnote.txt. */
02298 static const uInt border[] = { /* Order of the bit length code lengths */
02299         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
02300 
02301 /* inftrees.h -- header to use inftrees.c
02302  * Copyright (C) 1995-1998 Mark Adler
02303  * For conditions of distribution and use, see copyright notice in zlib.h 
02304  */
02305 
02306 /* WARNING: this file should *not* be used by applications. It is
02307    part of the implementation of the compression library and is
02308    subject to change. Applications should only use zlib.h.
02309  */
02310 
02311 /* Huffman code lookup table entry--this entry is four bytes for machines
02312    that have 16-bit pointers (e.g. PC's in the small or medium model). */
02313 
02314 typedef struct inflate_huft_s inflate_huft;
02315 
02316 struct inflate_huft_s {
02317   union {
02318     struct {
02319       Byte Exop;        /* number of extra bits or operation */
02320       Byte Bits;        /* number of bits in this code or subcode */
02321     } what;
02322     uInt pad;           /* pad structure to a power of 2 (4 bytes for */
02323   } word;               /*  16-bit, 8 bytes for 32-bit int's) */
02324   uInt base;            /* literal, length base, distance base,
02325                            or table offset */
02326 };
02327 
02328 /* Maximum size of dynamic tree.  The maximum found in a long but non-
02329    exhaustive search was 1004 huft structures (850 for length/literals
02330    and 154 for distances, the latter actually the result of an
02331    exhaustive search).  The actual maximum is not known, but the
02332    value below is more than safe. */
02333 #define MANY 1440
02334 
02335 static  int inflate_trees_bits OF((
02336     uInt *,                    /* 19 code lengths */
02337     uInt *,                    /* bits tree desired/actual depth */
02338     inflate_huft * *,       /* bits tree result */
02339     inflate_huft *,             /* space for trees */
02340     z_streamp));                /* for messages */
02341 
02342 static  int inflate_trees_dynamic OF((
02343     uInt,                       /* number of literal/length codes */
02344     uInt,                       /* number of distance codes */
02345     uInt *,                    /* that many (total) code lengths */
02346     uInt *,                    /* literal desired/actual bit depth */
02347     uInt *,                    /* distance desired/actual bit depth */
02348     inflate_huft * *,       /* literal/length tree result */
02349     inflate_huft * *,       /* distance tree result */
02350     inflate_huft *,             /* space for trees */
02351     z_streamp));                /* for messages */
02352 
02353 static  int inflate_trees_fixed OF((
02354     uInt *,                    /* literal desired/actual bit depth */
02355     uInt *,                    /* distance desired/actual bit depth */
02356     inflate_huft * *,       /* literal/length tree result */
02357     inflate_huft * *,       /* distance tree result */
02358     z_streamp));                /* for memory allocation */
02359 
02360 
02361 /* infcodes.h -- header to use infcodes.c
02362  * Copyright (C) 1995-1998 Mark Adler
02363  * For conditions of distribution and use, see copyright notice in zlib.h 
02364  */
02365 
02366 /* WARNING: this file should *not* be used by applications. It is
02367    part of the implementation of the compression library and is
02368    subject to change. Applications should only use zlib.h.
02369  */
02370 
02371 struct inflate_codes_state;
02372 typedef struct inflate_codes_state inflate_codes_statef;
02373 
02374 static inflate_codes_statef *inflate_codes_new OF((
02375     uInt, uInt,
02376     inflate_huft *, inflate_huft *,
02377     z_streamp ));
02378 
02379 static  int inflate_codes OF((
02380     inflate_blocks_statef *,
02381     z_streamp ,
02382     int));
02383 
02384 static  void inflate_codes_free OF((
02385     inflate_codes_statef *,
02386     z_streamp ));
02387 
02388 /* infutil.h -- types and macros common to blocks and codes
02389  * Copyright (C) 1995-1998 Mark Adler
02390  * For conditions of distribution and use, see copyright notice in zlib.h 
02391  */
02392 
02393 /* WARNING: this file should *not* be used by applications. It is
02394    part of the implementation of the compression library and is
02395    subject to change. Applications should only use zlib.h.
02396  */
02397 
02398 #ifndef _INFUTIL_H
02399 #define _INFUTIL_H
02400 
02401 typedef enum {
02402       TYPE,     /* get type bits (3, including end bit) */
02403       LENS,     /* get lengths for stored */
02404       STORED,   /* processing stored block */
02405       TABLE,    /* get table lengths */
02406       BTREE,    /* get bit lengths tree for a dynamic block */
02407       DTREE,    /* get length, distance trees for a dynamic block */
02408       CODES,    /* processing fixed or dynamic block */
02409       DRY,      /* output remaining window bytes */
02410       DONE,     /* finished last block, done */
02411       BAD}      /* got a data error--stuck here */
02412 inflate_block_mode;
02413 
02414 /* inflate blocks semi-private state */
02415 struct inflate_blocks_state {
02416 
02417   /* mode */
02418   inflate_block_mode  mode;     /* current inflate_block mode */
02419 
02420   /* mode dependent information */
02421   union {
02422     uInt left;          /* if STORED, bytes left to copy */
02423     struct {
02424       uInt table;               /* table lengths (14 bits) */
02425       uInt index;               /* index into blens (or border) */
02426       uInt *blens;             /* bit lengths of codes */
02427       uInt bb;                  /* bit length tree depth */
02428       inflate_huft *tb;         /* bit length decoding tree */
02429     } trees;            /* if DTREE, decoding info for trees */
02430     struct {
02431       inflate_codes_statef 
02432          *codes;
02433     } decode;           /* if CODES, current state */
02434   } sub;                /* submode */
02435   uInt last;            /* true if this block is the last block */
02436 
02437   /* mode independent information */
02438   uInt bitk;            /* bits in bit buffer */
02439   uLong bitb;           /* bit buffer */
02440   inflate_huft *hufts;  /* single malloc for tree space */
02441   Byte *window;        /* sliding window */
02442   Byte *end;           /* one byte after sliding window */
02443   Byte *read;          /* window read pointer */
02444   Byte *write;         /* window write pointer */
02445   check_func checkfn;   /* check function */
02446   uLong check;          /* check on output */
02447 
02448 };
02449 
02450 
02451 /* defines for inflate input/output */
02452 /*   update pointers and return */
02453 #define UPDBITS {s->bitb=b;s->bitk=k;}
02454 #define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
02455 #define UPDOUT {s->write=q;}
02456 #define UPDATE {UPDBITS UPDIN UPDOUT}
02457 #define LEAVE {UPDATE return inflate_flush(s,z,r);}
02458 /*   get bytes and bits */
02459 #define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
02460 #define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
02461 #define NEXTBYTE (n--,*p++)
02462 #define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
02463 #define DUMPBITS(j) {b>>=(j);k-=(j);}
02464 /*   output bytes */
02465 #define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
02466 #define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
02467 #define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
02468 #define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
02469 #define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
02470 #define OUTBYTE(a) {*q++=(Byte)(a);m--;}
02471 /*   load static pointers */
02472 #define LOAD {LOADIN LOADOUT}
02473 
02474 /* masks for lower bits (size given to avoid silly warnings with Visual C++) */
02475 static  uInt inflate_mask[17];
02476 
02477 /* copy as much as possible from the sliding window to the output area */
02478 static  int inflate_flush OF((
02479     inflate_blocks_statef *,
02480     z_streamp ,
02481     int));
02482 
02483 #endif
02484 
02485                                 
02486 /*
02487    Notes beyond the 1.93a appnote.txt:
02488 
02489    1. Distance pointers never point before the beginning of the output
02490       stream.
02491    2. Distance pointers can point back across blocks, up to 32k away.
02492    3. There is an implied maximum of 7 bits for the bit length table and
02493       15 bits for the actual data.
02494    4. If only one code exists, then it is encoded using one bit.  (Zero
02495       would be more efficient, but perhaps a little confusing.)  If two
02496       codes exist, they are coded using one bit each (0 and 1).
02497    5. There is no way of sending zero distance codes--a dummy must be
02498       sent if there are none.  (History: a pre 2.0 version of PKZIP would
02499       store blocks with no distance codes, but this was discovered to be
02500       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
02501       zero distance codes, which is sent as one code of zero bits in
02502       length.
02503    6. There are up to 286 literal/length codes.  Code 256 represents the
02504       end-of-block.  Note however that the static length tree defines
02505       288 codes just to fill out the Huffman codes.  Codes 286 and 287
02506       cannot be used though, since there is no length base or extra bits
02507       defined for them.  Similarily, there are up to 30 distance codes.
02508       However, static trees define 32 codes (all 5 bits) to fill out the
02509       Huffman codes, but the last two had better not show up in the data.
02510    7. Unzip can check dynamic Huffman blocks for complete code sets.
02511       The exception is that a single code would not be complete (see #4).
02512    8. The five bits following the block type is really the number of
02513       literal codes sent minus 257.
02514    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
02515       (1+6+6).  Therefore, to output three times the length, you output
02516       three codes (1+1+1), whereas to output four times the same length,
02517       you only need two codes (1+3).  Hmm.
02518   10. In the tree reconstruction algorithm, Code = Code + Increment
02519       only if BitLength(i) is not zero.  (Pretty obvious.)
02520   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
02521   12. Note: length code 284 can represent 227-258, but length code 285
02522       really is 258.  The last length deserves its own, short code
02523       since it gets used a lot in very redundant files.  The length
02524       258 is special since 258 - 3 (the min match length) is 255.
02525   13. The literal/length and distance code bit lengths are read as a
02526       single stream of lengths.  It is possible (and advantageous) for
02527       a repeat code (16, 17, or 18) to go across the boundary between
02528       the two sets of lengths.
02529  */
02530 
02531 
02532 void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c)
02533 {
02534   if (c != Z_NULL)
02535     *c = s->check;
02536   if (s->mode == BTREE || s->mode == DTREE)
02537     ZFREE(z, s->sub.trees.blens);
02538   if (s->mode == CODES)
02539     inflate_codes_free(s->sub.decode.codes, z);
02540   s->mode = TYPE;
02541   s->bitk = 0;
02542   s->bitb = 0;
02543   s->read = s->write = s->window;
02544   if (s->checkfn != Z_NULL)
02545     z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0);
02546   Tracev(("inflate:   blocks reset\n"));
02547 }
02548 
02549 
02550 inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w)
02551 {
02552   inflate_blocks_statef *s;
02553 
02554   if ((s = (inflate_blocks_statef *)ZALLOC
02555        (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
02556     return s;
02557   if ((s->hufts =
02558        (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
02559   {
02560     ZFREE(z, s);
02561     return Z_NULL;
02562   }
02563   if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL)
02564   {
02565     ZFREE(z, s->hufts);
02566     ZFREE(z, s);
02567     return Z_NULL;
02568   }
02569   s->end = s->window + w;
02570   s->checkfn = c;
02571   s->mode = TYPE;
02572   Tracev(("inflate:   blocks allocated\n"));
02573   inflate_blocks_reset(s, z, Z_NULL);
02574   return s;
02575 }
02576 
02577 
02578 int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r)
02579 {
02580   uInt t;               /* temporary storage */
02581   uLong b;              /* bit buffer */
02582   uInt k;               /* bits in bit buffer */
02583   Byte *p;             /* input data pointer */
02584   uInt n;               /* bytes available there */
02585   Byte *q;             /* output window write pointer */
02586   uInt m;               /* bytes to end of window or read pointer */
02587 
02588   /* copy input/output information to locals (UPDATE macro restores) */
02589   LOAD
02590 
02591   /* process input based on current state */
02592   while (1) switch (s->mode)
02593   {
02594     case TYPE:
02595       NEEDBITS(3)
02596       t = (uInt)b & 7;
02597       s->last = t & 1;
02598       switch (t >> 1)
02599       {
02600         case 0:                         /* stored */
02601           Tracev(("inflate:     stored block%s\n",
02602                  s->last ? " (last)" : ""));
02603           DUMPBITS(3)
02604           t = k & 7;                    /* go to byte boundary */
02605           DUMPBITS(t)
02606           s->mode = LENS;               /* get length of stored block */
02607           break;
02608         case 1:                         /* fixed */
02609           Tracev(("inflate:     fixed codes block%s\n",
02610                  s->last ? " (last)" : ""));
02611           {
02612             uInt bl, bd;
02613             inflate_huft *tl, *td;
02614             inflate_trees_fixed(&bl, &bd, &tl, &td, z);
02615             s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
02616             if (s->sub.decode.codes == Z_NULL)
02617             {
02618               r = Z_MEM_ERROR;
02619               LEAVE
02620             }
02621           }
02622           DUMPBITS(3)
02623           s->mode = CODES;
02624           break;
02625         case 2:                         /* dynamic */
02626           Tracev(("inflate:     dynamic codes block%s\n",
02627                  s->last ? " (last)" : ""));
02628           DUMPBITS(3)
02629           s->mode = TABLE;
02630           break;
02631         case 3:                         /* illegal */
02632           DUMPBITS(3)
02633           s->mode = BAD;
02634           z->msg = (char*)"invalid block type";
02635           r = Z_DATA_ERROR;
02636           LEAVE
02637       }
02638       break;
02639     case LENS:
02640       NEEDBITS(32)
02641       if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
02642       {
02643         s->mode = BAD;
02644         z->msg = (char*)"invalid stored block lengths";
02645         r = Z_DATA_ERROR;
02646         LEAVE
02647       }
02648       s->sub.left = (uInt)b & 0xffff;
02649       b = k = 0;                      /* dump bits */
02650       Tracev(("inflate:       stored length %u\n", s->sub.left));
02651       s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
02652       break;
02653     case STORED:
02654       if (n == 0)
02655         LEAVE
02656       NEEDOUT
02657       t = s->sub.left;
02658       if (t > n) t = n;
02659       if (t > m) t = m;
02660       zmemcpy(q, p, t);
02661       p += t;  n -= t;
02662       q += t;  m -= t;
02663       if ((s->sub.left -= t) != 0)
02664         break;
02665       Tracev(("inflate:       stored end, %lu total out\n",
02666               z->total_out + (q >= s->read ? q - s->read :
02667               (s->end - s->read) + (q - s->window))));
02668       s->mode = s->last ? DRY : TYPE;
02669       break;
02670     case TABLE:
02671       NEEDBITS(14)
02672       s->sub.trees.table = t = (uInt)b & 0x3fff;
02673 #ifndef PKZIP_BUG_WORKAROUND
02674       if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
02675       {
02676         s->mode = BAD;
02677         z->msg = (char*)"too many length or distance symbols";
02678         r = Z_DATA_ERROR;
02679         LEAVE
02680       }
02681 #endif
02682       t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
02683       if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
02684       {
02685         r = Z_MEM_ERROR;
02686         LEAVE
02687       }
02688       DUMPBITS(14)
02689       s->sub.trees.index = 0;
02690       Tracev(("inflate:       table sizes ok\n"));
02691       s->mode = BTREE;
02692     case BTREE:
02693       while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
02694       {
02695         NEEDBITS(3)
02696         s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
02697         DUMPBITS(3)
02698       }
02699       while (s->sub.trees.index < 19)
02700         s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
02701       s->sub.trees.bb = 7;
02702       t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
02703                              &s->sub.trees.tb, s->hufts, z);
02704       if (t != Z_OK)
02705       {
02706         ZFREE(z, s->sub.trees.blens);
02707         r = t;
02708         if (r == Z_DATA_ERROR)
02709           s->mode = BAD;
02710         LEAVE
02711       }
02712       s->sub.trees.index = 0;
02713       Tracev(("inflate:       bits tree ok\n"));
02714       s->mode = DTREE;
02715     case DTREE:
02716       while (t = s->sub.trees.table,
02717              s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
02718       {
02719         inflate_huft *h;
02720         uInt i, j, c;
02721 
02722         t = s->sub.trees.bb;
02723         NEEDBITS(t)
02724         h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
02725         t = h->bits;
02726         c = h->base;
02727         if (c < 16)
02728         {
02729           DUMPBITS(t)
02730           s->sub.trees.blens[s->sub.trees.index++] = c;
02731         }
02732         else /* c == 16..18 */
02733         {
02734           i = c == 18 ? 7 : c - 14;
02735           j = c == 18 ? 11 : 3;
02736           NEEDBITS(t + i)
02737           DUMPBITS(t)
02738           j += (uInt)b & inflate_mask[i];
02739           DUMPBITS(i)
02740           i = s->sub.trees.index;
02741           t = s->sub.trees.table;
02742           if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
02743               (c == 16 && i < 1))
02744           {
02745             ZFREE(z, s->sub.trees.blens);
02746             s->mode = BAD;
02747             z->msg = (char*)"invalid bit length repeat";
02748             r = Z_DATA_ERROR;
02749             LEAVE
02750           }
02751           c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
02752           do {
02753             s->sub.trees.blens[i++] = c;
02754           } while (--j);
02755           s->sub.trees.index = i;
02756         }
02757       }
02758       s->sub.trees.tb = Z_NULL;
02759       {
02760         uInt bl, bd;
02761         inflate_huft *tl, *td;
02762         inflate_codes_statef *c;
02763 
02764         tl = NULL;
02765         td = NULL;
02766         bl = 9;         /* must be <= 9 for lookahead assumptions */
02767         bd = 6;         /* must be <= 9 for lookahead assumptions */
02768         t = s->sub.trees.table;
02769         t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
02770                                   s->sub.trees.blens, &bl, &bd, &tl, &td,
02771                                   s->hufts, z);
02772         ZFREE(z, s->sub.trees.blens);
02773         if (t != Z_OK)
02774         {
02775           if (t == (uInt)Z_DATA_ERROR)
02776             s->mode = BAD;
02777           r = t;
02778           LEAVE
02779         }
02780         Tracev(("inflate:       trees ok\n"));
02781         if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
02782         {
02783           r = Z_MEM_ERROR;
02784           LEAVE
02785         }
02786         s->sub.decode.codes = c;
02787       }
02788       s->mode = CODES;
02789     case CODES:
02790       UPDATE
02791       if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
02792         return inflate_flush(s, z, r);
02793       r = Z_OK;
02794       inflate_codes_free(s->sub.decode.codes, z);
02795       LOAD
02796       Tracev(("inflate:       codes end, %lu total out\n",
02797               z->total_out + (q >= s->read ? q - s->read :
02798               (s->end - s->read) + (q - s->window))));
02799       if (!s->last)
02800       {
02801         s->mode = TYPE;
02802         break;
02803       }
02804       s->mode = DRY;
02805     case DRY:
02806       FLUSH
02807       if (s->read != s->write)
02808         LEAVE
02809       s->mode = DONE;
02810     case DONE:
02811       r = Z_STREAM_END;
02812       LEAVE
02813     case BAD:
02814       r = Z_DATA_ERROR;
02815       LEAVE
02816     default:
02817       r = Z_STREAM_ERROR;
02818       LEAVE
02819   }
02820 }
02821 
02822 
02823 int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z)
02824 {
02825   inflate_blocks_reset(s, z, Z_NULL);
02826   ZFREE(z, s->window);
02827   ZFREE(z, s->hufts);
02828   ZFREE(z, s);
02829   Tracev(("inflate:   blocks freed\n"));
02830   return Z_OK;
02831 }
02832 
02833 #if 0
02834 void inflate_set_dictionary(inflate_blocks_statef *s, const Byte *d, uInt n)
02835 {
02836   zmemcpy(s->window, d, n);
02837   s->read = s->write = s->window + n;
02838 }
02839 
02840 /* Returns true if inflate is currently at the end of a block generated
02841  * by Z_SYNC_FLUSH or Z_FULL_FLUSH. 
02842  * IN assertion: s != Z_NULL
02843  */
02844 int inflate_blocks_sync_point(inflate_blocks_statef *s)
02845 {
02846   return s->mode == LENS;
02847 }
02848 #endif
02849 
02850 
02851 /* And'ing with mask[n] masks the lower n bits */
02852 static uInt inflate_mask[17] = {
02853     0x0000,
02854     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
02855     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
02856 };
02857 
02858 
02859 /* copy as much as possible from the sliding window to the output area */
02860 int inflate_flush(inflate_blocks_statef *s, z_streamp z, int r)
02861 {
02862   uInt n;
02863   Byte *p;
02864   Byte *q;
02865 
02866   /* static copies of source and destination pointers */
02867   p = z->next_out;
02868   q = s->read;
02869 
02870   /* compute number of bytes to copy as as end of window */
02871   n = (uInt)((q <= s->write ? s->write : s->end) - q);
02872   if (n > z->avail_out) n = z->avail_out;
02873   if (n && r == Z_BUF_ERROR) r = Z_OK;
02874 
02875   /* update counters */
02876   z->avail_out -= n;
02877   z->total_out += n;
02878 
02879   /* update check information */
02880   if (s->checkfn != Z_NULL)
02881     z->adler = s->check = (*s->checkfn)(s->check, q, n);
02882 
02883   /* copy as as end of window */
02884   zmemcpy(p, q, n);
02885   p += n;
02886   q += n;
02887 
02888   /* see if more to copy at beginning of window */
02889   if (q == s->end)
02890   {
02891     /* wrap pointers */
02892     q = s->window;
02893     if (s->write == s->end)
02894       s->write = s->window;
02895 
02896     /* compute bytes to copy */
02897     n = (uInt)(s->write - q);
02898     if (n > z->avail_out) n = z->avail_out;
02899     if (n && r == Z_BUF_ERROR) r = Z_OK;
02900 
02901     /* update counters */
02902     z->avail_out -= n;
02903     z->total_out += n;
02904 
02905     /* update check information */
02906     if (s->checkfn != Z_NULL)
02907       z->adler = s->check = (*s->checkfn)(s->check, q, n);
02908 
02909     /* copy */
02910     zmemcpy(p, q, n);
02911     p += n;
02912     q += n;
02913   }
02914 
02915   /* update pointers */
02916   z->next_out = p;
02917   s->read = q;
02918 
02919   /* done */
02920   return r;
02921 }
02922 
02923 /* inftrees.c -- generate Huffman trees for efficient decoding
02924  * Copyright (C) 1995-1998 Mark Adler
02925  * For conditions of distribution and use, see copyright notice in zlib.h 
02926  */
02927 
02928 static const char inflate_copyright[] =
02929    " inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
02930 /*
02931   If you use the zlib library in a product, an acknowledgment is welcome
02932   in the documentation of your product. If for some reason you cannot
02933   include such an acknowledgment, I would appreciate that you keep this
02934   copyright string in the executable of your product.
02935  */
02936 
02937 /* simplify the use of the inflate_huft type with some defines */
02938 #define exop word.what.Exop
02939 #define bits word.what.Bits
02940 
02941 
02942 static int huft_build OF((
02943     uInt *,             /* code lengths in bits */
02944     uInt,               /* number of codes */
02945     uInt,               /* number of "simple" codes */
02946     const uInt *,       /* list of base values for non-simple codes */
02947     const uInt *,       /* list of extra bits for non-simple codes */
02948     inflate_huft **,    /* result: starting table */
02949     uInt *,             /* maximum lookup bits (returns actual) */
02950     inflate_huft *,     /* space for trees */
02951     uInt *,             /* hufts used in space */
02952     uInt * ));          /* space for values */
02953 
02954 /* Tables for deflate from PKZIP's appnote.txt. */
02955 static const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
02956         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
02957         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
02958         /* see note #13 above about 258 */
02959 static const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
02960         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
02961         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
02962 static const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
02963         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
02964         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
02965         8193, 12289, 16385, 24577};
02966 static const uInt cpdext[30] = { /* Extra bits for distance codes */
02967         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
02968         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
02969         12, 12, 13, 13};
02970 
02971 /*
02972    Huffman code decoding is performed using a multi-level table lookup.
02973    The fastest way to decode is to simply build a lookup table whose
02974    size is determined by the longest code.  However, the time it takes
02975    to build this table can also be a factor if the data being decoded
02976    is not very long.  The most common codes are necessarily the
02977    shortest codes, so those codes dominate the decoding time, and hence
02978    the speed.  The idea is you can have a shorter table that decodes the
02979    shorter, more probable codes, and then point to subsidiary tables for
02980    the longer codes.  The time it costs to decode the longer codes is
02981    then traded against the time it takes to make longer tables.
02982 
02983    This results of this trade are in the variables lbits and dbits
02984    below.  lbits is the number of bits the first level table for literal/
02985    length codes can decode in one step, and dbits is the same thing for
02986    the distance codes.  Subsequent tables are also less than or equal to
02987    those sizes.  These values may be adjusted either when all of the
02988    codes are shorter than that, in which case the longest code length in
02989    bits is used, or when the shortest code is *longer* than the requested
02990    table size, in which case the length of the shortest code in bits is
02991    used.
02992 
02993    There are two different values for the two tables, since they code a
02994    different number of possibilities each.  The literal/length table
02995    codes 286 possible values, or in a flat code, a little over eight
02996    bits.  The distance table codes 30 possible values, or a little less
02997    than five bits, flat.  The optimum values for speed end up being
02998    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
02999    The optimum values may differ though from machine to machine, and
03000    possibly even between compilers.  Your mileage may vary.
03001  */
03002 
03003 
03004 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
03005 #define BMAX 15         /* maximum bit length of any code */
03006 
03007 static int huft_build(uInt *b, uInt n, uInt s, const uInt *d, const uInt *e, inflate_huft ** t, uInt *m, inflate_huft *hp, uInt *hn, uInt *v)
03008 //uInt *b;               /* code lengths in bits (all assumed <= BMAX) */
03009 //uInt n;                 /* number of codes (assumed <= 288) */
03010 //uInt s;                 /* number of simple-valued codes (0..s-1) */
03011 //const uInt *d;         /* list of base values for non-simple codes */
03012 //const uInt *e;         /* list of extra bits for non-simple codes */
03013 //inflate_huft ** t;        /* result: starting table */
03014 //uInt *m;               /* maximum lookup bits, returns actual */
03015 //inflate_huft *hp;       /* space for trees */
03016 //uInt *hn;               /* hufts used in space */
03017 //uInt *v;               /* working area: values in order of bit length */
03018 /* Given a list of code lengths and a maximum table size, make a set of
03019    tables to decode that set of codes.  Return Z_OK on success, Z_BUF_ERROR
03020    if the given code set is incomplete (the tables are still built in this
03021    case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
03022    lengths), or Z_MEM_ERROR if not enough memory. */
03023 {
03024 
03025   uInt a;                       /* counter for codes of length k */
03026   uInt c[BMAX+1];               /* bit length count table */
03027   uInt f;                       /* i repeats in table every f entries */
03028   int g;                        /* maximum code length */
03029   int h;                        /* table level */
03030   register uInt i;              /* counter, current code */
03031   register uInt j;              /* counter */
03032   register int k;               /* number of bits in current code */
03033   int l;                        /* bits per table (returned in m) */
03034   uInt mask;                    /* (1 << w) - 1, to avoid cc -O bug on HP */
03035   register uInt *p;            /* pointer into c[], b[], or v[] */
03036   inflate_huft *q;              /* points to current table */
03037   struct inflate_huft_s r;      /* table entry for structure assignment */
03038   inflate_huft *u[BMAX];        /* table stack */
03039   register int w;               /* bits before this table == (l * h) */
03040   uInt x[BMAX+1];               /* bit offsets, then code stack */
03041   uInt *xp;                    /* pointer into x */
03042   int y;                        /* number of dummy codes added */
03043   uInt z;                       /* number of entries in current table */
03044 
03045 
03046   /* Generate counts for each bit length */
03047   p = c;
03048 #define C0 *p++ = 0;
03049 #define C2 C0 C0 C0 C0
03050 #define C4 C2 C2 C2 C2
03051   C4                            /* clear c[]--assume BMAX+1 is 16 */
03052   p = b;  i = n;
03053   do {
03054     c[*p++]++;                  /* assume all entries <= BMAX */
03055   } while (--i);
03056   if (c[0] == n)                /* null input--all zero length codes */
03057   {
03058     *t = (inflate_huft *)Z_NULL;
03059     *m = 0;
03060     return Z_OK;
03061   }
03062 
03063 
03064   /* Find minimum and maximum length, bound *m by those */
03065   l = *m;
03066   for (j = 1; j <= BMAX; j++)
03067     if (c[j])
03068       break;
03069   k = j;                        /* minimum code length */
03070   if ((uInt)l < j)
03071     l = j;
03072   for (i = BMAX; i; i--)
03073     if (c[i])
03074       break;
03075   g = i;                        /* maximum code length */
03076   if ((uInt)l > i)
03077     l = i;
03078   *m = l;
03079 
03080 
03081   /* Adjust last length count to fill out codes, if needed */
03082   for (y = 1 << j; j < i; j++, y <<= 1)
03083     if ((y -= c[j]) < 0)
03084       return Z_DATA_ERROR;
03085   if ((y -= c[i]) < 0)
03086     return Z_DATA_ERROR;
03087   c[i] += y;
03088 
03089 
03090   /* Generate starting offsets into the value table for each length */
03091   x[1] = j = 0;
03092   p = c + 1;  xp = x + 2;
03093   while (--i) {                 /* note that i == g from above */
03094     *xp++ = (j += *p++);
03095   }
03096 
03097 
03098   /* Make a table of values in order of bit lengths */
03099   p = b;  i = 0;
03100   do {
03101     if ((j = *p++) != 0)
03102       v[x[j]++] = i;
03103   } while (++i < n);
03104   n = x[g];                     /* set n to length of v */
03105 
03106 
03107   /* Generate the Huffman codes and for each, make the table entries */
03108   x[0] = i = 0;                 /* first Huffman code is zero */
03109   p = v;                        /* grab values in bit order */
03110   h = -1;                       /* no tables yet--level -1 */
03111   w = -l;                       /* bits decoded == (l * h) */
03112   u[0] = (inflate_huft *)Z_NULL;        /* just to keep compilers happy */
03113   q = (inflate_huft *)Z_NULL;   /* ditto */
03114   z = 0;                        /* ditto */
03115 
03116   /* go through the bit lengths (k already is bits in shortest code) */
03117   for (; k <= g; k++)
03118   {
03119     a = c[k];
03120     while (a--)
03121     {
03122       /* here i is the Huffman code of length k bits for value *p */
03123       /* make tables up to required level */
03124       while (k > w + l)
03125       {
03126         h++;
03127         w += l;                 /* previous table always l bits */
03128 
03129         /* compute minimum size table less than or equal to l bits */
03130         z = g - w;
03131         z = z > (uInt)l ? l : z;        /* table size upper limit */
03132         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
03133         {                       /* too few codes for k-w bit table */
03134           f -= a + 1;           /* deduct codes from patterns left */
03135           xp = c + k;
03136           if (j < z)
03137             while (++j < z)     /* try smaller tables up to z bits */
03138             {
03139               if ((f <<= 1) <= *++xp)
03140                 break;          /* enough codes to use up j bits */
03141               f -= *xp;         /* else deduct codes from patterns */
03142             }
03143         }
03144         z = 1 << j;             /* table entries for j-bit table */
03145 
03146         /* allocate new table */
03147         if (*hn + z > MANY)     /* (note: doesn't matter for fixed) */
03148           return Z_MEM_ERROR;   /* not enough memory */
03149         u[h] = q = hp + *hn;
03150         *hn += z;
03151 
03152         /* connect to last table, if there is one */
03153         if (h)
03154         {
03155           x[h] = i;             /* save pattern for backing up */
03156           r.bits = (Byte)l;     /* bits to dump before this table */
03157           r.exop = (Byte)j;     /* bits in this table */
03158           j = i >> (w - l);
03159           r.base = (uInt)(q - u[h-1] - j);   /* offset to this table */
03160           u[h-1][j] = r;        /* connect to last table */
03161         }
03162         else
03163           *t = q;               /* first table is returned result */
03164       }
03165 
03166       /* set up table entry in r */
03167       r.bits = (Byte)(k - w);
03168       if (p >= v + n)
03169         r.exop = 128 + 64;      /* out of values--invalid code */
03170       else if (*p < s)
03171       {
03172         r.exop = (Byte)(*p < 256 ? 0 : 32 + 64);     /* 256 is end-of-block */
03173         r.base = *p++;          /* simple code is just the value */
03174       }
03175       else
03176       {
03177         r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
03178         r.base = d[*p++ - s];
03179       }
03180 
03181       /* fill code-like entries with r */
03182       f = 1 << (k - w);
03183       for (j = i >> w; j < z; j += f)
03184         q[j] = r;
03185 
03186       /* backwards increment the k-bit code i */
03187       for (j = 1 << (k - 1); i & j; j >>= 1)
03188         i ^= j;
03189       i ^= j;
03190 
03191       /* backup over finished tables */
03192       mask = (1 << w) - 1;      /* needed on HP, cc -O bug */
03193       while ((i & mask) != x[h])
03194       {
03195         h--;                    /* don't need to update q */
03196         w -= l;
03197         mask = (1 << w) - 1;
03198       }
03199     }
03200   }
03201 
03202 
03203   /* Return Z_BUF_ERROR if we were given an incomplete table */
03204   return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
03205 }
03206 
03207 
03208 int inflate_trees_bits(uInt *c, uInt *bb, inflate_huft * *tb, inflate_huft *hp, z_streamp z)
03209 //uInt *c;               /* 19 code lengths */
03210 //uInt *bb;              /* bits tree desired/actual depth */
03211 //inflate_huft * *tb; /* bits tree result */
03212 //inflate_huft *hp;       /* space for trees */
03213 //z_streamp z;            /* for messages */
03214 {
03215   int r;
03216   uInt hn = 0;          /* hufts used in space */
03217   uInt *v;             /* work area for huft_build */
03218 
03219   if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
03220     return Z_MEM_ERROR;
03221   r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL,
03222                  tb, bb, hp, &hn, v);
03223   if (r == Z_DATA_ERROR)
03224     z->msg = (char*)"oversubscribed dynamic bit lengths tree";
03225   else if (r == Z_BUF_ERROR || *bb == 0)
03226   {
03227     z->msg = (char*)"incomplete dynamic bit lengths tree";
03228     r = Z_DATA_ERROR;
03229   }
03230   ZFREE(z, v);
03231   return r;
03232 }
03233 
03234 
03235 int inflate_trees_dynamic(uInt nl, uInt nd, uInt *c, uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, inflate_huft *hp, z_streamp z)
03236 //uInt nl;                /* number of literal/length codes */
03237 //uInt nd;                /* number of distance codes */
03238 //uInt *c;               /* that many (total) code lengths */
03239 //uInt *bl;              /* literal desired/actual bit depth */
03240 //uInt *bd;              /* distance desired/actual bit depth */
03241 //inflate_huft * *tl; /* literal/length tree result */
03242 //inflate_huft * *td; /* distance tree result */
03243 //inflate_huft *hp;       /* space for trees */
03244 //z_streamp z;            /* for messages */
03245 {
03246   int r;
03247   uInt hn = 0;          /* hufts used in space */
03248   uInt *v;             /* work area for huft_build */
03249 
03250   /* allocate work area */
03251   if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
03252     return Z_MEM_ERROR;
03253 
03254   /* build literal/length tree */
03255   r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
03256   if (r != Z_OK || *bl == 0)
03257   {
03258     if (r == Z_DATA_ERROR)
03259       z->msg = (char*)"oversubscribed literal/length tree";
03260     else if (r != Z_MEM_ERROR)
03261     {
03262       z->msg = (char*)"incomplete literal/length tree";
03263       r = Z_DATA_ERROR;
03264     }
03265     ZFREE(z, v);
03266     return r;
03267   }
03268 
03269   /* build distance tree */
03270   r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
03271   if (r != Z_OK || (*bd == 0 && nl > 257))
03272   {
03273     if (r == Z_DATA_ERROR)
03274       z->msg = (char*)"oversubscribed distance tree";
03275     else if (r == Z_BUF_ERROR) {
03276 #ifdef PKZIP_BUG_WORKAROUND
03277       r = Z_OK;
03278     }
03279 #else
03280       z->msg = (char*)"incomplete distance tree";
03281       r = Z_DATA_ERROR;
03282     }
03283     else if (r != Z_MEM_ERROR)
03284     {
03285       z->msg = (char*)"empty distance tree with lengths";
03286       r = Z_DATA_ERROR;
03287     }
03288     ZFREE(z, v);
03289     return r;
03290 #endif
03291   }
03292 
03293   /* done */
03294   ZFREE(z, v);
03295   return Z_OK;
03296 }
03297 
03298 /* inffixed.h -- table for decoding fixed codes
03299  * Generated automatically by the maketree.c program
03300  */
03301 
03302 /* WARNING: this file should *not* be used by applications. It is
03303    part of the implementation of the compression library and is
03304    subject to change. Applications should only use zlib.h.
03305  */
03306 
03307 static uInt fixed_bl = 9;
03308 static uInt fixed_bd = 5;
03309 static inflate_huft fixed_tl[] = {
03310     {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
03311     {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
03312     {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
03313     {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
03314     {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
03315     {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
03316     {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
03317     {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
03318     {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
03319     {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
03320     {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
03321     {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
03322     {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
03323     {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
03324     {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
03325     {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
03326     {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
03327     {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
03328     {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
03329     {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
03330     {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
03331     {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
03332     {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
03333     {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
03334     {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
03335     {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
03336     {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
03337     {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
03338     {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
03339     {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
03340     {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
03341     {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
03342     {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
03343     {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
03344     {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
03345     {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
03346     {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
03347     {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
03348     {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
03349     {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
03350     {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
03351     {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
03352     {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
03353     {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
03354     {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
03355     {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
03356     {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
03357     {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
03358     {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
03359     {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
03360     {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
03361     {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
03362     {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
03363     {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
03364     {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
03365     {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
03366     {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
03367     {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
03368     {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
03369     {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
03370     {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
03371     {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
03372     {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
03373     {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
03374     {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
03375     {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
03376     {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
03377     {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
03378     {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
03379     {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
03380     {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
03381     {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
03382     {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
03383     {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
03384     {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
03385     {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
03386     {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
03387     {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
03388     {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
03389     {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
03390     {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
03391     {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
03392     {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
03393     {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
03394     {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
03395     {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
03396     {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
03397     {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
03398     {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
03399     {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
03400     {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
03401     {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
03402     {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
03403     {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
03404     {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
03405     {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
03406     {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
03407     {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
03408     {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
03409     {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
03410     {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
03411     {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
03412     {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
03413     {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
03414     {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
03415     {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
03416     {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
03417     {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
03418     {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
03419     {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
03420     {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
03421     {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
03422     {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
03423     {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
03424     {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
03425     {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
03426     {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
03427     {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
03428     {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
03429     {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
03430     {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
03431     {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
03432     {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
03433     {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
03434     {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
03435     {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
03436     {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
03437     {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
03438   };
03439 static inflate_huft fixed_td[] = {
03440     {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
03441     {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
03442     {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
03443     {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
03444     {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
03445     {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
03446     {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
03447     {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
03448   };
03449 
03450 int inflate_trees_fixed(uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, z_streamp z)
03451 //uInt *bl;               /* literal desired/actual bit depth */
03452 //uInt *bd;               /* distance desired/actual bit depth */
03453 //inflate_huft * *tl;  /* literal/length tree result */
03454 //inflate_huft * *td;  /* distance tree result */
03455 //z_streamp z;             /* for memory allocation */
03456 {
03457   *bl = fixed_bl;
03458   *bd = fixed_bd;
03459   *tl = fixed_tl;
03460   *td = fixed_td;
03461   return Z_OK;
03462 }
03463 
03464 /* simplify the use of the inflate_huft type with some defines */
03465 #define exop word.what.Exop
03466 #define bits word.what.Bits
03467 
03468 /* macros for bit input with no checking and for returning unused bytes */
03469 #define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
03470 #define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;}
03471 
03472 /* Called with number of bytes left to write in window at least 258
03473    (the maximum string length) and number of input bytes available
03474    at least ten.  The ten bytes are six bytes for the longest length/
03475    distance pair plus four bytes for overloading the bit buffer. */
03476 
03477 static int inflate_fast(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, inflate_blocks_statef *s, z_streamp z)
03478 {
03479   inflate_huft *t;      /* temporary pointer */
03480   uInt e;               /* extra bits or operation */
03481   uLong b;              /* bit buffer */
03482   uInt k;               /* bits in bit buffer */
03483   Byte *p;             /* input data pointer */
03484   uInt n;               /* bytes available there */
03485   Byte *q;             /* output window write pointer */
03486   uInt m;               /* bytes to end of window or read pointer */
03487   uInt ml;              /* mask for literal/length tree */
03488   uInt md;              /* mask for distance tree */
03489   uInt c;               /* bytes to copy */
03490   uInt d;               /* distance back to copy from */
03491   Byte *r;             /* copy source pointer */
03492 
03493   /* load input, output, bit values */
03494   LOAD
03495 
03496   /* initialize masks */
03497   ml = inflate_mask[bl];
03498   md = inflate_mask[bd];
03499 
03500   /* do until not enough input or output space for fast loop */
03501   do {                          /* assume called with m >= 258 && n >= 10 */
03502     /* get literal/length code */
03503     GRABBITS(20)                /* max bits for literal/length code */
03504     if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
03505     {
03506       DUMPBITS(t->bits)
03507       Tracevv((t->base >= 0x20 && t->base < 0x7f ?
03508                 "inflate:         * literal '%c'\n" :
03509                 "inflate:         * literal 0x%02x\n", t->base));
03510       *q++ = (Byte)t->base;
03511       m--;
03512       continue;
03513     }
03514     do {
03515       DUMPBITS(t->bits)
03516       if (e & 16)
03517       {
03518         /* get extra bits for length */
03519         e &= 15;
03520         c = t->base + ((uInt)b & inflate_mask[e]);
03521         DUMPBITS(e)
03522         Tracevv(("inflate:         * length %u\n", c));
03523 
03524         /* decode distance base of block to copy */
03525         GRABBITS(15);           /* max bits for distance code */
03526         e = (t = td + ((uInt)b & md))->exop;
03527         do {
03528           DUMPBITS(t->bits)
03529           if (e & 16)
03530           {
03531             /* get extra bits to add to distance base */
03532             e &= 15;
03533             GRABBITS(e)         /* get extra bits (up to 13) */
03534             d = t->base + ((uInt)b & inflate_mask[e]);
03535             DUMPBITS(e)
03536             Tracevv(("inflate:         * distance %u\n", d));
03537 
03538             /* do the copy */
03539             m -= c;
03540             if ((uInt)(q - s->window) >= d)     /* offset before dest */
03541             {                                   /*  just copy */
03542               r = q - d;
03543               *q++ = *r++;  c--;        /* minimum count is three, */
03544               *q++ = *r++;  c--;        /*  so unroll loop a little */
03545             }
03546             else                        /* else offset after destination */
03547             {
03548               e = d - (uInt)(q - s->window); /* bytes from offset to end */
03549               r = s->end - e;           /* pointer to offset */
03550               if (c > e)                /* if source crosses, */
03551               {
03552                 c -= e;                 /* copy to end of window */
03553                 do {
03554                   *q++ = *r++;
03555                 } while (--e);
03556                 r = s->window;          /* copy rest from start of window */
03557               }
03558             }
03559             do {                        /* copy all or what's left */
03560               *q++ = *r++;
03561             } while (--c);
03562             break;
03563           }
03564           else if ((e & 64) == 0)
03565           {
03566             t += t->base;
03567             e = (t += ((uInt)b & inflate_mask[e]))->exop;
03568           }
03569           else
03570           {
03571             z->msg = (char*)"invalid distance code";
03572             UNGRAB
03573             UPDATE
03574             return Z_DATA_ERROR;
03575           }
03576         } while (1);
03577         break;
03578       }
03579       if ((e & 64) == 0)
03580       {
03581         t += t->base;
03582         if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0)
03583         {
03584           DUMPBITS(t->bits)
03585           Tracevv((t->base >= 0x20 && t->base < 0x7f ?
03586                     "inflate:         * literal '%c'\n" :
03587                     "inflate:         * literal 0x%02x\n", t->base));
03588           *q++ = (Byte)t->base;
03589           m--;
03590           break;
03591         }
03592       }
03593       else if (e & 32)
03594       {
03595         Tracevv(("inflate:         * end of block\n"));
03596         UNGRAB
03597         UPDATE
03598         return Z_STREAM_END;
03599       }
03600       else
03601       {
03602         z->msg = (char*)"invalid literal/length code";
03603         UNGRAB
03604         UPDATE
03605         return Z_DATA_ERROR;
03606       }
03607     } while (1);
03608   } while (m >= 258 && n >= 10);
03609 
03610   /* not enough input or output--restore pointers and return */
03611   UNGRAB
03612   UPDATE
03613   return Z_OK;
03614 }
03615 
03616 /* infcodes.c -- process literals and length/distance pairs
03617  * Copyright (C) 1995-1998 Mark Adler
03618  * For conditions of distribution and use, see copyright notice in zlib.h 
03619  */
03620 
03621 /* simplify the use of the inflate_huft type with some defines */
03622 #define exop word.what.Exop
03623 #define bits word.what.Bits
03624 
03625 typedef enum {        /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
03626       START,    /* x: set up for LEN */
03627       LEN,      /* i: get length/literal/eob next */
03628       LENEXT,   /* i: getting length extra (have base) */
03629       DIST,     /* i: get distance next */
03630       DISTEXT,  /* i: getting distance extra */
03631       COPY,     /* o: copying bytes in window, waiting for space */
03632       LIT,      /* o: got literal, waiting for output space */
03633       WASH,     /* o: got eob, possibly still output waiting */
03634       END,      /* x: got eob and all data flushed */
03635       BADCODE}  /* x: got error */
03636 inflate_codes_mode;
03637 
03638 /* inflate codes private state */
03639 struct inflate_codes_state {
03640 
03641   /* mode */
03642   inflate_codes_mode mode;      /* current inflate_codes mode */
03643 
03644   /* mode dependent information */
03645   uInt len;
03646   union {
03647     struct {
03648       inflate_huft *tree;       /* pointer into tree */
03649       uInt need;                /* bits needed */
03650     } code;             /* if LEN or DIST, where in tree */
03651     uInt lit;           /* if LIT, literal */
03652     struct {
03653       uInt get;                 /* bits to get for extra */
03654       uInt dist;                /* distance back to copy from */
03655     } copy;             /* if EXT or COPY, where and how much */
03656   } sub;                /* submode */
03657 
03658   /* mode independent information */
03659   Byte lbits;           /* ltree bits decoded per branch */
03660   Byte dbits;           /* dtree bits decoder per branch */
03661   inflate_huft *ltree;          /* literal/length/eob tree */
03662   inflate_huft *dtree;          /* distance tree */
03663 
03664 };
03665 
03666 
03667 inflate_codes_statef *inflate_codes_new(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, z_streamp z)
03668 {
03669   inflate_codes_statef *c;
03670 
03671   if ((c = (inflate_codes_statef *)
03672        ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
03673   {
03674     c->mode = START;
03675     c->lbits = (Byte)bl;
03676     c->dbits = (Byte)bd;
03677     c->ltree = tl;
03678     c->dtree = td;
03679     Tracev(("inflate:       codes new\n"));
03680   }
03681   return c;
03682 }
03683 
03684 
03685 int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r)
03686 {
03687   uInt j;               /* temporary storage */
03688   inflate_huft *t;      /* temporary pointer */
03689   uInt e;               /* extra bits or operation */
03690   uLong b;              /* bit buffer */
03691   uInt k;               /* bits in bit buffer */
03692   Byte *p;             /* input data pointer */
03693   uInt n;               /* bytes available there */
03694   Byte *q;             /* output window write pointer */
03695   uInt m;               /* bytes to end of window or read pointer */
03696   Byte *f;             /* pointer to copy strings from */
03697   inflate_codes_statef *c = s->sub.decode.codes;  /* codes state */
03698 
03699   /* copy input/output information to locals (UPDATE macro restores) */
03700   LOAD
03701 
03702   /* process input and output based on current state */
03703   while (1) switch (c->mode)
03704   {             /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
03705     case START:         /* x: set up for LEN */
03706 #ifndef SLOW
03707       if (m >= 258 && n >= 10)
03708       {
03709         UPDATE
03710         r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
03711         LOAD
03712         if (r != Z_OK)
03713         {
03714           c->mode = r == Z_STREAM_END ? WASH : BADCODE;
03715           break;
03716         }
03717       }
03718 #endif /* !SLOW */
03719       c->sub.code.need = c->lbits;
03720       c->sub.code.tree = c->ltree;
03721       c->mode = LEN;
03722     case LEN:           /* i: get length/literal/eob next */
03723       j = c->sub.code.need;
03724       NEEDBITS(j)
03725       t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
03726       DUMPBITS(t->bits)
03727       e = (uInt)(t->exop);
03728       if (e == 0)               /* literal */
03729       {
03730         c->sub.lit = t->base;
03731         Tracevv((t->base >= 0x20 && t->base < 0x7f ?
03732                  "inflate:         literal '%c'\n" :
03733                  "inflate:         literal 0x%02x\n", t->base));
03734         c->mode = LIT;
03735         break;
03736       }
03737       if (e & 16)               /* length */
03738       {
03739         c->sub.copy.get = e & 15;
03740         c->len = t->base;
03741         c->mode = LENEXT;
03742         break;
03743       }
03744       if ((e & 64) == 0)        /* next table */
03745       {
03746         c->sub.code.need = e;
03747         c->sub.code.tree = t + t->base;
03748         break;
03749       }
03750       if (e & 32)               /* end of block */
03751       {
03752         Tracevv(("inflate:         end of block\n"));
03753         c->mode = WASH;
03754         break;
03755       }
03756       c->mode = BADCODE;        /* invalid code */
03757       z->msg = (char*)"invalid literal/length code";
03758       r = Z_DATA_ERROR;
03759       LEAVE
03760     case LENEXT:        /* i: getting length extra (have base) */
03761       j = c->sub.copy.get;
03762       NEEDBITS(j)
03763       c->len += (uInt)b & inflate_mask[j];
03764       DUMPBITS(j)
03765       c->sub.code.need = c->dbits;
03766       c->sub.code.tree = c->dtree;
03767       Tracevv(("inflate:         length %u\n", c->len));
03768       c->mode = DIST;
03769     case DIST:          /* i: get distance next */
03770       j = c->sub.code.need;
03771       NEEDBITS(j)
03772       t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
03773       DUMPBITS(t->bits)
03774       e = (uInt)(t->exop);
03775       if (e & 16)               /* distance */
03776       {
03777         c->sub.copy.get = e & 15;
03778         c->sub.copy.dist = t->base;
03779         c->mode = DISTEXT;
03780         break;
03781       }
03782       if ((e & 64) == 0)        /* next table */
03783       {
03784         c->sub.code.need = e;
03785         c->sub.code.tree = t + t->base;
03786         break;
03787       }
03788       c->mode = BADCODE;        /* invalid code */
03789       z->msg = (char*)"invalid distance code";
03790       r = Z_DATA_ERROR;
03791       LEAVE
03792     case DISTEXT:       /* i: getting distance extra */
03793       j = c->sub.copy.get;
03794       NEEDBITS(j)
03795       c->sub.copy.dist += (uInt)b & inflate_mask[j];
03796       DUMPBITS(j)
03797       Tracevv(("inflate:         distance %u\n", c->sub.copy.dist));
03798       c->mode = COPY;
03799     case COPY:          /* o: copying bytes in window, waiting for space */
03800 #ifndef __TURBOC__ /* Turbo C bug for following expression */
03801       f = (uInt)(q - s->window) < c->sub.copy.dist ?
03802           s->end - (c->sub.copy.dist - (q - s->window)) :
03803           q - c->sub.copy.dist;
03804 #else
03805       f = q - c->sub.copy.dist;
03806       if ((uInt)(q - s->window) < c->sub.copy.dist)
03807         f = s->end - (c->sub.copy.dist - (uInt)(q - s->window));
03808 #endif
03809       while (c->len)
03810       {
03811         NEEDOUT
03812         OUTBYTE(*f++)
03813         if (f == s->end)
03814           f = s->window;
03815         c->len--;
03816       }
03817       c->mode = START;
03818       break;
03819     case LIT:           /* o: got literal, waiting for output space */
03820       NEEDOUT
03821       OUTBYTE(c->sub.lit)
03822       c->mode = START;
03823       break;
03824     case WASH:          /* o: got eob, possibly more output */
03825       if (k > 7)        /* return unused byte, if any */
03826       {
03827         Assert(k < 16, "inflate_codes grabbed too many bytes")
03828         k -= 8;
03829         n++;
03830         p--;            /* can always return one */
03831       }
03832       FLUSH
03833       if (s->read != s->write)
03834         LEAVE
03835       c->mode = END;
03836     case END:
03837       r = Z_STREAM_END;
03838       LEAVE
03839     case BADCODE:       /* x: got error */
03840       r = Z_DATA_ERROR;
03841       LEAVE
03842     default:
03843       r = Z_STREAM_ERROR;
03844       LEAVE
03845   }
03846 #ifdef NEED_DUMMY_RETURN
03847   return Z_STREAM_ERROR;  /* Some dumb compilers complain without this */
03848 #endif
03849 }
03850 
03851 
03852 void inflate_codes_free(inflate_codes_statef *c, z_streamp z)
03853 {
03854   ZFREE(z, c);
03855   Tracev(("inflate:       codes free\n"));
03856 }
03857 
03858 /* adler32.c -- compute the Adler-32 checksum of a data stream
03859  * Copyright (C) 1995-1998 Mark Adler
03860  * For conditions of distribution and use, see copyright notice in zlib.h 
03861  */
03862 
03863 #define BASE 65521L /* largest prime smaller than 65536 */
03864 #define NMAX 5552
03865 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
03866 
03867 #undef DO1
03868 #undef DO2
03869 #undef DO4
03870 #undef DO8
03871 
03872 #define DO1(buf,i)  {s1 += buf[i]; s2 += s1;}
03873 #define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
03874 #define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
03875 #define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
03876 #define DO16(buf)   DO8(buf,0); DO8(buf,8);
03877 
03878 /* ========================================================================= */
03879 static uLong adler32(uLong adler, const Byte *buf, uInt len)
03880 {
03881     unsigned long s1 = adler & 0xffff;
03882     unsigned long s2 = (adler >> 16) & 0xffff;
03883     int k;
03884 
03885     if (buf == Z_NULL) return 1L;
03886 
03887     while (len > 0) {
03888         k = len < NMAX ? len : NMAX;
03889         len -= k;
03890         while (k >= 16) {
03891             DO16(buf);
03892         buf += 16;
03893             k -= 16;
03894         }
03895         if (k != 0) do {
03896             s1 += *buf++;
03897         s2 += s1;
03898         } while (--k);
03899         s1 %= BASE;
03900         s2 %= BASE;
03901     }
03902     return (s2 << 16) | s1;
03903 }
03904 
03905 
03906 /* infblock.h -- header to use infblock.c
03907  * Copyright (C) 1995-1998 Mark Adler
03908  * For conditions of distribution and use, see copyright notice in zlib.h 
03909  */
03910 
03911 /* WARNING: this file should *not* be used by applications. It is
03912    part of the implementation of the compression library and is
03913    subject to change. Applications should only use zlib.h.
03914  */
03915 
03916 static inflate_blocks_statef * inflate_blocks_new OF((
03917     z_streamp z,
03918     check_func c,               /* check function */
03919     uInt w));                   /* window size */
03920 
03921 static int inflate_blocks OF((
03922     inflate_blocks_statef *,
03923     z_streamp ,
03924     int));                      /* initial return code */
03925 
03926 static void inflate_blocks_reset OF((
03927     inflate_blocks_statef *,
03928     z_streamp ,
03929     uLong *));                  /* check value on output */
03930 
03931 static int inflate_blocks_free OF((
03932     inflate_blocks_statef *,
03933     z_streamp));
03934 
03935 #if 0
03936 static void inflate_set_dictionary OF((
03937     inflate_blocks_statef *s,
03938     const Byte *d,  /* dictionary */
03939     uInt  n));       /* dictionary length */
03940 
03941 static int inflate_blocks_sync_point OF((
03942     inflate_blocks_statef *s));
03943 #endif
03944 
03945 typedef enum {
03946       imMETHOD,   /* waiting for method byte */
03947       imFLAG,     /* waiting for flag byte */
03948       imDICT4,    /* four dictionary check bytes to go */
03949       imDICT3,    /* three dictionary check bytes to go */
03950       imDICT2,    /* two dictionary check bytes to go */
03951       imDICT1,    /* one dictionary check byte to go */
03952       imDICT0,    /* waiting for inflateSetDictionary */
03953       imBLOCKS,   /* decompressing blocks */
03954       imCHECK4,   /* four check bytes to go */
03955       imCHECK3,   /* three check bytes to go */
03956       imCHECK2,   /* two check bytes to go */
03957       imCHECK1,   /* one check byte to go */
03958       imDONE,     /* finished check, done */
03959       imBAD}      /* got an error--stay here */
03960 inflate_mode;
03961 
03962 /* inflate private state */
03963 struct internal_state {
03964 
03965   /* mode */
03966   inflate_mode  mode;   /* current inflate mode */
03967 
03968   /* mode dependent information */
03969   union {
03970     uInt method;        /* if FLAGS, method byte */
03971     struct {
03972       uLong was;                /* computed check value */
03973       uLong need;               /* stream check value */
03974     } check;            /* if CHECK, check values to compare */
03975     uInt marker;        /* if BAD, inflateSync's marker bytes count */
03976   } sub;        /* submode */
03977 
03978   /* mode independent information */
03979   int  nowrap;          /* flag for no wrapper */
03980   uInt wbits;           /* log2(window size)  (8..15, defaults to 15) */
03981   inflate_blocks_statef 
03982     *blocks;            /* current inflate_blocks state */
03983 
03984 };
03985 
03986 
03987 int inflateReset(z_streamp z)
03988 {
03989   if (z == Z_NULL || z->state == Z_NULL)
03990     return Z_STREAM_ERROR;
03991   z->total_in = z->total_out = 0;
03992   z->msg = Z_NULL;
03993   z->state->mode = z->state->nowrap ? imBLOCKS : imMETHOD;
03994   inflate_blocks_reset(z->state->blocks, z, Z_NULL);
03995   Tracev(("inflate: reset\n"));
03996   return Z_OK;
03997 }
03998 
03999 
04000 int inflateEnd(z_streamp z)
04001 {
04002   if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
04003     return Z_STREAM_ERROR;
04004   if (z->state->blocks != Z_NULL)
04005     inflate_blocks_free(z->state->blocks, z);
04006   ZFREE(z, z->state);
04007   z->state = Z_NULL;
04008   Tracev(("inflate: end\n"));
04009   return Z_OK;
04010 }
04011 
04012 
04013 
04014 int inflateInit2_(z_streamp z, int w, const char *version, int stream_size)
04015 {
04016   if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
04017       stream_size != sizeof(z_stream))
04018       return Z_VERSION_ERROR;
04019 
04020   /* initialize state */
04021   if (z == Z_NULL)
04022     return Z_STREAM_ERROR;
04023   z->msg = Z_NULL;
04024   if (z->zalloc == Z_NULL)
04025   {
04026     z->zalloc = (void *(*)(void *, unsigned, unsigned))zcalloc;
04027     z->opaque = (voidp)0;
04028   }
04029   if (z->zfree == Z_NULL) z->zfree = (void (*)(void *, void *))zcfree;
04030   if ((z->state = (struct internal_state *)
04031        ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
04032     return Z_MEM_ERROR;
04033   z->state->blocks = Z_NULL;
04034 
04035   /* handle undocumented nowrap option (no zlib header or check) */
04036   z->state->nowrap = 0;
04037   if (w < 0)
04038   {
04039     w = - w;
04040     z->state->nowrap = 1;
04041   }
04042 
04043   /* set window size */
04044   if (w < 8 || w > 15)
04045   {
04046     inflateEnd(z);
04047     return Z_STREAM_ERROR;
04048   }
04049   z->state->wbits = (uInt)w;
04050 
04051   /* create inflate_blocks state */
04052   if ((z->state->blocks =
04053       inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
04054       == Z_NULL)
04055   {
04056     inflateEnd(z);
04057     return Z_MEM_ERROR;
04058   }
04059   Tracev(("inflate: allocated\n"));
04060 
04061   /* reset state */
04062   inflateReset(z);
04063   return Z_OK;
04064 }
04065 
04066 #if 0
04067 int inflateInit_(z_streamp z, const char *version, int stream_size)
04068 {
04069   return inflateInit2_(z, DEF_WBITS, version, stream_size);
04070 }
04071 #endif
04072 
04073 #define iNEEDBYTE {if(z->avail_in==0)return r;r=f;}
04074 #define iNEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
04075 
04076 int inflate(z_streamp z, int f)
04077 {
04078   int r;
04079   uInt b;
04080 
04081   if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
04082     return Z_STREAM_ERROR;
04083   f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
04084   r = Z_BUF_ERROR;
04085   while (1) switch (z->state->mode)
04086   {
04087     case imMETHOD:
04088       iNEEDBYTE
04089       if (((z->state->sub.method = iNEXTBYTE) & 0xf) != Z_DEFLATED)
04090       {
04091         z->state->mode = imBAD;
04092         z->msg = (char*)"unknown compression method";
04093         z->state->sub.marker = 5;       /* can't try inflateSync */
04094         break;
04095       }
04096       if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
04097       {
04098         z->state->mode = imBAD;
04099         z->msg = (char*)"invalid window size";
04100         z->state->sub.marker = 5;       /* can't try inflateSync */
04101         break;
04102       }
04103       z->state->mode = imFLAG;
04104     case imFLAG:
04105       iNEEDBYTE
04106       b = iNEXTBYTE;
04107       if (((z->state->sub.method << 8) + b) % 31)
04108       {
04109         z->state->mode = imBAD;
04110         z->msg = (char*)"incorrect header check";
04111         z->state->sub.marker = 5;       /* can't try inflateSync */
04112         break;
04113       }
04114       Tracev(("inflate: zlib header ok\n"));
04115       if (!(b & PRESET_DICT))
04116       {
04117         z->state->mode = imBLOCKS;
04118         break;
04119       }
04120       z->state->mode = imDICT4;
04121     case imDICT4:
04122       iNEEDBYTE
04123       z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
04124       z->state->mode = imDICT3;
04125     case imDICT3:
04126       iNEEDBYTE
04127       z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
04128       z->state->mode = imDICT2;
04129     case imDICT2:
04130       iNEEDBYTE
04131       z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
04132       z->state->mode = imDICT1;
04133     case imDICT1:
04134       iNEEDBYTE
04135       z->state->sub.check.need += (uLong)iNEXTBYTE;
04136       z->adler = z->state->sub.check.need;
04137       z->state->mode = imDICT0;
04138       return Z_NEED_DICT;
04139     case imDICT0:
04140       z->state->mode = imBAD;
04141       z->msg = (char*)"need dictionary";
04142       z->state->sub.marker = 0;       /* can try inflateSync */
04143       return Z_STREAM_ERROR;
04144     case imBLOCKS:
04145       r = inflate_blocks(z->state->blocks, z, r);
04146       if (r == Z_DATA_ERROR)
04147       {
04148         z->state->mode = imBAD;
04149         z->state->sub.marker = 0;       /* can try inflateSync */
04150         break;
04151       }
04152       if (r == Z_OK)
04153         r = f;
04154       if (r != Z_STREAM_END)
04155         return r;
04156       r = f;
04157       inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
04158       if (z->state->nowrap)
04159       {
04160         z->state->mode = imDONE;
04161         break;
04162       }
04163       z->state->mode = imCHECK4;
04164     case imCHECK4:
04165       iNEEDBYTE
04166       z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
04167       z->state->mode = imCHECK3;
04168     case imCHECK3:
04169       iNEEDBYTE
04170       z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
04171       z->state->mode = imCHECK2;
04172     case imCHECK2:
04173       iNEEDBYTE
04174       z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
04175       z->state->mode = imCHECK1;
04176     case imCHECK1:
04177       iNEEDBYTE
04178       z->state->sub.check.need += (uLong)iNEXTBYTE;
04179 
04180       if (z->state->sub.check.was != z->state->sub.check.need)
04181       {
04182         z->state->mode = imBAD;
04183         z->msg = (char*)"incorrect data check";
04184         z->state->sub.marker = 5;       /* can't try inflateSync */
04185         break;
04186       }
04187       Tracev(("inflate: zlib check ok\n"));
04188       z->state->mode = imDONE;
04189     case imDONE:
04190       return Z_STREAM_END;
04191     case imBAD:
04192       return Z_DATA_ERROR;
04193     default:
04194       return Z_STREAM_ERROR;
04195   }
04196 #ifdef NEED_DUMMY_RETURN
04197   return Z_STREAM_ERROR;  /* Some dumb compilers complain without this */
04198 #endif
04199 }
04200 
04201 // defined but not used
04202 #if 0
04203 int inflateSetDictionary(z_streamp z, const Byte *dictionary, uInt dictLength)
04204 {
04205   uInt length = dictLength;
04206 
04207   if (z == Z_NULL || z->state == Z_NULL || z->state->mode != imDICT0)
04208     return Z_STREAM_ERROR;
04209 
04210   if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR;
04211   z->adler = 1L;
04212 
04213   if (length >= ((uInt)1<<z->state->wbits))
04214   {
04215     length = (1<<z->state->wbits)-1;
04216     dictionary += dictLength - length;
04217   }
04218   inflate_set_dictionary(z->state->blocks, dictionary, length);
04219   z->state->mode = imBLOCKS;
04220   return Z_OK;
04221 }
04222 
04223 int inflateSync(z_streamp z)
04224 {
04225   uInt n;       /* number of bytes to look at */
04226   Byte *p;     /* pointer to bytes */
04227   uInt m;       /* number of marker bytes found in a row */
04228   uLong r, w;   /* temporaries to save total_in and total_out */
04229 
04230   /* set up */
04231   if (z == Z_NULL || z->state == Z_NULL)
04232     return Z_STREAM_ERROR;
04233   if (z->state->mode != imBAD)
04234   {
04235     z->state->mode = imBAD;
04236     z->state->sub.marker = 0;
04237   }
04238   if ((n = z->avail_in) == 0)
04239     return Z_BUF_ERROR;
04240   p = z->next_in;
04241   m = z->state->sub.marker;
04242 
04243   /* search */
04244   while (n && m < 4)
04245   {
04246     static const Byte mark[4] = {0, 0, 0xff, 0xff};
04247     if (*p == mark[m])
04248       m++;
04249     else if (*p)
04250       m = 0;
04251     else
04252       m = 4 - m;
04253     p++, n--;
04254   }
04255 
04256   /* restore */
04257   z->total_in += p - z->next_in;
04258   z->next_in = p;
04259   z->avail_in = n;
04260   z->state->sub.marker = m;
04261 
04262   /* return no joy or set up to restart on a new block */
04263   if (m != 4)
04264     return Z_DATA_ERROR;
04265   r = z->total_in;  w = z->total_out;
04266   inflateReset(z);
04267   z->total_in = r;  z->total_out = w;
04268   z->state->mode = imBLOCKS;
04269   return Z_OK;
04270 }
04271 
04272 /* Returns true if inflate is currently at the end of a block generated
04273  * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
04274  * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
04275  * but removes the length bytes of the resulting empty stored block. When
04276  * decompressing, PPP checks that at the end of input packet, inflate is
04277  * waiting for these length bytes.
04278  */
04279 int inflateSyncPoint(z_streamp z)
04280 {
04281   if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL)
04282     return Z_STREAM_ERROR;
04283   return inflate_blocks_sync_point(z->state->blocks);
04284 }
04285 #endif
04286 
04287 voidp zcalloc (voidp opaque, unsigned items, unsigned size)
04288 {
04289     if (opaque) items += size - size; /* make compiler happy */
04290     return (voidp)Z_Malloc(items*size);
04291 }
04292 
04293 void  zcfree (voidp opaque, voidp ptr)
04294 {
04295     Z_Free(ptr);
04296     if (opaque) return; /* make compiler happy */
04297 }
04298 
04299 

Generated on Thu Aug 25 12:37:48 2005 for Quake III Arena by  doxygen 1.3.9.1