]> icculus.org git repositories - icculus/iodoom3.git/blob - neo/framework/Unzip.cpp
Various Mac OS X tweaks to get this to build. Probably breaking things.
[icculus/iodoom3.git] / neo / framework / Unzip.cpp
1 #include "../idlib/precompiled.h"
2 #pragma hdrstop
3
4 #include "Unzip.h"
5
6 /* unzip.h -- IO for uncompress .zip files using zlib 
7    Version 0.15 beta, Mar 19th, 1998,
8
9    Copyright (C) 1998 Gilles Vollant
10
11    This unzip package allow extract file from .ZIP file, compatible with PKZip 2.04g
12      WinZip, InfoZip tools and compatible.
13    Encryption and multi volume ZipFile (span) are not supported.
14    Old compressions used by old PKZip 1.x are not supported
15
16    THIS IS AN ALPHA VERSION. AT THIS STAGE OF DEVELOPPEMENT, SOMES API OR STRUCTURE
17    CAN CHANGE IN FUTURE VERSION !!
18    I WAIT FEEDBACK at mail info@winimage.com
19    Visit also http://www.winimage.com/zLibDll/unzip.htm for evolution
20
21    Condition of use and distribution are the same than zlib :
22
23   This software is provided 'as-is', without any express or implied
24   warranty.  In no event will the authors be held liable for any damages
25   arising from the use of this software.
26
27   Permission is granted to anyone to use this software for any purpose,
28   including commercial applications, and to alter it and redistribute it
29   freely, subject to the following restrictions:
30
31   1. The origin of this software must not be misrepresented; you must not
32      claim that you wrote the original software. If you use this software
33      in a product, an acknowledgment in the product documentation would be
34      appreciated but is not required.
35   2. Altered source versions must be plainly marked as such, and must not be
36      misrepresented as being the original software.
37   3. This notice may not be removed or altered from any source distribution.
38
39
40 */
41 /* for more info about .ZIP format, see 
42       ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
43    PkWare has also a specification at :
44       ftp://ftp.pkware.com/probdesc.zip */
45
46 /* zlib.h -- interface of the 'zlib' general purpose compression library
47   version 1.1.3, July 9th, 1998
48
49   Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
50
51   This software is provided 'as-is', without any express or implied
52   warranty.  In no event will the authors be held liable for any damages
53   arising from the use of this software.
54
55   Permission is granted to anyone to use this software for any purpose,
56   including commercial applications, and to alter it and redistribute it
57   freely, subject to the following restrictions:
58
59   1. The origin of this software must not be misrepresented; you must not
60      claim that you wrote the original software. If you use this software
61      in a product, an acknowledgment in the product documentation would be
62      appreciated but is not required.
63   2. Altered source versions must be plainly marked as such, and must not be
64      misrepresented as being the original software.
65   3. This notice may not be removed or altered from any source distribution.
66
67   Jean-loup Gailly        Mark Adler
68   jloup@gzip.org          madler@alumni.caltech.edu
69
70
71   The data format used by the zlib library is described by RFCs (Request for
72   Comments) 1950 to 1952 in the files ftp://ds.internic.net/rfc/rfc1950.txt
73   (zlib format), rfc1951.txt (deflate format) and rfc1952.txt (gzip format).
74 */
75
76 /* zconf.h -- configuration of the zlib compression library
77  * Copyright (C) 1995-1998 Jean-loup Gailly.
78  * For conditions of distribution and use, see copyright notice in zlib.h 
79  */
80
81 /* @(#) $Id: unzip.c,v 1.2 1999/09/07 20:51:25 zoid Exp $ */
82
83 #ifndef _ZCONF_H
84 #define _ZCONF_H
85
86 /* Maximum value for memLevel in deflateInit2 */
87 #ifndef MAX_MEM_LEVEL
88 #  ifdef MAXSEG_64K
89 #    define MAX_MEM_LEVEL 8
90 #  else
91 #    define MAX_MEM_LEVEL 9
92 #  endif
93 #endif
94
95 /* Maximum value for windowBits in deflateInit2 and inflateInit2.
96  * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
97  * created by gzip. (Files created by minigzip can still be extracted by
98  * gzip.)
99  */
100 #ifndef MAX_WBITS
101 #  define MAX_WBITS   15 /* 32K LZ77 window */
102 #endif
103
104 /* The memory requirements for deflate are (in bytes):
105             (1 << (windowBits+2)) +  (1 << (memLevel+9))
106  that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
107  plus a few kilobytes for small objects. For example, if you want to reduce
108  the default memory requirements from 256K to 128K, compile with
109      make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
110  Of course this will generally degrade compression (there's no free lunch).
111
112    The memory requirements for inflate are (in bytes) 1 << windowBits
113  that is, 32K for windowBits=15 (default value) plus a few kilobytes
114  for small objects.
115 */
116
117                         /* Type declarations */
118
119 #ifndef OF /* function prototypes */
120 #define OF(args)  args
121 #endif
122
123 typedef unsigned char  Byte;  /* 8 bits */
124 typedef unsigned int   uInt;  /* 16 bits or more */
125 typedef unsigned long  uLong; /* 32 bits or more */
126 typedef Byte    *voidp;
127
128 #ifndef SEEK_SET
129 #  define SEEK_SET        0       /* Seek from beginning of file.  */
130 #  define SEEK_CUR        1       /* Seek from current position.  */
131 #  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
132 #endif
133
134 #endif /* _ZCONF_H */
135
136 #define ZLIB_VERSION "1.1.3"
137
138 /* 
139      The 'zlib' compression library provides in-memory compression and
140   decompression functions, including integrity checks of the uncompressed
141   data.  This version of the library supports only one compression method
142   (deflation) but other algorithms will be added later and will have the same
143   stream interface.
144
145      Compression can be done in a single step if the buffers are large
146   enough (for example if an input file is mmap'ed), or can be done by
147   repeated calls of the compression function.  In the latter case, the
148   application must provide more input and/or consume the output
149   (providing more output space) before each call.
150
151      The library also supports reading and writing files in gzip (.gz) format
152   with an interface similar to that of stdio.
153
154      The library does not install any signal handler. The decoder checks
155   the consistency of the compressed data, so the library should never
156   crash even in case of corrupted input.
157 */
158
159 /*
160    The application must update next_in and avail_in when avail_in has
161    dropped to zero. It must update next_out and avail_out when avail_out
162    has dropped to zero. The application must initialize zalloc, zfree and
163    opaque before calling the init function. All other fields are set by the
164    compression library and must not be updated by the application.
165
166    The opaque value provided by the application will be passed as the first
167    parameter for calls of zalloc and zfree. This can be useful for custom
168    memory management. The compression library attaches no meaning to the
169    opaque value.
170
171    zalloc must return Z_NULL if there is not enough memory for the object.
172    If zlib is used in a multi-threaded application, zalloc and zfree must be
173    thread safe.
174
175    On 16-bit systems, the functions zalloc and zfree must be able to allocate
176    exactly 65536 bytes, but will not be required to allocate more than this
177    if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
178    pointers returned by zalloc for objects of exactly 65536 bytes *must*
179    have their offset normalized to zero. The default allocation function
180    provided by this library ensures this (see zutil.c). To reduce memory
181    requirements and avoid any allocation of 64K objects, at the expense of
182    compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
183
184    The fields total_in and total_out can be used for statistics or
185    progress reports. After compression, total_in holds the total size of
186    the uncompressed data and may be saved for use in the decompressor
187    (particularly if the decompressor wants to decompress everything in
188    a single step).
189 */
190
191                         /* constants */
192
193 #define Z_NO_FLUSH      0
194 #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
195 #define Z_SYNC_FLUSH    2
196 #define Z_FULL_FLUSH    3
197 #define Z_FINISH        4
198 /* Allowed flush values; see deflate() below for details */
199
200 #define Z_OK            0
201 #define Z_STREAM_END    1
202 #define Z_NEED_DICT     2
203 #define Z_ERRNO        (-1)
204 #define Z_STREAM_ERROR (-2)
205 #define Z_DATA_ERROR   (-3)
206 #define Z_MEM_ERROR    (-4)
207 #define Z_BUF_ERROR    (-5)
208 #define Z_VERSION_ERROR (-6)
209 /* Return codes for the compression/decompression functions. Negative
210  * values are errors, positive values are used for special but normal events.
211  */
212
213 #define Z_NO_COMPRESSION         0
214 #define Z_BEST_SPEED             1
215 #define Z_BEST_COMPRESSION       9
216 #define Z_DEFAULT_COMPRESSION  (-1)
217 /* compression levels */
218
219 #define Z_FILTERED            1
220 #define Z_HUFFMAN_ONLY        2
221 #define Z_DEFAULT_STRATEGY    0
222 /* compression strategy; see deflateInit2() below for details */
223
224 #define Z_BINARY   0
225 #define Z_ASCII    1
226 #define Z_UNKNOWN  2
227 /* Possible values of the data_type field */
228
229 #define Z_DEFLATED   8
230 /* The deflate compression method (the only one supported in this version) */
231
232 #define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
233
234 #define zlib_version zlibVersion()
235 /* for compatibility with versions < 1.0.2 */
236
237                         /* basic functions */
238
239 const char * zlibVersion OF((void));
240 /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
241    If the first character differs, the library code actually used is
242    not compatible with the zlib.h header file used by the application.
243    This check is automatically made by deflateInit and inflateInit.
244  */
245
246 /* 
247 int deflateInit OF((z_streamp strm, int level));
248
249      Initializes the internal stream state for compression. The fields
250    zalloc, zfree and opaque must be initialized before by the caller.
251    If zalloc and zfree are set to Z_NULL, deflateInit updates them to
252    use default allocation functions.
253
254      The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
255    1 gives best speed, 9 gives best compression, 0 gives no compression at
256    all (the input data is simply copied a block at a time).
257    Z_DEFAULT_COMPRESSION requests a default compromise between speed and
258    compression (currently equivalent to level 6).
259
260      deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
261    enough memory, Z_STREAM_ERROR if level is not a valid compression level,
262    Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
263    with the version assumed by the caller (ZLIB_VERSION).
264    msg is set to null if there is no error message.  deflateInit does not
265    perform any compression: this will be done by deflate().
266 */
267
268
269 int deflate OF((z_streamp strm, int flush));
270 /*
271     deflate compresses as much data as possible, and stops when the input
272   buffer becomes empty or the output buffer becomes full. It may introduce some
273   output latency (reading input without producing any output) except when
274   forced to flush.
275
276     The detailed semantics are as follows. deflate performs one or both of the
277   following actions:
278
279   - Compress more input starting at next_in and update next_in and avail_in
280     accordingly. If not all input can be processed (because there is not
281     enough room in the output buffer), next_in and avail_in are updated and
282     processing will resume at this point for the next call of deflate().
283
284   - Provide more output starting at next_out and update next_out and avail_out
285     accordingly. This action is forced if the parameter flush is non zero.
286     Forcing flush frequently degrades the compression ratio, so this parameter
287     should be set only when necessary (in interactive applications).
288     Some output may be provided even if flush is not set.
289
290   Before the call of deflate(), the application should ensure that at least
291   one of the actions is possible, by providing more input and/or consuming
292   more output, and updating avail_in or avail_out accordingly; avail_out
293   should never be zero before the call. The application can consume the
294   compressed output when it wants, for example when the output buffer is full
295   (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
296   and with zero avail_out, it must be called again after making room in the
297   output buffer because there might be more output pending.
298
299     If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
300   flushed to the output buffer and the output is aligned on a byte boundary, so
301   that the decompressor can get all input data available so far. (In particular
302   avail_in is zero after the call if enough output space has been provided
303   before the call.)  Flushing may degrade compression for some compression
304   algorithms and so it should be used only when necessary.
305
306     If flush is set to Z_FULL_FLUSH, all output is flushed as with
307   Z_SYNC_FLUSH, and the compression state is reset so that decompression can
308   restart from this point if previous compressed data has been damaged or if
309   random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
310   the compression.
311
312     If deflate returns with avail_out == 0, this function must be called again
313   with the same value of the flush parameter and more output space (updated
314   avail_out), until the flush is complete (deflate returns with non-zero
315   avail_out).
316
317     If the parameter flush is set to Z_FINISH, pending input is processed,
318   pending output is flushed and deflate returns with Z_STREAM_END if there
319   was enough output space; if deflate returns with Z_OK, this function must be
320   called again with Z_FINISH and more output space (updated avail_out) but no
321   more input data, until it returns with Z_STREAM_END or an error. After
322   deflate has returned Z_STREAM_END, the only possible operations on the
323   stream are deflateReset or deflateEnd.
324   
325     Z_FINISH can be used immediately after deflateInit if all the compression
326   is to be done in a single step. In this case, avail_out must be at least
327   0.1% larger than avail_in plus 12 bytes.  If deflate does not return
328   Z_STREAM_END, then it must be called again as described above.
329
330     deflate() sets strm->adler to the adler32 checksum of all input read
331   so (that is, total_in bytes).
332
333     deflate() may update data_type if it can make a good guess about
334   the input data type (Z_ASCII or Z_BINARY). In doubt, the data is considered
335   binary. This field is only for information purposes and does not affect
336   the compression algorithm in any manner.
337
338     deflate() returns Z_OK if some progress has been made (more input
339   processed or more output produced), Z_STREAM_END if all input has been
340   consumed and all output has been produced (only when flush is set to
341   Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
342   if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
343   (for example avail_in or avail_out was zero).
344 */
345
346
347 int deflateEnd OF((z_streamp strm));
348 /*
349      All dynamically allocated data structures for this stream are freed.
350    This function discards any unprocessed input and does not flush any
351    pending output.
352
353      deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
354    stream state was inconsistent, Z_DATA_ERROR if the stream was freed
355    prematurely (some input or output was discarded). In the error case,
356    msg may be set but then points to a static string (which must not be
357    deallocated).
358 */
359
360
361 /* 
362 int inflateInit OF((z_streamp strm));
363
364      Initializes the internal stream state for decompression. The fields
365    next_in, avail_in, zalloc, zfree and opaque must be initialized before by
366    the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
367    value depends on the compression method), inflateInit determines the
368    compression method from the zlib header and allocates all data structures
369    accordingly; otherwise the allocation will be deferred to the first call of
370    inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
371    use default allocation functions.
372
373      inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
374    memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
375    version assumed by the caller.  msg is set to null if there is no error
376    message. inflateInit does not perform any decompression apart from reading
377    the zlib header if present: this will be done by inflate().  (So next_in and
378    avail_in may be modified, but next_out and avail_out are unchanged.)
379 */
380
381
382 int inflate OF((z_streamp strm, int flush));
383 /*
384     inflate decompresses as much data as possible, and stops when the input
385   buffer becomes empty or the output buffer becomes full. It may some
386   introduce some output latency (reading input without producing any output)
387   except when forced to flush.
388
389   The detailed semantics are as follows. inflate performs one or both of the
390   following actions:
391
392   - Decompress more input starting at next_in and update next_in and avail_in
393     accordingly. If not all input can be processed (because there is not
394     enough room in the output buffer), next_in is updated and processing
395     will resume at this point for the next call of inflate().
396
397   - Provide more output starting at next_out and update next_out and avail_out
398     accordingly.  inflate() provides as much output as possible, until there
399     is no more input data or no more space in the output buffer (see below
400     about the flush parameter).
401
402   Before the call of inflate(), the application should ensure that at least
403   one of the actions is possible, by providing more input and/or consuming
404   more output, and updating the next_* and avail_* values accordingly.
405   The application can consume the uncompressed output when it wants, for
406   example when the output buffer is full (avail_out == 0), or after each
407   call of inflate(). If inflate returns Z_OK and with zero avail_out, it
408   must be called again after making room in the output buffer because there
409   might be more output pending.
410
411     If the parameter flush is set to Z_SYNC_FLUSH, inflate flushes as much
412   output as possible to the output buffer. The flushing behavior of inflate is
413   not specified for values of the flush parameter other than Z_SYNC_FLUSH
414   and Z_FINISH, but the current implementation actually flushes as much output
415   as possible anyway.
416
417     inflate() should normally be called until it returns Z_STREAM_END or an
418   error. However if all decompression is to be performed in a single step
419   (a single call of inflate), the parameter flush should be set to
420   Z_FINISH. In this case all pending input is processed and all pending
421   output is flushed; avail_out must be large enough to hold all the
422   uncompressed data. (The size of the uncompressed data may have been saved
423   by the compressor for this purpose.) The next operation on this stream must
424   be inflateEnd to deallocate the decompression state. The use of Z_FINISH
425   is never required, but can be used to inform inflate that a faster routine
426   may be used for the single inflate() call.
427
428      If a preset dictionary is needed at this point (see inflateSetDictionary
429   below), inflate sets strm-adler to the adler32 checksum of the
430   dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise 
431   it sets strm->adler to the adler32 checksum of all output produced
432   so (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
433   an error code as described below. At the end of the stream, inflate()
434   checks that its computed adler32 checksum is equal to that saved by the
435   compressor and returns Z_STREAM_END only if the checksum is correct.
436
437     inflate() returns Z_OK if some progress has been made (more input processed
438   or more output produced), Z_STREAM_END if the end of the compressed data has
439   been reached and all uncompressed output has been produced, Z_NEED_DICT if a
440   preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
441   corrupted (input stream not conforming to the zlib format or incorrect
442   adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent
443   (for example if next_in or next_out was NULL), Z_MEM_ERROR if there was not
444   enough memory, Z_BUF_ERROR if no progress is possible or if there was not
445   enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
446   case, the application may then call inflateSync to look for a good
447   compression block.
448 */
449
450
451 int inflateEnd OF((z_streamp strm));
452 /*
453      All dynamically allocated data structures for this stream are freed.
454    This function discards any unprocessed input and does not flush any
455    pending output.
456
457      inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
458    was inconsistent. In the error case, msg may be set but then points to a
459    static string (which must not be deallocated).
460 */
461
462                         /* Advanced functions */
463
464 /*
465     The following functions are needed only in some special applications.
466 */
467
468 /*   
469 int deflateInit2 OF((z_streamp strm,
470                                      int  level,
471                                      int  method,
472                                      int  windowBits,
473                                      int  memLevel,
474                                      int  strategy));
475
476      This is another version of deflateInit with more compression options. The
477    fields next_in, zalloc, zfree and opaque must be initialized before by
478    the caller.
479
480      The method parameter is the compression method. It must be Z_DEFLATED in
481    this version of the library.
482
483      The windowBits parameter is the base two logarithm of the window size
484    (the size of the history buffer).  It should be in the range 8..15 for this
485    version of the library. Larger values of this parameter result in better
486    compression at the expense of memory usage. The default value is 15 if
487    deflateInit is used instead.
488
489      The memLevel parameter specifies how much memory should be allocated
490    for the internal compression state. memLevel=1 uses minimum memory but
491    is slow and reduces compression ratio; memLevel=9 uses maximum memory
492    for optimal speed. The default value is 8. See zconf.h for total memory
493    usage as a function of windowBits and memLevel.
494
495      The strategy parameter is used to tune the compression algorithm. Use the
496    value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
497    filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
498    string match).  Filtered data consists mostly of small values with a
499    somewhat random distribution. In this case, the compression algorithm is
500    tuned to compress them better. The effect of Z_FILTERED is to force more
501    Huffman coding and less string matching; it is somewhat intermediate
502    between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
503    the compression ratio but not the correctness of the compressed output even
504    if it is not set appropriately.
505
506       deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
507    memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
508    method). msg is set to null if there is no error message.  deflateInit2 does
509    not perform any compression: this will be done by deflate().
510 */
511                             
512 int deflateSetDictionary OF((z_streamp strm,
513                                              const Byte *dictionary,
514                                              uInt  dictLength));
515 /*
516      Initializes the compression dictionary from the given byte sequence
517    without producing any compressed output. This function must be called
518    immediately after deflateInit, deflateInit2 or deflateReset, before any
519    call of deflate. The compressor and decompressor must use exactly the same
520    dictionary (see inflateSetDictionary).
521
522      The dictionary should consist of strings (byte sequences) that are likely
523    to be encountered later in the data to be compressed, with the most commonly
524    used strings preferably put towards the end of the dictionary. Using a
525    dictionary is most useful when the data to be compressed is short and can be
526    predicted with good accuracy; the data can then be compressed better than
527    with the default empty dictionary.
528
529      Depending on the size of the compression data structures selected by
530    deflateInit or deflateInit2, a part of the dictionary may in effect be
531    discarded, for example if the dictionary is larger than the window size in
532    deflate or deflate2. Thus the strings most likely to be useful should be
533    put at the end of the dictionary, not at the front.
534
535      Upon return of this function, strm->adler is set to the Adler32 value
536    of the dictionary; the decompressor may later use this value to determine
537    which dictionary has been used by the compressor. (The Adler32 value
538    applies to the whole dictionary even if only a subset of the dictionary is
539    actually used by the compressor.)
540
541      deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
542    parameter is invalid (such as NULL dictionary) or the stream state is
543    inconsistent (for example if deflate has already been called for this stream
544    or if the compression method is bsort). deflateSetDictionary does not
545    perform any compression: this will be done by deflate().
546 */
547
548 int deflateCopy OF((z_streamp dest,
549                                     z_streamp source));
550 /*
551      Sets the destination stream as a complete copy of the source stream.
552
553      This function can be useful when several compression strategies will be
554    tried, for example when there are several ways of pre-processing the input
555    data with a filter. The streams that will be discarded should then be freed
556    by calling deflateEnd.  Note that deflateCopy duplicates the internal
557    compression state which can be quite large, so this strategy is slow and
558    can consume lots of memory.
559
560      deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
561    enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
562    (such as zalloc being NULL). msg is left unchanged in both source and
563    destination.
564 */
565
566 int deflateReset OF((z_streamp strm));
567 /*
568      This function is equivalent to deflateEnd followed by deflateInit,
569    but does not free and reallocate all the internal compression state.
570    The stream will keep the same compression level and any other attributes
571    that may have been set by deflateInit2.
572
573       deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
574    stream state was inconsistent (such as zalloc or state being NULL).
575 */
576
577 int deflateParams OF((z_streamp strm,
578                                       int level,
579                                       int strategy));
580 /*
581      Dynamically update the compression level and compression strategy.  The
582    interpretation of level and strategy is as in deflateInit2.  This can be
583    used to switch between compression and straight copy of the input data, or
584    to switch to a different kind of input data requiring a different
585    strategy. If the compression level is changed, the input available so far
586    is compressed with the old level (and may be flushed); the new level will
587    take effect only at the next call of deflate().
588
589      Before the call of deflateParams, the stream state must be set as for
590    a call of deflate(), since the currently available input may have to
591    be compressed and flushed. In particular, strm->avail_out must be non-zero.
592
593      deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
594    stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
595    if strm->avail_out was zero.
596 */
597
598 /*   
599 int inflateInit2 OF((z_streamp strm,
600                                      int  windowBits));
601
602      This is another version of inflateInit with an extra parameter. The
603    fields next_in, avail_in, zalloc, zfree and opaque must be initialized
604    before by the caller.
605
606      The windowBits parameter is the base two logarithm of the maximum window
607    size (the size of the history buffer).  It should be in the range 8..15 for
608    this version of the library. The default value is 15 if inflateInit is used
609    instead. If a compressed stream with a larger window size is given as
610    input, inflate() will return with the error code Z_DATA_ERROR instead of
611    trying to allocate a larger window.
612
613       inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
614    memory, Z_STREAM_ERROR if a parameter is invalid (such as a negative
615    memLevel). msg is set to null if there is no error message.  inflateInit2
616    does not perform any decompression apart from reading the zlib header if
617    present: this will be done by inflate(). (So next_in and avail_in may be
618    modified, but next_out and avail_out are unchanged.)
619 */
620
621 int inflateSetDictionary OF((z_streamp strm,
622                                              const Byte *dictionary,
623                                              uInt  dictLength));
624 /*
625      Initializes the decompression dictionary from the given uncompressed byte
626    sequence. This function must be called immediately after a call of inflate
627    if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
628    can be determined from the Adler32 value returned by this call of
629    inflate. The compressor and decompressor must use exactly the same
630    dictionary (see deflateSetDictionary).
631
632      inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
633    parameter is invalid (such as NULL dictionary) or the stream state is
634    inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
635    expected one (incorrect Adler32 value). inflateSetDictionary does not
636    perform any decompression: this will be done by subsequent calls of
637    inflate().
638 */
639
640 int inflateSync OF((z_streamp strm));
641 /* 
642     Skips invalid compressed data until a full flush point (see above the
643   description of deflate with Z_FULL_FLUSH) can be found, or until all
644   available input is skipped. No output is provided.
645
646     inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
647   if no more input was provided, Z_DATA_ERROR if no flush point has been found,
648   or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
649   case, the application may save the current current value of total_in which
650   indicates where valid compressed data was found. In the error case, the
651   application may repeatedly call inflateSync, providing more input each time,
652   until success or end of the input data.
653 */
654
655 int inflateReset OF((z_streamp strm));
656 /*
657      This function is equivalent to inflateEnd followed by inflateInit,
658    but does not free and reallocate all the internal decompression state.
659    The stream will keep attributes that may have been set by inflateInit2.
660
661       inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
662    stream state was inconsistent (such as zalloc or state being NULL).
663 */
664
665
666                         /* utility functions */
667
668 /*
669      The following utility functions are implemented on top of the
670    basic stream-oriented functions. To simplify the interface, some
671    default options are assumed (compression level and memory usage,
672    standard memory allocation functions). The source code of these
673    utility functions can easily be modified if you need special options.
674 */
675
676 int compress OF((Byte *dest,   uLong *destLen,
677                                  const Byte *source, uLong sourceLen));
678 /*
679      Compresses the source buffer into the destination buffer.  sourceLen is
680    the byte length of the source buffer. Upon entry, destLen is the total
681    size of the destination buffer, which must be at least 0.1% larger than
682    sourceLen plus 12 bytes. Upon exit, destLen is the actual size of the
683    compressed buffer.
684      This function can be used to compress a whole file at once if the
685    input file is mmap'ed.
686      compress returns Z_OK if success, Z_MEM_ERROR if there was not
687    enough memory, Z_BUF_ERROR if there was not enough room in the output
688    buffer.
689 */
690
691 int compress2 OF((Byte *dest,   uLong *destLen,
692                                   const Byte *source, uLong sourceLen,
693                                   int level));
694 /*
695      Compresses the source buffer into the destination buffer. The level
696    parameter has the same meaning as in deflateInit.  sourceLen is the byte
697    length of the source buffer. Upon entry, destLen is the total size of the
698    destination buffer, which must be at least 0.1% larger than sourceLen plus
699    12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
700
701      compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
702    memory, Z_BUF_ERROR if there was not enough room in the output buffer,
703    Z_STREAM_ERROR if the level parameter is invalid.
704 */
705
706 int uncompress OF((Byte *dest,   uLong *destLen,
707                                    const Byte *source, uLong sourceLen));
708 /*
709      Decompresses the source buffer into the destination buffer.  sourceLen is
710    the byte length of the source buffer. Upon entry, destLen is the total
711    size of the destination buffer, which must be large enough to hold the
712    entire uncompressed data. (The size of the uncompressed data must have
713    been saved previously by the compressor and transmitted to the decompressor
714    by some mechanism outside the scope of this compression library.)
715    Upon exit, destLen is the actual size of the compressed buffer.
716      This function can be used to decompress a whole file at once if the
717    input file is mmap'ed.
718
719      uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
720    enough memory, Z_BUF_ERROR if there was not enough room in the output
721    buffer, or Z_DATA_ERROR if the input data was corrupted.
722 */
723
724
725 typedef voidp gzFile;
726
727 gzFile gzopen  OF((const char *path, const char *mode));
728 /*
729      Opens a gzip (.gz) file for reading or writing. The mode parameter
730    is as in fopen ("rb" or "wb") but can also include a compression level
731    ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
732    Huffman only compression as in "wb1h". (See the description
733    of deflateInit2 for more information about the strategy parameter.)
734
735      gzopen can be used to read a file which is not in gzip format; in this
736    case gzread will directly read from the file without decompression.
737
738      gzopen returns NULL if the file could not be opened or if there was
739    insufficient memory to allocate the (de)compression state; errno
740    can be checked to distinguish the two cases (if errno is zero, the
741    zlib error is Z_MEM_ERROR).  */
742
743 gzFile gzdopen  OF((int fd, const char *mode));
744 /*
745      gzdopen() associates a gzFile with the file descriptor fd.  File
746    descriptors are obtained from calls like open, dup, creat, pipe or
747    fileno (in the file has been previously opened with fopen).
748    The mode parameter is as in gzopen.
749      The next call of gzclose on the returned gzFile will also close the
750    file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
751    descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
752      gzdopen returns NULL if there was insufficient memory to allocate
753    the (de)compression state.
754 */
755
756 int gzsetparams OF((gzFile file, int level, int strategy));
757 /*
758      Dynamically update the compression level or strategy. See the description
759    of deflateInit2 for the meaning of these parameters.
760      gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
761    opened for writing.
762 */
763
764 int    gzread  OF((gzFile file, voidp buf, unsigned len));
765 /*
766      Reads the given number of uncompressed bytes from the compressed file.
767    If the input file was not in gzip format, gzread copies the given number
768    of bytes into the buffer.
769      gzread returns the number of uncompressed bytes actually read (0 for
770    end of file, -1 for error). */
771
772 int    gzwrite OF((gzFile file, 
773                                    const voidp buf, unsigned len));
774 /*
775      Writes the given number of uncompressed bytes into the compressed file.
776    gzwrite returns the number of uncompressed bytes actually written
777    (0 in case of error).
778 */
779
780 int    gzprintf OF((gzFile file, const char *format, ...));
781 /*
782      Converts, formats, and writes the args to the compressed file under
783    control of the format string, as in fprintf. gzprintf returns the number of
784    uncompressed bytes actually written (0 in case of error).
785 */
786
787 int gzputs OF((gzFile file, const char *s));
788 /*
789       Writes the given null-terminated string to the compressed file, excluding
790    the terminating null character.
791       gzputs returns the number of characters written, or -1 in case of error.
792 */
793
794 char * gzgets OF((gzFile file, char *buf, int len));
795 /*
796       Reads bytes from the compressed file until len-1 characters are read, or
797    a newline character is read and transferred to buf, or an end-of-file
798    condition is encountered.  The string is then terminated with a null
799    character.
800       gzgets returns buf, or Z_NULL in case of error.
801 */
802
803 int    gzputc OF((gzFile file, int c));
804 /*
805       Writes c, converted to an unsigned char, into the compressed file.
806    gzputc returns the value that was written, or -1 in case of error.
807 */
808
809 int    gzgetc OF((gzFile file));
810 /*
811       Reads one byte from the compressed file. gzgetc returns this byte
812    or -1 in case of end of file or error.
813 */
814
815 int    gzflush OF((gzFile file, int flush));
816 /*
817      Flushes all pending output into the compressed file. The parameter
818    flush is as in the deflate() function. The return value is the zlib
819    error number (see function gzerror below). gzflush returns Z_OK if
820    the flush parameter is Z_FINISH and all output could be flushed.
821      gzflush should be called only when strictly necessary because it can
822    degrade compression.
823 */
824
825 long gzseek OF((gzFile file,
826                                       long offset, int whence));
827 /* 
828       Sets the starting position for the next gzread or gzwrite on the
829    given compressed file. The offset represents a number of bytes in the
830    uncompressed data stream. The whence parameter is defined as in lseek(2);
831    the value SEEK_END is not supported.
832      If the file is opened for reading, this function is emulated but can be
833    extremely slow. If the file is opened for writing, only forward seeks are
834    supported; gzseek then compresses a sequence of zeroes up to the new
835    starting position.
836
837       gzseek returns the resulting offset location as measured in bytes from
838    the beginning of the uncompressed stream, or -1 in case of error, in
839    particular if the file is opened for writing and the new starting position
840    would be before the current position.
841 */
842
843 int    gzrewind OF((gzFile file));
844 /*
845      Rewinds the given file. This function is supported only for reading.
846
847    gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
848 */
849
850 long    gztell OF((gzFile file));
851 /*
852      Returns the starting position for the next gzread or gzwrite on the
853    given compressed file. This position represents a number of bytes in the
854    uncompressed data stream.
855
856    gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
857 */
858
859 int gzeof OF((gzFile file));
860 /*
861      Returns 1 when EOF has previously been detected reading the given
862    input stream, otherwise zero.
863 */
864
865 int    gzclose OF((gzFile file));
866 /*
867      Flushes all pending output if necessary, closes the compressed file
868    and deallocates all the (de)compression state. The return value is the zlib
869    error number (see function gzerror below).
870 */
871
872 const char * gzerror OF((gzFile file, int *errnum));
873 /*
874      Returns the error message for the last error which occurred on the
875    given compressed file. errnum is set to zlib error number. If an
876    error occurred in the file system and not in the compression library,
877    errnum is set to Z_ERRNO and the application may consult errno
878    to get the exact error code.
879 */
880
881                         /* checksum functions */
882
883 /*
884      These functions are not related to compression but are exported
885    anyway because they might be useful in applications using the
886    compression library.
887 */
888
889 uLong adler32 OF((uLong adler, const Byte *buf, uInt len));
890
891 /*
892      Update a running Adler-32 checksum with the bytes buf[0..len-1] and
893    return the updated checksum. If buf is NULL, this function returns
894    the required initial value for the checksum.
895    An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
896    much faster. Usage example:
897
898      uLong adler = adler32(0L, Z_NULL, 0);
899
900      while (read_buffer(buffer, length) != EOF) {
901        adler = adler32(adler, buffer, length);
902      }
903      if (adler != original_adler) error();
904 */
905
906 uLong crc32   OF((uLong crc, const Byte *buf, uInt len));
907 /*
908      Update a running crc with the bytes buf[0..len-1] and return the updated
909    crc. If buf is NULL, this function returns the required initial value
910    for the crc. Pre- and post-conditioning (one's complement) is performed
911    within this function so it shouldn't be done by the application.
912    Usage example:
913
914      uLong crc = crc32(0L, Z_NULL, 0);
915
916      while (read_buffer(buffer, length) != EOF) {
917        crc = crc32(crc, buffer, length);
918      }
919      if (crc != original_crc) error();
920 */
921
922
923                         /* various hacks, don't look :) */
924
925 /* deflateInit and inflateInit are macros to allow checking the zlib version
926  * and the compiler's view of z_stream:
927  */
928 int deflateInit_ OF((z_streamp strm, int level,
929                                      const char *version, int stream_size));
930 int inflateInit_ OF((z_streamp strm,
931                                      const char *version, int stream_size));
932 int deflateInit2_ OF((z_streamp strm, int  level, int  method,
933                                       int windowBits, int memLevel,
934                                       int strategy, const char *version,
935                                       int stream_size));
936 int inflateInit2_ OF((z_streamp strm, int  windowBits,
937                                       const char *version, int stream_size));
938 #define deflateInit(strm, level) \
939         deflateInit_((strm), (level),       ZLIB_VERSION, sizeof(z_stream))
940 #define inflateInit(strm) \
941         inflateInit_((strm),                ZLIB_VERSION, sizeof(z_stream))
942 #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
943         deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
944                       (strategy),           ZLIB_VERSION, sizeof(z_stream))
945 #define inflateInit2(strm, windowBits) \
946         inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
947
948
949 const char   * zError           OF((int err));
950 int            inflateSyncPoint OF((z_streamp z));
951 const uLong * get_crc_table    OF((void));
952
953 typedef unsigned char  uch;
954 typedef unsigned short ush;
955 typedef unsigned long  ulg;
956
957 extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */
958 /* (size given to avoid silly warnings with Visual C++) */
959
960 #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
961
962 #define ERR_RETURN(strm,err) \
963   return (strm->msg = (char*)ERR_MSG(err), (err))
964 /* To be used only when the state is known to be valid */
965
966         /* common constants */
967
968 #ifndef DEF_WBITS
969 #  define DEF_WBITS MAX_WBITS
970 #endif
971 /* default windowBits for decompression. MAX_WBITS is for compression only */
972
973 #if MAX_MEM_LEVEL >= 8
974 #  define DEF_MEM_LEVEL 8
975 #else
976 #  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
977 #endif
978 /* default memLevel */
979
980 #define STORED_BLOCK 0
981 #define STATIC_TREES 1
982 #define DYN_TREES    2
983 /* The three kinds of block type */
984
985 #define MIN_MATCH  3
986 #define MAX_MATCH  258
987 /* The minimum and maximum match lengths */
988
989 #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
990
991         /* target dependencies */
992
993         /* Common defaults */
994
995 #ifndef OS_CODE
996 #  define OS_CODE  0x03  /* assume Unix */
997 #endif
998
999 #ifndef F_OPEN
1000 #  define F_OPEN(name, mode) fopen((name), (mode))
1001 #endif
1002
1003          /* functions */
1004
1005 #ifdef HAVE_STRERROR
1006    extern char *strerror OF((int));
1007 #  define zstrerror(errnum) strerror(errnum)
1008 #else
1009 #  define zstrerror(errnum) ""
1010 #endif
1011
1012 #define zmemcpy memcpy
1013 #define zmemcmp memcmp
1014 #define zmemzero(dest, len) memset(dest, 0, len)
1015
1016 /* Diagnostic functions */
1017 #ifdef _ZIP_DEBUG_
1018    int z_verbose = 0;
1019 #  define Assert(cond,msg) assert(cond);
1020    //{if(!(cond)) Sys_Error(msg);}
1021 #  define Trace(x) {if (z_verbose>=0) Sys_Error x ;}
1022 #  define Tracev(x) {if (z_verbose>0) Sys_Error x ;}
1023 #  define Tracevv(x) {if (z_verbose>1) Sys_Error x ;}
1024 #  define Tracec(c,x) {if (z_verbose>0 && (c)) Sys_Error x ;}
1025 #  define Tracecv(c,x) {if (z_verbose>1 && (c)) Sys_Error x ;}
1026 #else
1027 #  define Assert(cond,msg)
1028 #  define Trace(x)
1029 #  define Tracev(x)
1030 #  define Tracevv(x)
1031 #  define Tracec(c,x)
1032 #  define Tracecv(c,x)
1033 #endif
1034
1035
1036 typedef uLong (*check_func) OF((uLong check, const Byte *buf, uInt len));
1037 voidp zcalloc OF((voidp opaque, unsigned items, unsigned size));
1038 void   zcfree  OF((voidp opaque, voidp ptr));
1039
1040 #define ZALLOC(strm, items, size) \
1041            (*((strm)->zalloc))((strm)->opaque, (items), (size))
1042 #define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidp)(addr))
1043 #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
1044
1045
1046 #if !defined(unix) && !defined(CASESENSITIVITYDEFAULT_YES) && \
1047                       !defined(CASESENSITIVITYDEFAULT_NO)
1048 #define CASESENSITIVITYDEFAULT_NO
1049 #endif
1050
1051
1052 #ifndef UNZ_BUFSIZE
1053 #define UNZ_BUFSIZE (65536)
1054 #endif
1055
1056 #ifndef UNZ_MAXFILENAMEINZIP
1057 #define UNZ_MAXFILENAMEINZIP (256)
1058 #endif
1059
1060 #ifndef ALLOC
1061 # define ALLOC(size) (Mem_Alloc(size))
1062 #endif
1063 #ifndef TRYFREE
1064 # define TRYFREE(p) {if (p) Mem_Free(p);}
1065 #endif
1066
1067 #define SIZECENTRALDIRITEM (0x2e)
1068 #define SIZEZIPLOCALHEADER (0x1e)
1069
1070
1071
1072 /* ===========================================================================
1073      Read a byte from a gz_stream; update next_in and avail_in. Return EOF
1074    for end of file.
1075    IN assertion: the stream s has been sucessfully opened for reading.
1076 */
1077
1078 /*
1079 static int unzlocal_getByte(FILE *fin,int *pi)
1080 {
1081     unsigned char c;
1082         int err = fread(&c, 1, 1, fin);
1083     if (err==1)
1084     {
1085         *pi = (int)c;
1086         return UNZ_OK;
1087     }
1088     else
1089     {
1090         if (ferror(fin)) 
1091             return UNZ_ERRNO;
1092         else
1093             return UNZ_EOF;
1094     }
1095 }
1096 */
1097
1098 /* ===========================================================================
1099    Reads a long in LSB order from the given gz_stream. Sets 
1100 */
1101 static int unzlocal_getShort (FILE* fin, uLong *pX)
1102 {
1103         short   v;
1104
1105         fread( &v, sizeof(v), 1, fin );
1106
1107         *pX = LittleShort( v);
1108         return UNZ_OK;
1109
1110 /*
1111     uLong x ;
1112     int i;
1113     int err;
1114
1115     err = unzlocal_getByte(fin,&i);
1116     x = (uLong)i;
1117     
1118     if (err==UNZ_OK)
1119         err = unzlocal_getByte(fin,&i);
1120     x += ((uLong)i)<<8;
1121    
1122     if (err==UNZ_OK)
1123         *pX = x;
1124     else
1125         *pX = 0;
1126     return err;
1127 */
1128 }
1129
1130 static int unzlocal_getLong (FILE *fin, uLong *pX)
1131 {
1132         int             v;
1133
1134         fread( &v, sizeof(v), 1, fin );
1135
1136         *pX = LittleLong( v);
1137         return UNZ_OK;
1138
1139 /*
1140     uLong x ;
1141     int i;
1142     int err;
1143
1144     err = unzlocal_getByte(fin,&i);
1145     x = (uLong)i;
1146     
1147     if (err==UNZ_OK)
1148         err = unzlocal_getByte(fin,&i);
1149     x += ((uLong)i)<<8;
1150
1151     if (err==UNZ_OK)
1152         err = unzlocal_getByte(fin,&i);
1153     x += ((uLong)i)<<16;
1154
1155     if (err==UNZ_OK)
1156         err = unzlocal_getByte(fin,&i);
1157     x += ((uLong)i)<<24;
1158    
1159     if (err==UNZ_OK)
1160         *pX = x;
1161     else
1162         *pX = 0;
1163     return err;
1164 */
1165 }
1166
1167
1168 /* My own strcmpi / strcasecmp */
1169 static int strcmpcasenosensitive_internal (const char* fileName1,const char* fileName2)
1170 {
1171         for (;;)
1172         {
1173                 char c1=*(fileName1++);
1174                 char c2=*(fileName2++);
1175                 if ((c1>='a') && (c1<='z'))
1176                         c1 -= 0x20;
1177                 if ((c2>='a') && (c2<='z'))
1178                         c2 -= 0x20;
1179                 if (c1=='\0')
1180                         return ((c2=='\0') ? 0 : -1);
1181                 if (c2=='\0')
1182                         return 1;
1183                 if (c1<c2)
1184                         return -1;
1185                 if (c1>c2)
1186                         return 1;
1187         }
1188 }
1189
1190
1191 #ifdef  CASESENSITIVITYDEFAULT_NO
1192 #define CASESENSITIVITYDEFAULTVALUE 2
1193 #else
1194 #define CASESENSITIVITYDEFAULTVALUE 1
1195 #endif
1196
1197 #ifndef STRCMPCASENOSENTIVEFUNCTION
1198 #define STRCMPCASENOSENTIVEFUNCTION strcmpcasenosensitive_internal
1199 #endif
1200
1201 /* 
1202    Compare two filename (fileName1,fileName2).
1203    If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
1204    If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
1205                                                                 or strcasecmp)
1206    If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
1207         (like 1 on Unix, 2 on Windows)
1208
1209 */
1210 extern int unzStringFileNameCompare (const char* fileName1,const char* fileName2,int iCaseSensitivity)
1211 {
1212         if (iCaseSensitivity==0)
1213                 iCaseSensitivity=CASESENSITIVITYDEFAULTVALUE;
1214
1215         if (iCaseSensitivity==1)
1216                 return strcmp(fileName1,fileName2);
1217
1218         return STRCMPCASENOSENTIVEFUNCTION(fileName1,fileName2);
1219
1220
1221 #define BUFREADCOMMENT (0x400)
1222
1223 /*
1224   Locate the Central directory of a zipfile (at the end, just before
1225     the global comment)
1226 */
1227 static uLong unzlocal_SearchCentralDir(FILE *fin)
1228 {
1229         unsigned char* buf;
1230         uLong uSizeFile;
1231         uLong uBackRead;
1232         uLong uMaxBack=0xffff; /* maximum size of global comment */
1233         uLong uPosFound=0;
1234         
1235         if (fseek(fin,0,SEEK_END) != 0)
1236                 return 0;
1237
1238
1239         uSizeFile = ftell( fin );
1240         
1241         if (uMaxBack>uSizeFile)
1242                 uMaxBack = uSizeFile;
1243
1244         buf = (unsigned char*)ALLOC(BUFREADCOMMENT+4);
1245         if (buf==NULL)
1246                 return 0;
1247
1248         uBackRead = 4;
1249         while (uBackRead<uMaxBack)
1250         {
1251                 uLong uReadSize,uReadPos ;
1252                 int i;
1253                 if (uBackRead+BUFREADCOMMENT>uMaxBack) 
1254                         uBackRead = uMaxBack;
1255                 else
1256                         uBackRead+=BUFREADCOMMENT;
1257                 uReadPos = uSizeFile-uBackRead ;
1258                 
1259                 uReadSize = ((BUFREADCOMMENT+4) < (uSizeFile-uReadPos)) ? 
1260                      (BUFREADCOMMENT+4) : (uSizeFile-uReadPos);
1261                 if (fseek(fin,uReadPos,SEEK_SET)!=0)
1262                         break;
1263
1264                 if (fread(buf,(uInt)uReadSize,1,fin)!=1)
1265                         break;
1266
1267                 for (i=(int)uReadSize-3; (i--)>0;)
1268                         if (((*(buf+i))==0x50) && ((*(buf+i+1))==0x4b) && 
1269                                 ((*(buf+i+2))==0x05) && ((*(buf+i+3))==0x06))
1270                         {
1271                                 uPosFound = uReadPos+i;
1272                                 break;
1273                         }
1274
1275                 if (uPosFound!=0)
1276                         break;
1277         }
1278         TRYFREE(buf);
1279         return uPosFound;
1280 }
1281
1282 extern unzFile unzReOpen (const char* path, unzFile file)
1283 {
1284         unz_s *s;
1285         FILE * fin;
1286
1287     fin=fopen(path,"rb");
1288         if (fin==NULL)
1289                 return NULL;
1290
1291         s=(unz_s*)ALLOC(sizeof(unz_s));
1292         memcpy(s, (unz_s*)file, sizeof(unz_s));
1293
1294         s->file = fin;
1295     s->pfile_in_zip_read = NULL;
1296
1297         return (unzFile)s;      
1298 }
1299
1300 /*
1301   Open a Zip file. path contain the full pathname (by example,
1302      on a Windows NT computer "c:\\test\\zlib109.zip" or on an Unix computer
1303          "zlib/zlib109.zip".
1304          If the zipfile cannot be opened (file don't exist or in not valid), the
1305            return value is NULL.
1306      Else, the return value is a unzFile Handle, usable with other function
1307            of this unzip package.
1308 */
1309 extern unzFile unzOpen (const char* path)
1310 {
1311         unz_s us;
1312         unz_s *s;
1313         uLong central_pos,uL;
1314         FILE * fin ;
1315
1316         uLong number_disk;          /* number of the current dist, used for 
1317                                                                    spaning ZIP, unsupported, always 0*/
1318         uLong number_disk_with_CD;  /* number the the disk with central dir, used
1319                                                                    for spaning ZIP, unsupported, always 0*/
1320         uLong number_entry_CD;      /* total number of entries in
1321                                        the central dir 
1322                                        (same than number_entry on nospan) */
1323
1324         int err=UNZ_OK;
1325
1326     fin=fopen(path,"rb");
1327         if (fin==NULL)
1328                 return NULL;
1329
1330         central_pos = unzlocal_SearchCentralDir(fin);
1331         if (central_pos==0)
1332                 err=UNZ_ERRNO;
1333
1334         if (fseek(fin,central_pos,SEEK_SET)!=0)
1335                 err=UNZ_ERRNO;
1336
1337         /* the signature, already checked */
1338         if (unzlocal_getLong(fin,&uL)!=UNZ_OK)
1339                 err=UNZ_ERRNO;
1340
1341         /* number of this disk */
1342         if (unzlocal_getShort(fin,&number_disk)!=UNZ_OK)
1343                 err=UNZ_ERRNO;
1344
1345         /* number of the disk with the start of the central directory */
1346         if (unzlocal_getShort(fin,&number_disk_with_CD)!=UNZ_OK)
1347                 err=UNZ_ERRNO;
1348
1349         /* total number of entries in the central dir on this disk */
1350         if (unzlocal_getShort(fin,&us.gi.number_entry)!=UNZ_OK)
1351                 err=UNZ_ERRNO;
1352
1353         /* total number of entries in the central dir */
1354         if (unzlocal_getShort(fin,&number_entry_CD)!=UNZ_OK)
1355                 err=UNZ_ERRNO;
1356
1357         if ((number_entry_CD!=us.gi.number_entry) ||
1358                 (number_disk_with_CD!=0) ||
1359                 (number_disk!=0))
1360                 err=UNZ_BADZIPFILE;
1361
1362         /* size of the central directory */
1363         if (unzlocal_getLong(fin,&us.size_central_dir)!=UNZ_OK)
1364                 err=UNZ_ERRNO;
1365
1366         /* offset of start of central directory with respect to the 
1367               starting disk number */
1368         if (unzlocal_getLong(fin,&us.offset_central_dir)!=UNZ_OK)
1369                 err=UNZ_ERRNO;
1370
1371         /* zipfile comment length */
1372         if (unzlocal_getShort(fin,&us.gi.size_comment)!=UNZ_OK)
1373                 err=UNZ_ERRNO;
1374
1375         if ((central_pos<us.offset_central_dir+us.size_central_dir) && 
1376                 (err==UNZ_OK))
1377                 err=UNZ_BADZIPFILE;
1378
1379         if (err!=UNZ_OK)
1380         {
1381                 fclose(fin);
1382                 return NULL;
1383         }
1384
1385         us.file=fin;
1386         us.byte_before_the_zipfile = central_pos -
1387                                     (us.offset_central_dir+us.size_central_dir);
1388         us.central_pos = central_pos;
1389     us.pfile_in_zip_read = NULL;
1390         
1391
1392         s=(unz_s*)ALLOC(sizeof(unz_s));
1393         *s=us;
1394 //      unzGoToFirstFile((unzFile)s);   
1395         return (unzFile)s;      
1396 }
1397
1398
1399 /*
1400   Close a ZipFile opened with unzipOpen.
1401   If there is files inside the .Zip opened with unzipOpenCurrentFile (see later),
1402     these files MUST be closed with unzipCloseCurrentFile before call unzipClose.
1403   return UNZ_OK if there is no problem. */
1404 extern int unzClose (unzFile file)
1405 {
1406         unz_s* s;
1407         if (file==NULL)
1408                 return UNZ_PARAMERROR;
1409         s=(unz_s*)file;
1410
1411     if (s->pfile_in_zip_read!=NULL)
1412         unzCloseCurrentFile(file);
1413
1414         fclose(s->file);
1415         TRYFREE(s);
1416         return UNZ_OK;
1417 }
1418
1419
1420 /*
1421   Write info about the ZipFile in the *pglobal_info structure.
1422   No preparation of the structure is needed
1423   return UNZ_OK if there is no problem. */
1424 extern int unzGetGlobalInfo (unzFile file,unz_global_info *pglobal_info)
1425 {
1426         unz_s* s;
1427         if (file==NULL)
1428                 return UNZ_PARAMERROR;
1429         s=(unz_s*)file;
1430         *pglobal_info=s->gi;
1431         return UNZ_OK;
1432 }
1433
1434
1435 /*
1436    Translate date/time from Dos format to tm_unz (readable more easilty)
1437 */
1438 static void unzlocal_DosDateToTmuDate (uLong ulDosDate, tm_unz* ptm)
1439 {
1440     uLong uDate;
1441     uDate = (uLong)(ulDosDate>>16);
1442     ptm->tm_mday = (uInt)(uDate&0x1f) ;
1443     ptm->tm_mon =  (uInt)((((uDate)&0x1E0)/0x20)-1) ;
1444     ptm->tm_year = (uInt)(((uDate&0x0FE00)/0x0200)+1980) ;
1445
1446     ptm->tm_hour = (uInt) ((ulDosDate &0xF800)/0x800);
1447     ptm->tm_min =  (uInt) ((ulDosDate&0x7E0)/0x20) ;
1448     ptm->tm_sec =  (uInt) (2*(ulDosDate&0x1f)) ;
1449 }
1450
1451 /*
1452   Get Info about the current file in the zipfile, with internal only info
1453 */
1454 static int unzlocal_GetCurrentFileInfoInternal (unzFile file,
1455                                                   unz_file_info *pfile_info,
1456                                                   unz_file_info_internal 
1457                                                   *pfile_info_internal,
1458                                                   char *szFileName,
1459                                                                                                   uLong fileNameBufferSize,
1460                                                   void *extraField,
1461                                                                                                   uLong extraFieldBufferSize,
1462                                                   char *szComment,
1463                                                                                                   uLong commentBufferSize)
1464 {
1465         unz_s* s;
1466         unz_file_info file_info;
1467         unz_file_info_internal file_info_internal;
1468         int err=UNZ_OK;
1469         uLong uMagic;
1470         long lSeek=0;
1471
1472         if (file==NULL)
1473                 return UNZ_PARAMERROR;
1474         s=(unz_s*)file;
1475         if (fseek(s->file,s->pos_in_central_dir+s->byte_before_the_zipfile,SEEK_SET)!=0)
1476                 err=UNZ_ERRNO;
1477
1478
1479         /* we check the magic */
1480         if (err==UNZ_OK)
1481                 if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
1482                         err=UNZ_ERRNO;
1483                 else if (uMagic!=0x02014b50)
1484                         err=UNZ_BADZIPFILE;
1485
1486         if (unzlocal_getShort(s->file,&file_info.version) != UNZ_OK)
1487                 err=UNZ_ERRNO;
1488
1489         if (unzlocal_getShort(s->file,&file_info.version_needed) != UNZ_OK)
1490                 err=UNZ_ERRNO;
1491
1492         if (unzlocal_getShort(s->file,&file_info.flag) != UNZ_OK)
1493                 err=UNZ_ERRNO;
1494
1495         if (unzlocal_getShort(s->file,&file_info.compression_method) != UNZ_OK)
1496                 err=UNZ_ERRNO;
1497
1498         if (unzlocal_getLong(s->file,&file_info.dosDate) != UNZ_OK)
1499                 err=UNZ_ERRNO;
1500
1501     unzlocal_DosDateToTmuDate(file_info.dosDate,&file_info.tmu_date);
1502
1503         if (unzlocal_getLong(s->file,&file_info.crc) != UNZ_OK)
1504                 err=UNZ_ERRNO;
1505
1506         if (unzlocal_getLong(s->file,&file_info.compressed_size) != UNZ_OK)
1507                 err=UNZ_ERRNO;
1508
1509         if (unzlocal_getLong(s->file,&file_info.uncompressed_size) != UNZ_OK)
1510                 err=UNZ_ERRNO;
1511
1512         if (unzlocal_getShort(s->file,&file_info.size_filename) != UNZ_OK)
1513                 err=UNZ_ERRNO;
1514
1515         if (unzlocal_getShort(s->file,&file_info.size_file_extra) != UNZ_OK)
1516                 err=UNZ_ERRNO;
1517
1518         if (unzlocal_getShort(s->file,&file_info.size_file_comment) != UNZ_OK)
1519                 err=UNZ_ERRNO;
1520
1521         if (unzlocal_getShort(s->file,&file_info.disk_num_start) != UNZ_OK)
1522                 err=UNZ_ERRNO;
1523
1524         if (unzlocal_getShort(s->file,&file_info.internal_fa) != UNZ_OK)
1525                 err=UNZ_ERRNO;
1526
1527         if (unzlocal_getLong(s->file,&file_info.external_fa) != UNZ_OK)
1528                 err=UNZ_ERRNO;
1529
1530         if (unzlocal_getLong(s->file,&file_info_internal.offset_curfile) != UNZ_OK)
1531                 err=UNZ_ERRNO;
1532
1533         lSeek+=file_info.size_filename;
1534         if ((err==UNZ_OK) && (szFileName!=NULL))
1535         {
1536                 uLong uSizeRead ;
1537                 if (file_info.size_filename<fileNameBufferSize)
1538                 {
1539                         *(szFileName+file_info.size_filename)='\0';
1540                         uSizeRead = file_info.size_filename;
1541                 }
1542                 else
1543                         uSizeRead = fileNameBufferSize;
1544
1545                 if ((file_info.size_filename>0) && (fileNameBufferSize>0))
1546                         if (fread(szFileName,(uInt)uSizeRead,1,s->file)!=1)
1547                                 err=UNZ_ERRNO;
1548                 lSeek -= uSizeRead;
1549         }
1550
1551         
1552         if ((err==UNZ_OK) && (extraField!=NULL))
1553         {
1554                 uLong uSizeRead ;
1555                 if (file_info.size_file_extra<extraFieldBufferSize)
1556                         uSizeRead = file_info.size_file_extra;
1557                 else
1558                         uSizeRead = extraFieldBufferSize;
1559
1560                 if (lSeek!=0)
1561                         if (fseek(s->file,lSeek,SEEK_CUR)==0)
1562                                 lSeek=0;
1563                         else
1564                                 err=UNZ_ERRNO;
1565                 if ((file_info.size_file_extra>0) && (extraFieldBufferSize>0))
1566                         if (fread(extraField,(uInt)uSizeRead,1,s->file)!=1)
1567                                 err=UNZ_ERRNO;
1568                 lSeek += file_info.size_file_extra - uSizeRead;
1569         }
1570         else
1571                 lSeek+=file_info.size_file_extra; 
1572
1573         
1574         if ((err==UNZ_OK) && (szComment!=NULL))
1575         {
1576                 uLong uSizeRead ;
1577                 if (file_info.size_file_comment<commentBufferSize)
1578                 {
1579                         *(szComment+file_info.size_file_comment)='\0';
1580                         uSizeRead = file_info.size_file_comment;
1581                 }
1582                 else
1583                         uSizeRead = commentBufferSize;
1584
1585                 if (lSeek!=0)
1586                         if (fseek(s->file,lSeek,SEEK_CUR)==0)
1587                                 lSeek=0;
1588                         else
1589                                 err=UNZ_ERRNO;
1590                 if ((file_info.size_file_comment>0) && (commentBufferSize>0))
1591                         if (fread(szComment,(uInt)uSizeRead,1,s->file)!=1)
1592                                 err=UNZ_ERRNO;
1593                 lSeek+=file_info.size_file_comment - uSizeRead;
1594         }
1595         else
1596                 lSeek+=file_info.size_file_comment;
1597
1598         if ((err==UNZ_OK) && (pfile_info!=NULL))
1599                 *pfile_info=file_info;
1600
1601         if ((err==UNZ_OK) && (pfile_info_internal!=NULL))
1602                 *pfile_info_internal=file_info_internal;
1603
1604         return err;
1605 }
1606
1607 /*
1608   Write info about the ZipFile in the *pglobal_info structure.
1609   No preparation of the structure is needed
1610   return UNZ_OK if there is no problem.
1611 */
1612 extern int unzGetCurrentFileInfo (      unzFile file, unz_file_info *pfile_info,
1613                                                                         char *szFileName, uLong fileNameBufferSize,
1614                                                                         void *extraField, uLong extraFieldBufferSize,
1615                                                                         char *szComment, uLong commentBufferSize)
1616 {
1617         return unzlocal_GetCurrentFileInfoInternal(file,pfile_info,NULL,
1618                                                                                                 szFileName,fileNameBufferSize,
1619                                                                                                 extraField,extraFieldBufferSize,
1620                                                                                                 szComment,commentBufferSize);
1621 }
1622
1623 /*
1624   Set the current file of the zipfile to the first file.
1625   return UNZ_OK if there is no problem
1626 */
1627 extern int unzGoToFirstFile (unzFile file)
1628 {
1629         int err=UNZ_OK;
1630         unz_s* s;
1631         if (file==NULL)
1632                 return UNZ_PARAMERROR;
1633         s=(unz_s*)file;
1634         s->pos_in_central_dir=s->offset_central_dir;
1635         s->num_file=0;
1636         err=unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
1637                                                                                          &s->cur_file_info_internal,
1638                                                                                          NULL,0,NULL,0,NULL,0);
1639         s->current_file_ok = (err == UNZ_OK);
1640         return err;
1641 }
1642
1643 /*
1644   Set the current file of the zipfile to the next file.
1645   return UNZ_OK if there is no problem
1646   return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
1647 */
1648 extern int unzGoToNextFile (unzFile file)
1649 {
1650         unz_s* s;       
1651         int err;
1652
1653         if (file==NULL)
1654                 return UNZ_PARAMERROR;
1655         s=(unz_s*)file;
1656         if (!s->current_file_ok)
1657                 return UNZ_END_OF_LIST_OF_FILE;
1658         if (s->num_file+1==s->gi.number_entry)
1659                 return UNZ_END_OF_LIST_OF_FILE;
1660
1661         s->pos_in_central_dir += SIZECENTRALDIRITEM + s->cur_file_info.size_filename +
1662                         s->cur_file_info.size_file_extra + s->cur_file_info.size_file_comment ;
1663         s->num_file++;
1664         err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
1665                                                                                            &s->cur_file_info_internal,
1666                                                                                            NULL,0,NULL,0,NULL,0);
1667         s->current_file_ok = (err == UNZ_OK);
1668         return err;
1669 }
1670
1671 /*
1672   Get the position of the info of the current file in the zip.
1673   return UNZ_OK if there is no problem
1674 */
1675 extern int unzGetCurrentFileInfoPosition (unzFile file, unsigned long *pos )
1676 {
1677         unz_s* s;       
1678
1679         if (file==NULL)
1680                 return UNZ_PARAMERROR;
1681         s=(unz_s*)file;
1682
1683         *pos = s->pos_in_central_dir;
1684         return UNZ_OK;
1685 }
1686
1687 /*
1688   Set the position of the info of the current file in the zip.
1689   return UNZ_OK if there is no problem
1690 */
1691 extern int unzSetCurrentFileInfoPosition (unzFile file, unsigned long pos )
1692 {
1693         unz_s* s;       
1694         int err;
1695
1696         if (file==NULL)
1697                 return UNZ_PARAMERROR;
1698         s=(unz_s*)file;
1699
1700         s->pos_in_central_dir = pos;
1701         err = unzlocal_GetCurrentFileInfoInternal(file,&s->cur_file_info,
1702                                                                                            &s->cur_file_info_internal,
1703                                                                                            NULL,0,NULL,0,NULL,0);
1704         s->current_file_ok = (err == UNZ_OK);
1705         return UNZ_OK;
1706 }
1707
1708 /*
1709   Try locate the file szFileName in the zipfile.
1710   For the iCaseSensitivity signification, see unzipStringFileNameCompare
1711
1712   return value :
1713   UNZ_OK if the file is found. It becomes the current file.
1714   UNZ_END_OF_LIST_OF_FILE if the file is not found
1715 */
1716 extern int unzLocateFile (unzFile file, const char *szFileName, int iCaseSensitivity)
1717 {
1718         unz_s* s;       
1719         int err;
1720
1721         
1722         uLong num_fileSaved;
1723         uLong pos_in_central_dirSaved;
1724
1725
1726         if (file==NULL)
1727                 return UNZ_PARAMERROR;
1728
1729     if (strlen(szFileName)>=UNZ_MAXFILENAMEINZIP)
1730         return UNZ_PARAMERROR;
1731
1732         s=(unz_s*)file;
1733         if (!s->current_file_ok)
1734                 return UNZ_END_OF_LIST_OF_FILE;
1735
1736         num_fileSaved = s->num_file;
1737         pos_in_central_dirSaved = s->pos_in_central_dir;
1738
1739         err = unzGoToFirstFile(file);
1740
1741         while (err == UNZ_OK)
1742         {
1743                 char szCurrentFileName[UNZ_MAXFILENAMEINZIP+1];
1744                 unzGetCurrentFileInfo(file,NULL,
1745                                                                 szCurrentFileName,sizeof(szCurrentFileName)-1,
1746                                                                 NULL,0,NULL,0);
1747                 if (unzStringFileNameCompare(szCurrentFileName,
1748                                                                                 szFileName,iCaseSensitivity)==0)
1749                         return UNZ_OK;
1750                 err = unzGoToNextFile(file);
1751         }
1752
1753         s->num_file = num_fileSaved ;
1754         s->pos_in_central_dir = pos_in_central_dirSaved ;
1755         return err;
1756 }
1757
1758
1759 /*
1760   Read the static header of the current zipfile
1761   Check the coherency of the static header and info in the end of central
1762         directory about this file
1763   store in *piSizeVar the size of extra info in static header
1764         (filename and size of extra field data)
1765 */
1766 static int unzlocal_CheckCurrentFileCoherencyHeader (unz_s* s, uInt* piSizeVar,
1767                                                                                                         uLong *poffset_local_extrafield,
1768                                                                                                         uInt *psize_local_extrafield)
1769 {
1770         uLong uMagic,uData,uFlags;
1771         uLong size_filename;
1772         uLong size_extra_field;
1773         int err=UNZ_OK;
1774
1775         *piSizeVar = 0;
1776         *poffset_local_extrafield = 0;
1777         *psize_local_extrafield = 0;
1778
1779         if (fseek(s->file,s->cur_file_info_internal.offset_curfile +
1780                                                                 s->byte_before_the_zipfile,SEEK_SET)!=0)
1781                 return UNZ_ERRNO;
1782
1783
1784         if (err==UNZ_OK)
1785                 if (unzlocal_getLong(s->file,&uMagic) != UNZ_OK)
1786                         err=UNZ_ERRNO;
1787                 else if (uMagic!=0x04034b50)
1788                         err=UNZ_BADZIPFILE;
1789
1790         if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
1791                 err=UNZ_ERRNO;
1792 /*
1793         else if ((err==UNZ_OK) && (uData!=s->cur_file_info.wVersion))
1794                 err=UNZ_BADZIPFILE;
1795 */
1796         if (unzlocal_getShort(s->file,&uFlags) != UNZ_OK)
1797                 err=UNZ_ERRNO;
1798
1799         if (unzlocal_getShort(s->file,&uData) != UNZ_OK)
1800                 err=UNZ_ERRNO;
1801         else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compression_method))
1802                 err=UNZ_BADZIPFILE;
1803
1804     if ((err==UNZ_OK) && (s->cur_file_info.compression_method!=0) &&
1805                          (s->cur_file_info.compression_method!=Z_DEFLATED))
1806         err=UNZ_BADZIPFILE;
1807
1808         if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* date/time */
1809                 err=UNZ_ERRNO;
1810
1811         if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* crc */
1812                 err=UNZ_ERRNO;
1813         else if ((err==UNZ_OK) && (uData!=s->cur_file_info.crc) &&
1814                                       ((uFlags & 8)==0))
1815                 err=UNZ_BADZIPFILE;
1816
1817         if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size compr */
1818                 err=UNZ_ERRNO;
1819         else if ((err==UNZ_OK) && (uData!=s->cur_file_info.compressed_size) &&
1820                                                           ((uFlags & 8)==0))
1821                 err=UNZ_BADZIPFILE;
1822
1823         if (unzlocal_getLong(s->file,&uData) != UNZ_OK) /* size uncompr */
1824                 err=UNZ_ERRNO;
1825         else if ((err==UNZ_OK) && (uData!=s->cur_file_info.uncompressed_size) && 
1826                                                           ((uFlags & 8)==0))
1827                 err=UNZ_BADZIPFILE;
1828
1829
1830         if (unzlocal_getShort(s->file,&size_filename) != UNZ_OK)
1831                 err=UNZ_ERRNO;
1832         else if ((err==UNZ_OK) && (size_filename!=s->cur_file_info.size_filename))
1833                 err=UNZ_BADZIPFILE;
1834
1835         *piSizeVar += (uInt)size_filename;
1836
1837         if (unzlocal_getShort(s->file,&size_extra_field) != UNZ_OK)
1838                 err=UNZ_ERRNO;
1839         *poffset_local_extrafield= s->cur_file_info_internal.offset_curfile +
1840                                                                         SIZEZIPLOCALHEADER + size_filename;
1841         *psize_local_extrafield = (uInt)size_extra_field;
1842
1843         *piSizeVar += (uInt)size_extra_field;
1844
1845         return err;
1846 }
1847                                                                                                 
1848 /*
1849   Open for reading data the current file in the zipfile.
1850   If there is no error and the file is opened, the return value is UNZ_OK.
1851 */
1852 extern int unzOpenCurrentFile (unzFile file)
1853 {
1854         int err=UNZ_OK;
1855         int Store;
1856         uInt iSizeVar;
1857         unz_s* s;
1858         file_in_zip_read_info_s* pfile_in_zip_read_info;
1859         uLong offset_local_extrafield;  /* offset of the static extra field */
1860         uInt  size_local_extrafield;    /* size of the static extra field */
1861
1862         if (file==NULL)
1863                 return UNZ_PARAMERROR;
1864         s=(unz_s*)file;
1865         if (!s->current_file_ok)
1866                 return UNZ_PARAMERROR;
1867
1868     if (s->pfile_in_zip_read != NULL)
1869         unzCloseCurrentFile(file);
1870
1871         if (unzlocal_CheckCurrentFileCoherencyHeader(s,&iSizeVar,
1872                                 &offset_local_extrafield,&size_local_extrafield)!=UNZ_OK)
1873                 return UNZ_BADZIPFILE;
1874
1875         pfile_in_zip_read_info = (file_in_zip_read_info_s*)
1876                                                                             ALLOC(sizeof(file_in_zip_read_info_s));
1877         if (pfile_in_zip_read_info==NULL)
1878                 return UNZ_INTERNALERROR;
1879
1880         pfile_in_zip_read_info->read_buffer=(char*)ALLOC(UNZ_BUFSIZE);
1881         pfile_in_zip_read_info->offset_local_extrafield = offset_local_extrafield;
1882         pfile_in_zip_read_info->size_local_extrafield = size_local_extrafield;
1883         pfile_in_zip_read_info->pos_local_extrafield=0;
1884
1885         if (pfile_in_zip_read_info->read_buffer==NULL)
1886         {
1887                 TRYFREE(pfile_in_zip_read_info);
1888                 return UNZ_INTERNALERROR;
1889         }
1890
1891         pfile_in_zip_read_info->stream_initialised=0;
1892         
1893         if ((s->cur_file_info.compression_method!=0) &&
1894         (s->cur_file_info.compression_method!=Z_DEFLATED))
1895                 err=UNZ_BADZIPFILE;
1896         Store = s->cur_file_info.compression_method==0;
1897
1898         pfile_in_zip_read_info->crc32_wait=s->cur_file_info.crc;
1899         pfile_in_zip_read_info->crc32=0;
1900         pfile_in_zip_read_info->compression_method =
1901             s->cur_file_info.compression_method;
1902         pfile_in_zip_read_info->file=s->file;
1903         pfile_in_zip_read_info->byte_before_the_zipfile=s->byte_before_the_zipfile;
1904
1905     pfile_in_zip_read_info->stream.total_out = 0;
1906
1907         if (!Store)
1908         {
1909           pfile_in_zip_read_info->stream.zalloc = (alloc_func)0;
1910           pfile_in_zip_read_info->stream.zfree = (free_func)0;
1911           pfile_in_zip_read_info->stream.opaque = (voidp)0; 
1912       
1913           err=inflateInit2(&pfile_in_zip_read_info->stream, -MAX_WBITS);
1914           if (err == Z_OK)
1915             pfile_in_zip_read_info->stream_initialised=1;
1916         /* windowBits is passed < 0 to tell that there is no zlib header.
1917          * Note that in this case inflate *requires* an extra "dummy" byte
1918          * after the compressed stream in order to complete decompression and
1919          * return Z_STREAM_END. 
1920          * In unzip, i don't wait absolutely Z_STREAM_END because I known the 
1921          * size of both compressed and uncompressed data
1922          */
1923         }
1924         pfile_in_zip_read_info->rest_read_compressed = 
1925             s->cur_file_info.compressed_size ;
1926         pfile_in_zip_read_info->rest_read_uncompressed = 
1927             s->cur_file_info.uncompressed_size ;
1928
1929         
1930         pfile_in_zip_read_info->pos_in_zipfile = 
1931             s->cur_file_info_internal.offset_curfile + SIZEZIPLOCALHEADER + 
1932                           iSizeVar;
1933         
1934         pfile_in_zip_read_info->stream.avail_in = (uInt)0;
1935
1936
1937         s->pfile_in_zip_read = pfile_in_zip_read_info;
1938     return UNZ_OK;
1939 }
1940
1941
1942 /*
1943   Read bytes from the current file.
1944   buf contain buffer where data must be copied
1945   len the size of buf.
1946
1947   return the number of byte copied if somes bytes are copied
1948   return 0 if the end of file was reached
1949   return <0 with error code if there is an error
1950     (UNZ_ERRNO for IO error, or zLib error for uncompress error)
1951 */
1952 extern int unzReadCurrentFile  (unzFile file, void *buf, unsigned len)
1953 {
1954         int err=UNZ_OK;
1955         uInt iRead = 0;
1956         unz_s* s;
1957         file_in_zip_read_info_s* pfile_in_zip_read_info;
1958         if (file==NULL)
1959                 return UNZ_PARAMERROR;
1960         s=(unz_s*)file;
1961     pfile_in_zip_read_info=s->pfile_in_zip_read;
1962
1963         if (pfile_in_zip_read_info==NULL)
1964                 return UNZ_PARAMERROR;
1965
1966
1967         if ((pfile_in_zip_read_info->read_buffer == NULL))
1968                 return UNZ_END_OF_LIST_OF_FILE;
1969         if (len==0)
1970                 return 0;
1971
1972         pfile_in_zip_read_info->stream.next_out = (Byte*)buf;
1973
1974         pfile_in_zip_read_info->stream.avail_out = (uInt)len;
1975         
1976         if (len>pfile_in_zip_read_info->rest_read_uncompressed)
1977                 pfile_in_zip_read_info->stream.avail_out = 
1978                   (uInt)pfile_in_zip_read_info->rest_read_uncompressed;
1979
1980         while (pfile_in_zip_read_info->stream.avail_out>0)
1981         {
1982                 if ((pfile_in_zip_read_info->stream.avail_in==0) &&
1983             (pfile_in_zip_read_info->rest_read_compressed>0))
1984                 {
1985                         uInt uReadThis = UNZ_BUFSIZE;
1986                         if (pfile_in_zip_read_info->rest_read_compressed<uReadThis)
1987                                 uReadThis = (uInt)pfile_in_zip_read_info->rest_read_compressed;
1988                         if (uReadThis == 0)
1989                                 return UNZ_EOF;
1990                         if (s->cur_file_info.compressed_size == pfile_in_zip_read_info->rest_read_compressed)
1991                                 if (fseek(pfile_in_zip_read_info->file,
1992                                                   pfile_in_zip_read_info->pos_in_zipfile + 
1993                                                          pfile_in_zip_read_info->byte_before_the_zipfile,SEEK_SET)!=0)
1994                                         return UNZ_ERRNO;
1995                         if (fread(pfile_in_zip_read_info->read_buffer,uReadThis,1,
1996                          pfile_in_zip_read_info->file)!=1)
1997                                 return UNZ_ERRNO;
1998                         pfile_in_zip_read_info->pos_in_zipfile += uReadThis;
1999
2000                         pfile_in_zip_read_info->rest_read_compressed-=uReadThis;
2001                         
2002                         pfile_in_zip_read_info->stream.next_in = 
2003                 (Byte*)pfile_in_zip_read_info->read_buffer;
2004                         pfile_in_zip_read_info->stream.avail_in = (uInt)uReadThis;
2005                 }
2006
2007                 if (pfile_in_zip_read_info->compression_method==0)
2008                 {
2009                         uInt uDoCopy,i ;
2010                         if (pfile_in_zip_read_info->stream.avail_out < 
2011                             pfile_in_zip_read_info->stream.avail_in)
2012                                 uDoCopy = pfile_in_zip_read_info->stream.avail_out ;
2013                         else
2014                                 uDoCopy = pfile_in_zip_read_info->stream.avail_in ;
2015                                 
2016                         for (i=0;i<uDoCopy;i++)
2017                                 *(pfile_in_zip_read_info->stream.next_out+i) =
2018                         *(pfile_in_zip_read_info->stream.next_in+i);
2019                                         
2020                         pfile_in_zip_read_info->crc32 = crc32(pfile_in_zip_read_info->crc32,
2021                                                                 pfile_in_zip_read_info->stream.next_out,
2022                                                                 uDoCopy);
2023                         pfile_in_zip_read_info->rest_read_uncompressed-=uDoCopy;
2024                         pfile_in_zip_read_info->stream.avail_in -= uDoCopy;
2025                         pfile_in_zip_read_info->stream.avail_out -= uDoCopy;
2026                         pfile_in_zip_read_info->stream.next_out += uDoCopy;
2027                         pfile_in_zip_read_info->stream.next_in += uDoCopy;
2028             pfile_in_zip_read_info->stream.total_out += uDoCopy;
2029                         iRead += uDoCopy;
2030                 }
2031                 else
2032                 {
2033                         uLong uTotalOutBefore,uTotalOutAfter;
2034                         const Byte *bufBefore;
2035                         uLong uOutThis;
2036                         int flush=Z_SYNC_FLUSH;
2037
2038                         uTotalOutBefore = pfile_in_zip_read_info->stream.total_out;
2039                         bufBefore = pfile_in_zip_read_info->stream.next_out;
2040
2041                         /*
2042                         if ((pfile_in_zip_read_info->rest_read_uncompressed ==
2043                                  pfile_in_zip_read_info->stream.avail_out) &&
2044                                 (pfile_in_zip_read_info->rest_read_compressed == 0))
2045                                 flush = Z_FINISH;
2046                         */
2047                         err=inflate(&pfile_in_zip_read_info->stream,flush);
2048
2049                         uTotalOutAfter = pfile_in_zip_read_info->stream.total_out;
2050                         uOutThis = uTotalOutAfter-uTotalOutBefore;
2051                         
2052                         pfile_in_zip_read_info->crc32 = 
2053                 crc32(pfile_in_zip_read_info->crc32,bufBefore,
2054                         (uInt)(uOutThis));
2055
2056                         pfile_in_zip_read_info->rest_read_uncompressed -=
2057                 uOutThis;
2058
2059                         iRead += (uInt)(uTotalOutAfter - uTotalOutBefore);
2060             
2061                         if (err==Z_STREAM_END)
2062                                 return (iRead==0) ? UNZ_EOF : iRead;
2063                         if (err!=Z_OK) 
2064                                 break;
2065                 }
2066         }
2067
2068         if (err==Z_OK)
2069                 return iRead;
2070         return err;
2071 }
2072
2073
2074 /*
2075   Give the current position in uncompressed data
2076 */
2077 extern long unztell (unzFile file)
2078 {
2079         unz_s* s;
2080         file_in_zip_read_info_s* pfile_in_zip_read_info;
2081         if (file==NULL)
2082                 return UNZ_PARAMERROR;
2083         s=(unz_s*)file;
2084     pfile_in_zip_read_info=s->pfile_in_zip_read;
2085
2086         if (pfile_in_zip_read_info==NULL)
2087                 return UNZ_PARAMERROR;
2088
2089         return (long)pfile_in_zip_read_info->stream.total_out;
2090 }
2091
2092
2093 /*
2094   return 1 if the end of file was reached, 0 elsewhere 
2095 */
2096 extern int unzeof (unzFile file)
2097 {
2098         unz_s* s;
2099         file_in_zip_read_info_s* pfile_in_zip_read_info;
2100         if (file==NULL)
2101                 return UNZ_PARAMERROR;
2102         s=(unz_s*)file;
2103     pfile_in_zip_read_info=s->pfile_in_zip_read;
2104
2105         if (pfile_in_zip_read_info==NULL)
2106                 return UNZ_PARAMERROR;
2107         
2108         if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
2109                 return 1;
2110         else
2111                 return 0;
2112 }
2113
2114
2115
2116 /*
2117   Read extra field from the current file (opened by unzOpenCurrentFile)
2118   This is the static-header version of the extra field (sometimes, there is
2119     more info in the static-header version than in the central-header)
2120
2121   if buf==NULL, it return the size of the static extra field that can be read
2122
2123   if buf!=NULL, len is the size of the buffer, the extra header is copied in
2124         buf.
2125   the return value is the number of bytes copied in buf, or (if <0) 
2126         the error code
2127 */
2128 extern int unzGetLocalExtrafield (unzFile file,void *buf,unsigned len)
2129 {
2130         unz_s* s;
2131         file_in_zip_read_info_s* pfile_in_zip_read_info;
2132         uInt read_now;
2133         uLong size_to_read;
2134
2135         if (file==NULL)
2136                 return UNZ_PARAMERROR;
2137         s=(unz_s*)file;
2138     pfile_in_zip_read_info=s->pfile_in_zip_read;
2139
2140         if (pfile_in_zip_read_info==NULL)
2141                 return UNZ_PARAMERROR;
2142
2143         size_to_read = (pfile_in_zip_read_info->size_local_extrafield - 
2144                                 pfile_in_zip_read_info->pos_local_extrafield);
2145
2146         if (buf==NULL)
2147                 return (int)size_to_read;
2148         
2149         if (len>size_to_read)
2150                 read_now = (uInt)size_to_read;
2151         else
2152                 read_now = (uInt)len ;
2153
2154         if (read_now==0)
2155                 return 0;
2156         
2157         if (fseek(pfile_in_zip_read_info->file,
2158               pfile_in_zip_read_info->offset_local_extrafield + 
2159                           pfile_in_zip_read_info->pos_local_extrafield,SEEK_SET)!=0)
2160                 return UNZ_ERRNO;
2161
2162         if (fread(buf,(uInt)size_to_read,1,pfile_in_zip_read_info->file)!=1)
2163                 return UNZ_ERRNO;
2164
2165         return (int)read_now;
2166 }
2167
2168 /*
2169   Close the file in zip opened with unzipOpenCurrentFile
2170   Return UNZ_CRCERROR if all the file was read but the CRC is not good
2171 */
2172 extern int unzCloseCurrentFile (unzFile file)
2173 {
2174         int err=UNZ_OK;
2175
2176         unz_s* s;
2177         file_in_zip_read_info_s* pfile_in_zip_read_info;
2178         if (file==NULL)
2179                 return UNZ_PARAMERROR;
2180         s=(unz_s*)file;
2181     pfile_in_zip_read_info=s->pfile_in_zip_read;
2182
2183         if (pfile_in_zip_read_info==NULL)
2184                 return UNZ_PARAMERROR;
2185
2186
2187         if (pfile_in_zip_read_info->rest_read_uncompressed == 0)
2188         {
2189                 if (pfile_in_zip_read_info->crc32 != pfile_in_zip_read_info->crc32_wait)
2190                         err=UNZ_CRCERROR;
2191         }
2192
2193
2194         TRYFREE(pfile_in_zip_read_info->read_buffer);
2195         pfile_in_zip_read_info->read_buffer = NULL;
2196         if (pfile_in_zip_read_info->stream_initialised)
2197                 inflateEnd(&pfile_in_zip_read_info->stream);
2198
2199         pfile_in_zip_read_info->stream_initialised = 0;
2200         TRYFREE(pfile_in_zip_read_info);
2201
2202     s->pfile_in_zip_read=NULL;
2203
2204         return err;
2205 }
2206
2207
2208 /*
2209   Get the global comment string of the ZipFile, in the szComment buffer.
2210   uSizeBuf is the size of the szComment buffer.
2211   return the number of byte copied or an error code <0
2212 */
2213 extern int unzGetGlobalComment (unzFile file, char *szComment, uLong uSizeBuf)
2214 {
2215         unz_s* s;
2216         uLong uReadThis ;
2217         if (file==NULL)
2218                 return UNZ_PARAMERROR;
2219         s=(unz_s*)file;
2220
2221         uReadThis = uSizeBuf;
2222         if (uReadThis>s->gi.size_comment)
2223                 uReadThis = s->gi.size_comment;
2224
2225         if (fseek(s->file,s->central_pos+22,SEEK_SET)!=0)
2226                 return UNZ_ERRNO;
2227
2228         if (uReadThis>0)
2229     {
2230       *szComment='\0';
2231           if (fread(szComment,(uInt)uReadThis,1,s->file)!=1)
2232                 return UNZ_ERRNO;
2233     }
2234
2235         if ((szComment != NULL) && (uSizeBuf > s->gi.size_comment))
2236                 *(szComment+s->gi.size_comment)='\0';
2237         return (int)uReadThis;
2238 }
2239
2240 /* crc32.c -- compute the CRC-32 of a data stream
2241  * Copyright (C) 1995-1998 Mark Adler
2242  * For conditions of distribution and use, see copyright notice in zlib.h 
2243  */
2244
2245 /* @(#) $Id: unzip.c,v 1.2 1999/09/07 20:51:25 zoid Exp $ */
2246
2247 #ifdef DYNAMIC_CRC_TABLE
2248
2249 static int crc_table_empty = 1;
2250 static uLong crc_table[256];
2251 static void make_crc_table OF((void));
2252
2253 /*
2254   Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
2255   x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
2256
2257   Polynomials over GF(2) are represented in binary, one bit per coefficient,
2258   with the lowest powers in the most significant bit.  Then adding polynomials
2259   is just exclusive-or, and multiplying a polynomial by x is a right shift by
2260   one.  If we call the above polynomial p, and represent a byte as the
2261   polynomial q, also with the lowest power in the most significant bit (so the
2262   byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
2263   where a mod b means the remainder after dividing a by b.
2264
2265   This calculation is done using the shift-register method of multiplying and
2266   taking the remainder.  The register is initialized to zero, and for each
2267   incoming bit, x^32 is added mod p to the register if the bit is a one (where
2268   x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
2269   x (which is shifting right by one and adding x^32 mod p if the bit shifted
2270   out is a one).  We start with the highest power (least significant bit) of
2271   q and repeat for all eight bits of q.
2272
2273   The table is simply the CRC of all possible eight bit values.  This is all
2274   the information needed to generate CRC's on data a byte at a time for all
2275   combinations of CRC register values and incoming bytes.
2276 */
2277 static void make_crc_table()
2278 {
2279   uLong c;
2280   int n, k;
2281   uLong poly;            /* polynomial exclusive-or pattern */
2282   /* terms of polynomial defining this crc (except x^32): */
2283   static const Byte p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
2284
2285   /* make exclusive-or pattern from polynomial (0xedb88320L) */
2286   poly = 0L;
2287   for (n = 0; n < sizeof(p)/sizeof(Byte); n++)
2288     poly |= 1L << (31 - p[n]);
2289  
2290   for (n = 0; n < 256; n++)
2291   {
2292     c = (uLong)n;
2293     for (k = 0; k < 8; k++)
2294       c = c & 1 ? poly ^ (c >> 1) : c >> 1;
2295     crc_table[n] = c;
2296   }
2297   crc_table_empty = 0;
2298 }
2299 #else
2300 /* ========================================================================
2301  * Table of CRC-32's of all single-byte values (made by make_crc_table)
2302  */
2303 static const uLong crc_table[256] = {
2304   0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
2305   0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
2306   0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
2307   0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
2308   0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
2309   0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
2310   0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
2311   0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
2312   0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
2313   0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
2314   0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
2315   0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
2316   0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
2317   0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
2318   0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
2319   0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
2320   0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
2321   0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
2322   0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
2323   0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
2324   0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
2325   0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
2326   0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
2327   0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
2328   0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
2329   0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
2330   0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
2331   0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
2332   0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
2333   0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
2334   0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
2335   0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
2336   0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
2337   0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
2338   0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
2339   0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
2340   0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
2341   0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
2342   0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
2343   0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
2344   0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
2345   0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
2346   0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
2347   0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
2348   0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
2349   0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
2350   0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
2351   0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
2352   0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
2353   0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
2354   0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
2355   0x2d02ef8dL
2356 };
2357 #endif
2358
2359 /* =========================================================================
2360  * This function can be used by asm versions of crc32()
2361  */
2362 const uLong * get_crc_table()
2363 {
2364 #ifdef DYNAMIC_CRC_TABLE
2365   if (crc_table_empty) make_crc_table();
2366 #endif
2367   return (const uLong *)crc_table;
2368 }
2369
2370 /* ========================================================================= */
2371 #define DO1(buf) crc = crc_table[((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8);
2372 #define DO2(buf)  DO1(buf); DO1(buf);
2373 #define DO4(buf)  DO2(buf); DO2(buf);
2374 #define DO8(buf)  DO4(buf); DO4(buf);
2375
2376 /* ========================================================================= */
2377 uLong crc32(uLong crc, const Byte *buf, uInt len)
2378 {
2379     if (buf == Z_NULL) return 0L;
2380 #ifdef DYNAMIC_CRC_TABLE
2381     if (crc_table_empty)
2382       make_crc_table();
2383 #endif
2384     crc = crc ^ 0xffffffffL;
2385     while (len >= 8)
2386     {
2387       DO8(buf);
2388       len -= 8;
2389     }
2390     if (len) do {
2391       DO1(buf);
2392     } while (--len);
2393     return crc ^ 0xffffffffL;
2394 }
2395
2396 /* infblock.h -- header to use infblock.c
2397  * Copyright (C) 1995-1998 Mark Adler
2398  * For conditions of distribution and use, see copyright notice in zlib.h 
2399  */
2400
2401 /* WARNING: this file should *not* be used by applications. It is
2402    part of the implementation of the compression library and is
2403    subject to change. Applications should only use zlib.h.
2404  */
2405
2406 struct inflate_blocks_state;
2407 typedef struct inflate_blocks_state inflate_blocks_statef;
2408
2409 extern inflate_blocks_statef * inflate_blocks_new OF((
2410     z_streamp z,
2411     check_func c,               /* check function */
2412     uInt w));                   /* window size */
2413
2414 extern int inflate_blocks OF((
2415     inflate_blocks_statef *,
2416     z_streamp ,
2417     int));                      /* initial return code */
2418
2419 extern void inflate_blocks_reset OF((
2420     inflate_blocks_statef *,
2421     z_streamp ,
2422     uLong *));                  /* check value on output */
2423
2424 extern int inflate_blocks_free OF((
2425     inflate_blocks_statef *,
2426     z_streamp));
2427
2428 extern void inflate_set_dictionary OF((
2429     inflate_blocks_statef *s,
2430     const Byte *d,  /* dictionary */
2431     uInt  n));       /* dictionary length */
2432
2433 extern int inflate_blocks_sync_point OF((
2434     inflate_blocks_statef *s));
2435
2436 /* simplify the use of the inflate_huft type with some defines */
2437 #define exop word.what.Exop
2438 #define bits word.what.Bits
2439
2440 /* Table for deflate from PKZIP's appnote.txt. */
2441 static const uInt border[] = { /* Order of the bit length code lengths */
2442         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
2443
2444 /* inftrees.h -- header to use inftrees.c
2445  * Copyright (C) 1995-1998 Mark Adler
2446  * For conditions of distribution and use, see copyright notice in zlib.h 
2447  */
2448
2449 /* WARNING: this file should *not* be used by applications. It is
2450    part of the implementation of the compression library and is
2451    subject to change. Applications should only use zlib.h.
2452  */
2453
2454 /* Huffman code lookup table entry--this entry is four bytes for machines
2455    that have 16-bit pointers (e.g. PC's in the small or medium model). */
2456
2457 typedef struct inflate_huft_s inflate_huft;
2458
2459 struct inflate_huft_s {
2460   union {
2461     struct {
2462       Byte Exop;        /* number of extra bits or operation */
2463       Byte Bits;        /* number of bits in this code or subcode */
2464     } what;
2465     uInt pad;           /* pad structure to a power of 2 (4 bytes for */
2466   } word;               /*  16-bit, 8 bytes for 32-bit int's) */
2467   uInt base;            /* literal, length base, distance base,
2468                            or table offset */
2469 };
2470
2471 /* Maximum size of dynamic tree.  The maximum found in a long but non-
2472    exhaustive search was 1004 huft structures (850 for length/literals
2473    and 154 for distances, the latter actually the result of an
2474    exhaustive search).  The actual maximum is not known, but the
2475    value below is more than safe. */
2476 #define MANY 1440
2477
2478 extern int inflate_trees_bits OF((
2479     uInt *,                    /* 19 code lengths */
2480     uInt *,                    /* bits tree desired/actual depth */
2481     inflate_huft * *,       /* bits tree result */
2482     inflate_huft *,             /* space for trees */
2483     z_streamp));                /* for messages */
2484
2485 extern int inflate_trees_dynamic OF((
2486     uInt,                       /* number of literal/length codes */
2487     uInt,                       /* number of distance codes */
2488     uInt *,                    /* that many (total) code lengths */
2489     uInt *,                    /* literal desired/actual bit depth */
2490     uInt *,                    /* distance desired/actual bit depth */
2491     inflate_huft * *,       /* literal/length tree result */
2492     inflate_huft * *,       /* distance tree result */
2493     inflate_huft *,             /* space for trees */
2494     z_streamp));                /* for messages */
2495
2496 extern int inflate_trees_fixed OF((
2497     uInt *,                    /* literal desired/actual bit depth */
2498     uInt *,                    /* distance desired/actual bit depth */
2499     inflate_huft * *,       /* literal/length tree result */
2500     inflate_huft * *,       /* distance tree result */
2501     z_streamp));                /* for memory allocation */
2502
2503
2504 /* infcodes.h -- header to use infcodes.c
2505  * Copyright (C) 1995-1998 Mark Adler
2506  * For conditions of distribution and use, see copyright notice in zlib.h 
2507  */
2508
2509 /* WARNING: this file should *not* be used by applications. It is
2510    part of the implementation of the compression library and is
2511    subject to change. Applications should only use zlib.h.
2512  */
2513
2514 struct inflate_codes_state;
2515 typedef struct inflate_codes_state inflate_codes_statef;
2516
2517 extern inflate_codes_statef *inflate_codes_new OF((
2518     uInt, uInt,
2519     inflate_huft *, inflate_huft *,
2520     z_streamp ));
2521
2522 extern int inflate_codes OF((
2523     inflate_blocks_statef *,
2524     z_streamp ,
2525     int));
2526
2527 extern void inflate_codes_free OF((
2528     inflate_codes_statef *,
2529     z_streamp ));
2530
2531 /* infutil.h -- types and macros common to blocks and codes
2532  * Copyright (C) 1995-1998 Mark Adler
2533  * For conditions of distribution and use, see copyright notice in zlib.h 
2534  */
2535
2536 /* WARNING: this file should *not* be used by applications. It is
2537    part of the implementation of the compression library and is
2538    subject to change. Applications should only use zlib.h.
2539  */
2540
2541 #ifndef _INFUTIL_H
2542 #define _INFUTIL_H
2543
2544 typedef enum {
2545       TYPE,     /* get type bits (3, including end bit) */
2546       LENS,     /* get lengths for stored */
2547       STORED,   /* processing stored block */
2548       TABLE,    /* get table lengths */
2549       BTREE,    /* get bit lengths tree for a dynamic block */
2550       DTREE,    /* get length, distance trees for a dynamic block */
2551       CODES,    /* processing fixed or dynamic block */
2552       DRY,      /* output remaining window bytes */
2553       DONE,     /* finished last block, done */
2554       BAD}      /* got a data error--stuck here */
2555 inflate_block_mode;
2556
2557 /* inflate blocks semi-private state */
2558 struct inflate_blocks_state {
2559
2560   /* mode */
2561   inflate_block_mode  mode;     /* current inflate_block mode */
2562
2563   /* mode dependent information */
2564   union {
2565     uInt left;          /* if STORED, bytes left to copy */
2566     struct {
2567       uInt table;               /* table lengths (14 bits) */
2568       uInt index;               /* index into blens (or border) */
2569       uInt *blens;             /* bit lengths of codes */
2570       uInt bb;                  /* bit length tree depth */
2571       inflate_huft *tb;         /* bit length decoding tree */
2572     } trees;            /* if DTREE, decoding info for trees */
2573     struct {
2574       inflate_codes_statef 
2575          *codes;
2576     } decode;           /* if CODES, current state */
2577   } sub;                /* submode */
2578   uInt last;            /* true if this block is the last block */
2579
2580   /* mode independent information */
2581   uInt bitk;            /* bits in bit buffer */
2582   uLong bitb;           /* bit buffer */
2583   inflate_huft *hufts;  /* single malloc for tree space */
2584   Byte *window;        /* sliding window */
2585   Byte *end;           /* one byte after sliding window */
2586   Byte *read;          /* window read pointer */
2587   Byte *write;         /* window write pointer */
2588   check_func checkfn;   /* check function */
2589   uLong check;          /* check on output */
2590
2591 };
2592
2593
2594 /* defines for inflate input/output */
2595 /*   update pointers and return */
2596 #define UPDBITS {s->bitb=b;s->bitk=k;}
2597 #define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
2598 #define UPDOUT {s->write=q;}
2599 #define UPDATE {UPDBITS UPDIN UPDOUT}
2600 #define LEAVE {UPDATE return inflate_flush(s,z,r);}
2601 /*   get bytes and bits */
2602 #define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
2603 #define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
2604 #define NEXTBYTE (n--,*p++)
2605 #define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
2606 #define DUMPBITS(j) {b>>=(j);k-=(j);}
2607 /*   output bytes */
2608 #define WAVAIL (uInt)(q<s->read?s->read-q-1:s->end-q)
2609 #define LOADOUT {q=s->write;m=(uInt)WAVAIL;}
2610 #define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=(uInt)WAVAIL;}}
2611 #define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
2612 #define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
2613 #define OUTBYTE(a) {*q++=(Byte)(a);m--;}
2614 /*   load static pointers */
2615 #define LOAD {LOADIN LOADOUT}
2616
2617 /* masks for lower bits (size given to avoid silly warnings with Visual C++) */
2618 static /* And'ing with mask[n] masks the lower n bits */
2619 uInt inflate_mask[17] = {
2620     0x0000,
2621     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
2622     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
2623 };
2624
2625 /* copy as much as possible from the sliding window to the output area */
2626 extern int inflate_flush OF((
2627     inflate_blocks_statef *,
2628     z_streamp ,
2629     int));
2630
2631 #endif
2632
2633                                                                 
2634 /*
2635    Notes beyond the 1.93a appnote.txt:
2636
2637    1. Distance pointers never point before the beginning of the output
2638       stream.
2639    2. Distance pointers can point back across blocks, up to 32k away.
2640    3. There is an implied maximum of 7 bits for the bit length table and
2641       15 bits for the actual data.
2642    4. If only one code exists, then it is encoded using one bit.  (Zero
2643       would be more efficient, but perhaps a little confusing.)  If two
2644       codes exist, they are coded using one bit each (0 and 1).
2645    5. There is no way of sending zero distance codes--a dummy must be
2646       sent if there are none.  (History: a pre 2.0 version of PKZIP would
2647       store blocks with no distance codes, but this was discovered to be
2648       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
2649       zero distance codes, which is sent as one code of zero bits in
2650       length.
2651    6. There are up to 286 literal/length codes.  Code 256 represents the
2652       end-of-block.  Note however that the static length tree defines
2653       288 codes just to fill out the Huffman codes.  Codes 286 and 287
2654       cannot be used though, since there is no length base or extra bits
2655       defined for them.  Similarily, there are up to 30 distance codes.
2656       However, static trees define 32 codes (all 5 bits) to fill out the
2657       Huffman codes, but the last two had better not show up in the data.
2658    7. Unzip can check dynamic Huffman blocks for complete code sets.
2659       The exception is that a single code would not be complete (see #4).
2660    8. The five bits following the block type is really the number of
2661       literal codes sent minus 257.
2662    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
2663       (1+6+6).  Therefore, to output three times the length, you output
2664       three codes (1+1+1), whereas to output four times the same length,
2665       you only need two codes (1+3).  Hmm.
2666   10. In the tree reconstruction algorithm, Code = Code + Increment
2667       only if BitLength(i) is not zero.  (Pretty obvious.)
2668   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
2669   12. Note: length code 284 can represent 227-258, but length code 285
2670       really is 258.  The last length deserves its own, short code
2671       since it gets used a lot in very redundant files.  The length
2672       258 is special since 258 - 3 (the min match length) is 255.
2673   13. The literal/length and distance code bit lengths are read as a
2674       single stream of lengths.  It is possible (and advantageous) for
2675       a repeat code (16, 17, or 18) to go across the boundary between
2676       the two sets of lengths.
2677  */
2678
2679
2680 void inflate_blocks_reset(inflate_blocks_statef *s, z_streamp z, uLong *c)
2681 {
2682   if (c != Z_NULL)
2683     *c = s->check;
2684   if (s->mode == BTREE || s->mode == DTREE)
2685     ZFREE(z, s->sub.trees.blens);
2686   if (s->mode == CODES)
2687     inflate_codes_free(s->sub.decode.codes, z);
2688   s->mode = TYPE;
2689   s->bitk = 0;
2690   s->bitb = 0;
2691   s->read = s->write = s->window;
2692   if (s->checkfn != Z_NULL)
2693     z->adler = s->check = (*s->checkfn)(0L, (const Byte *)Z_NULL, 0);
2694   Tracev(("inflate:   blocks reset\n"));
2695 }
2696
2697
2698 inflate_blocks_statef *inflate_blocks_new(z_streamp z, check_func c, uInt w)
2699 {
2700   inflate_blocks_statef *s;
2701
2702   if ((s = (inflate_blocks_statef *)ZALLOC
2703        (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
2704     return s;
2705   if ((s->hufts =
2706        (inflate_huft *)ZALLOC(z, sizeof(inflate_huft), MANY)) == Z_NULL)
2707   {
2708     ZFREE(z, s);
2709     return Z_NULL;
2710   }
2711   if ((s->window = (Byte *)ZALLOC(z, 1, w)) == Z_NULL)
2712   {
2713     ZFREE(z, s->hufts);
2714     ZFREE(z, s);
2715     return Z_NULL;
2716   }
2717   s->end = s->window + w;
2718   s->checkfn = c;
2719   s->mode = TYPE;
2720   Tracev(("inflate:   blocks allocated\n"));
2721   inflate_blocks_reset(s, z, Z_NULL);
2722   return s;
2723 }
2724
2725
2726 int inflate_blocks(inflate_blocks_statef *s, z_streamp z, int r)
2727 {
2728   uInt t;               /* temporary storage */
2729   uLong b;              /* bit buffer */
2730   uInt k;               /* bits in bit buffer */
2731   Byte *p;             /* input data pointer */
2732   uInt n;               /* bytes available there */
2733   Byte *q;             /* output window write pointer */
2734   uInt m;               /* bytes to end of window or read pointer */
2735
2736   /* copy input/output information to locals (UPDATE macro restores) */
2737   LOAD
2738
2739   /* process input based on current state */
2740   while (1) switch (s->mode)
2741   {
2742     case TYPE:
2743       NEEDBITS(3)
2744       t = (uInt)b & 7;
2745       s->last = t & 1;
2746       switch (t >> 1)
2747       {
2748         case 0:                         /* stored */
2749           Tracev(("inflate:     stored block%s\n",
2750                  s->last ? " (last)" : ""));
2751           DUMPBITS(3)
2752           t = k & 7;                    /* go to byte boundary */
2753           DUMPBITS(t)
2754           s->mode = LENS;               /* get length of stored block */
2755           break;
2756         case 1:                         /* fixed */
2757           Tracev(("inflate:     fixed codes block%s\n",
2758                  s->last ? " (last)" : ""));
2759           {
2760             uInt bl, bd;
2761             inflate_huft *tl, *td;
2762
2763             inflate_trees_fixed(&bl, &bd, &tl, &td, z);
2764             s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
2765             if (s->sub.decode.codes == Z_NULL)
2766             {
2767               r = Z_MEM_ERROR;
2768               LEAVE
2769             }
2770           }
2771           DUMPBITS(3)
2772           s->mode = CODES;
2773           break;
2774         case 2:                         /* dynamic */
2775           Tracev(("inflate:     dynamic codes block%s\n",
2776                  s->last ? " (last)" : ""));
2777           DUMPBITS(3)
2778           s->mode = TABLE;
2779           break;
2780         case 3:                         /* illegal */
2781           DUMPBITS(3)
2782           s->mode = BAD;
2783           z->msg = (char*)"invalid block type";
2784           r = Z_DATA_ERROR;
2785           LEAVE
2786       }
2787       break;
2788     case LENS:
2789       NEEDBITS(32)
2790       if ((((~b) >> 16) & 0xffff) != (b & 0xffff))
2791       {
2792         s->mode = BAD;
2793         z->msg = (char*)"invalid stored block lengths";
2794         r = Z_DATA_ERROR;
2795         LEAVE
2796       }
2797       s->sub.left = (uInt)b & 0xffff;
2798       b = k = 0;                      /* dump bits */
2799       Tracev(("inflate:       stored length %u\n", s->sub.left));
2800       s->mode = s->sub.left ? STORED : (s->last ? DRY : TYPE);
2801       break;
2802     case STORED:
2803       if (n == 0)
2804         LEAVE
2805       NEEDOUT
2806       t = s->sub.left;
2807       if (t > n) t = n;
2808       if (t > m) t = m;
2809 #ifdef MACOS_X // Optimization
2810           if (t>64) {
2811                 zmemcpy(q, p, t);
2812       }
2813           else {
2814                 int t1;
2815                 for (t1=0; t1<t; t1++) {
2816                         q[t1] = p[t1];
2817                 }
2818           }
2819 #else
2820       zmemcpy(q, p, t);
2821 #endif
2822       p += t;  n -= t;
2823       q += t;  m -= t;
2824       if ((s->sub.left -= t) != 0)
2825         break;
2826       Tracev(("inflate:       stored end, %lu total out\n",
2827               z->total_out + (q >= s->read ? q - s->read :
2828               (s->end - s->read) + (q - s->window))));
2829       s->mode = s->last ? DRY : TYPE;
2830       break;
2831     case TABLE:
2832       NEEDBITS(14)
2833       s->sub.trees.table = t = (uInt)b & 0x3fff;
2834 #ifndef PKZIP_BUG_WORKAROUND
2835       if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
2836       {
2837         s->mode = BAD;
2838         z->msg = (char*)"too many length or distance symbols";
2839         r = Z_DATA_ERROR;
2840         LEAVE
2841       }
2842 #endif
2843       t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
2844       if ((s->sub.trees.blens = (uInt*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
2845       {
2846         r = Z_MEM_ERROR;
2847         LEAVE
2848       }
2849       DUMPBITS(14)
2850       s->sub.trees.index = 0;
2851       Tracev(("inflate:       table sizes ok\n"));
2852       s->mode = BTREE;
2853     case BTREE:
2854       while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
2855       {
2856         NEEDBITS(3)
2857         s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
2858         DUMPBITS(3)
2859       }
2860       while (s->sub.trees.index < 19)
2861         s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
2862       s->sub.trees.bb = 7;
2863       t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
2864                              &s->sub.trees.tb, s->hufts, z);
2865       if (t != Z_OK)
2866       {
2867         ZFREE(z, s->sub.trees.blens);
2868         r = t;
2869         if (r == Z_DATA_ERROR)
2870           s->mode = BAD;
2871         LEAVE
2872       }
2873       s->sub.trees.index = 0;
2874       Tracev(("inflate:       bits tree ok\n"));
2875       s->mode = DTREE;
2876     case DTREE:
2877       while (t = s->sub.trees.table,
2878              s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
2879       {
2880         inflate_huft *h;
2881         uInt i, j, c;
2882
2883         t = s->sub.trees.bb;
2884         NEEDBITS(t)
2885         h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
2886         t = h->bits;
2887         c = h->base;
2888         if (c < 16)
2889         {
2890           DUMPBITS(t)
2891           s->sub.trees.blens[s->sub.trees.index++] = c;
2892         }
2893         else /* c == 16..18 */
2894         {
2895           i = c == 18 ? 7 : c - 14;
2896           j = c == 18 ? 11 : 3;
2897           NEEDBITS(t + i)
2898           DUMPBITS(t)
2899           j += (uInt)b & inflate_mask[i];
2900           DUMPBITS(i)
2901           i = s->sub.trees.index;
2902           t = s->sub.trees.table;
2903           if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
2904               (c == 16 && i < 1))
2905           {
2906             ZFREE(z, s->sub.trees.blens);
2907             s->mode = BAD;
2908             z->msg = (char*)"invalid bit length repeat";
2909             r = Z_DATA_ERROR;
2910             LEAVE
2911           }
2912           c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
2913           do {
2914             s->sub.trees.blens[i++] = c;
2915           } while (--j);
2916           s->sub.trees.index = i;
2917         }
2918       }
2919       s->sub.trees.tb = Z_NULL;
2920       {
2921         uInt bl, bd;
2922         inflate_huft *tl, *td;
2923         inflate_codes_statef *c;
2924
2925         bl = 9;         /* must be <= 9 for lookahead assumptions */
2926         bd = 6;         /* must be <= 9 for lookahead assumptions */
2927         t = s->sub.trees.table;
2928         t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
2929                                   s->sub.trees.blens, &bl, &bd, &tl, &td,
2930                                   s->hufts, z);
2931         ZFREE(z, s->sub.trees.blens);
2932         if (t != Z_OK)
2933         {
2934           if (t == (uInt)Z_DATA_ERROR)
2935             s->mode = BAD;
2936           r = t;
2937           LEAVE
2938         }
2939         Tracev(("inflate:       trees ok\n"));
2940         if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
2941         {
2942           r = Z_MEM_ERROR;
2943           LEAVE
2944         }
2945         s->sub.decode.codes = c;
2946       }
2947       s->mode = CODES;
2948     case CODES:
2949       UPDATE
2950       if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
2951         return inflate_flush(s, z, r);
2952       r = Z_OK;
2953       inflate_codes_free(s->sub.decode.codes, z);
2954       LOAD
2955       Tracev(("inflate:       codes end, %lu total out\n",
2956               z->total_out + (q >= s->read ? q - s->read :
2957               (s->end - s->read) + (q - s->window))));
2958       if (!s->last)
2959       {
2960         s->mode = TYPE;
2961         break;
2962       }
2963       s->mode = DRY;
2964     case DRY:
2965       FLUSH
2966       if (s->read != s->write)
2967         LEAVE
2968       s->mode = DONE;
2969     case DONE:
2970       r = Z_STREAM_END;
2971       LEAVE
2972     case BAD:
2973       r = Z_DATA_ERROR;
2974       LEAVE
2975     default:
2976       r = Z_STREAM_ERROR;
2977       LEAVE
2978   }
2979 }
2980
2981
2982 int inflate_blocks_free(inflate_blocks_statef *s, z_streamp z)
2983 {
2984   inflate_blocks_reset(s, z, Z_NULL);
2985   ZFREE(z, s->window);
2986   ZFREE(z, s->hufts);
2987   ZFREE(z, s);
2988   Tracev(("inflate:   blocks freed\n"));
2989   return Z_OK;
2990 }
2991
2992
2993 void inflate_set_dictionary(inflate_blocks_statef *s, const Byte *d, uInt n)
2994 {
2995   zmemcpy(s->window, d, n);
2996   s->read = s->write = s->window + n;
2997 }
2998
2999
3000 /* Returns true if inflate is currently at the end of a block generated
3001  * by Z_SYNC_FLUSH or Z_FULL_FLUSH. 
3002  * IN assertion: s != Z_NULL
3003  */
3004 int inflate_blocks_sync_point(inflate_blocks_statef *s)
3005 {
3006   return s->mode == LENS;
3007 }
3008
3009 /* copy as much as possible from the sliding window to the output area */
3010 int inflate_flush(inflate_blocks_statef *s, z_streamp z, int r)
3011 {
3012   uInt n;
3013   Byte *p;
3014   Byte *q;
3015
3016   /* static copies of source and destination pointers */
3017   p = z->next_out;
3018   q = s->read;
3019
3020   /* compute number of bytes to copy as as end of window */
3021   n = (uInt)((q <= s->write ? s->write : s->end) - q);
3022   if (n > z->avail_out) n = z->avail_out;
3023   if (n && r == Z_BUF_ERROR) r = Z_OK;
3024
3025   /* update counters */
3026   z->avail_out -= n;
3027   z->total_out += n;
3028
3029   /* update check information */
3030   if (s->checkfn != Z_NULL)
3031     z->adler = s->check = (*s->checkfn)(s->check, q, n);
3032
3033   /* copy as as end of window */
3034 #ifdef MACOS_X // Optimization
3035   if (n>64) {
3036         zmemcpy(p, q, n);
3037   }
3038   else {
3039         int t1;
3040         for (t1=0; t1<n; t1++) {
3041                 p[t1] = q[t1];
3042         }
3043   }
3044 #else
3045   zmemcpy(p, q, n);
3046 #endif
3047   p += n;
3048   q += n;
3049
3050   /* see if more to copy at beginning of window */
3051   if (q == s->end)
3052   {
3053     /* wrap pointers */
3054     q = s->window;
3055     if (s->write == s->end)
3056       s->write = s->window;
3057
3058     /* compute bytes to copy */
3059     n = (uInt)(s->write - q);
3060     if (n > z->avail_out) n = z->avail_out;
3061     if (n && r == Z_BUF_ERROR) r = Z_OK;
3062
3063     /* update counters */
3064     z->avail_out -= n;
3065     z->total_out += n;
3066
3067     /* update check information */
3068     if (s->checkfn != Z_NULL)
3069       z->adler = s->check = (*s->checkfn)(s->check, q, n);
3070
3071     /* copy */
3072 #ifdef MACOS_X // Optimization
3073         if (n>64) {
3074           zmemcpy(p, q, n);
3075         }
3076         else {
3077           int t1;
3078           for (t1=0; t1<n; t1++) {
3079                 p[t1] = q[t1];
3080           }
3081         }
3082 #else
3083     zmemcpy(p, q, n);
3084 #endif
3085     p += n;
3086     q += n;
3087   }
3088
3089   /* update pointers */
3090   z->next_out = p;
3091   s->read = q;
3092
3093   /* done */
3094   return r;
3095 }
3096
3097 /* inftrees.c -- generate Huffman trees for efficient decoding
3098  * Copyright (C) 1995-1998 Mark Adler
3099  * For conditions of distribution and use, see copyright notice in zlib.h 
3100  */
3101
3102 const char inflate_copyright[] =
3103    " inflate 1.1.3 Copyright 1995-1998 Mark Adler ";
3104 /*
3105   If you use the zlib library in a product, an acknowledgment is welcome
3106   in the documentation of your product. If for some reason you cannot
3107   include such an acknowledgment, I would appreciate that you keep this
3108   copyright string in the executable of your product.
3109  */
3110
3111 /* simplify the use of the inflate_huft type with some defines */
3112 #define exop word.what.Exop
3113 #define bits word.what.Bits
3114
3115
3116 static int huft_build OF((
3117     uInt *,                             /* code lengths in bits */
3118     uInt,               /* number of codes */
3119     uInt,               /* number of "simple" codes */
3120     const uInt *,               /* list of base values for non-simple codes */
3121     const uInt *,               /* list of extra bits for non-simple codes */
3122     inflate_huft **,    /* result: starting table */
3123     uInt *,                             /* maximum lookup bits (returns actual) */
3124     inflate_huft *,     /* space for trees */
3125     uInt *,             /* hufts used in space */
3126     uInt * ));                  /* space for values */
3127
3128 /* Tables for deflate from PKZIP's appnote.txt. */
3129 static const uInt cplens[31] = { /* Copy lengths for literal codes 257..285 */
3130         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
3131         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
3132         /* see note #13 above about 258 */
3133 static const uInt cplext[31] = { /* Extra bits for literal codes 257..285 */
3134         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
3135         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 112, 112}; /* 112==invalid */
3136 static const uInt cpdist[30] = { /* Copy offsets for distance codes 0..29 */
3137         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
3138         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
3139         8193, 12289, 16385, 24577};
3140 static const uInt cpdext[30] = { /* Extra bits for distance codes */
3141         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
3142         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
3143         12, 12, 13, 13};
3144
3145 /*
3146    Huffman code decoding is performed using a multi-level table lookup.
3147    The fastest way to decode is to simply build a lookup table whose
3148    size is determined by the longest code.  However, the time it takes
3149    to build this table can also be a factor if the data being decoded
3150    is not very long.  The most common codes are necessarily the
3151    shortest codes, so those codes dominate the decoding time, and hence
3152    the speed.  The idea is you can have a shorter table that decodes the
3153    shorter, more probable codes, and then point to subsidiary tables for
3154    the longer codes.  The time it costs to decode the longer codes is
3155    then traded against the time it takes to make longer tables.
3156
3157    This results of this trade are in the variables lbits and dbits
3158    below.  lbits is the number of bits the first level table for literal/
3159    length codes can decode in one step, and dbits is the same thing for
3160    the distance codes.  Subsequent tables are also less than or equal to
3161    those sizes.  These values may be adjusted either when all of the
3162    codes are shorter than that, in which case the longest code length in
3163    bits is used, or when the shortest code is *longer* than the requested
3164    table size, in which case the length of the shortest code in bits is
3165    used.
3166
3167    There are two different values for the two tables, since they code a
3168    different number of possibilities each.  The literal/length table
3169    codes 286 possible values, or in a flat code, a little over eight
3170    bits.  The distance table codes 30 possible values, or a little less
3171    than five bits, flat.  The optimum values for speed end up being
3172    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
3173    The optimum values may differ though from machine to machine, and
3174    possibly even between compilers.  Your mileage may vary.
3175  */
3176
3177
3178 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
3179 #define BMAX 15         /* maximum bit length of any code */
3180
3181 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)
3182 //uInt *b;               /* code lengths in bits (all assumed <= BMAX) */
3183 //uInt n;                 /* number of codes (assumed <= 288) */
3184 //uInt s;                 /* number of simple-valued codes (0..s-1) */
3185 //const uInt *d;         /* list of base values for non-simple codes */
3186 //const uInt *e;         /* list of extra bits for non-simple codes */
3187 //inflate_huft ** t;            /* result: starting table */
3188 //uInt *m;               /* maximum lookup bits, returns actual */
3189 //inflate_huft *hp;       /* space for trees */
3190 //uInt *hn;               /* hufts used in space */
3191 //uInt *v;               /* working area: values in order of bit length */
3192 /* Given a list of code lengths and a maximum table size, make a set of
3193    tables to decode that set of codes.  Return Z_OK on success, Z_BUF_ERROR
3194    if the given code set is incomplete (the tables are still built in this
3195    case), Z_DATA_ERROR if the input is invalid (an over-subscribed set of
3196    lengths), or Z_MEM_ERROR if not enough memory. */
3197 {
3198
3199   uInt a;                       /* counter for codes of length k */
3200   uInt c[BMAX+1];               /* bit length count table */
3201   uInt f;                       /* i repeats in table every f entries */
3202   int g;                        /* maximum code length */
3203   int h;                        /* table level */
3204   register uInt i;              /* counter, current code */
3205   register uInt j;              /* counter */
3206   register int k;               /* number of bits in current code */
3207   int l;                        /* bits per table (returned in m) */
3208   uInt mask;                    /* (1 << w) - 1, to avoid cc -O bug on HP */
3209   register uInt *p;            /* pointer into c[], b[], or v[] */
3210   inflate_huft *q;              /* points to current table */
3211   struct inflate_huft_s r;      /* table entry for structure assignment */
3212   inflate_huft *u[BMAX];        /* table stack */
3213   register int w;               /* bits before this table == (l * h) */
3214   uInt x[BMAX+1];               /* bit offsets, then code stack */
3215   uInt *xp;                    /* pointer into x */
3216   int y;                        /* number of dummy codes added */
3217   uInt z;                       /* number of entries in current table */
3218
3219
3220   /* Generate counts for each bit length */
3221   p = c;
3222 #define C0 *p++ = 0;
3223 #define C2 C0 C0 C0 C0
3224 #define C4 C2 C2 C2 C2
3225   C4                            /* clear c[]--assume BMAX+1 is 16 */
3226   p = b;  i = n;
3227   do {
3228     c[*p++]++;                  /* assume all entries <= BMAX */
3229   } while (--i);
3230   if (c[0] == n)                /* null input--all zero length codes */
3231   {
3232     *t = (inflate_huft *)Z_NULL;
3233     *m = 0;
3234     return Z_OK;
3235   }
3236
3237
3238   /* Find minimum and maximum length, bound *m by those */
3239   l = *m;
3240   for (j = 1; j <= BMAX; j++)
3241     if (c[j])
3242       break;
3243   k = j;                        /* minimum code length */
3244   if ((uInt)l < j)
3245     l = j;
3246   for (i = BMAX; i; i--)
3247     if (c[i])
3248       break;
3249   g = i;                        /* maximum code length */
3250   if ((uInt)l > i)
3251     l = i;
3252   *m = l;
3253
3254
3255   /* Adjust last length count to fill out codes, if needed */
3256   for (y = 1 << j; j < i; j++, y <<= 1)
3257     if ((y -= c[j]) < 0)
3258       return Z_DATA_ERROR;
3259   if ((y -= c[i]) < 0)
3260     return Z_DATA_ERROR;
3261   c[i] += y;
3262
3263
3264   /* Generate starting offsets into the value table for each length */
3265   x[1] = j = 0;
3266   p = c + 1;  xp = x + 2;
3267   while (--i) {                 /* note that i == g from above */
3268     *xp++ = (j += *p++);
3269   }
3270
3271
3272   /* Make a table of values in order of bit lengths */
3273   p = b;  i = 0;
3274   do {
3275     if ((j = *p++) != 0)
3276       v[x[j]++] = i;
3277   } while (++i < n);
3278   n = x[g];                     /* set n to length of v */
3279
3280
3281   /* Generate the Huffman codes and for each, make the table entries */
3282   x[0] = i = 0;                 /* first Huffman code is zero */
3283   p = v;                        /* grab values in bit order */
3284   h = -1;                       /* no tables yet--level -1 */
3285   w = -l;                       /* bits decoded == (l * h) */
3286   u[0] = (inflate_huft *)Z_NULL;        /* just to keep compilers happy */
3287   q = (inflate_huft *)Z_NULL;   /* ditto */
3288   z = 0;                        /* ditto */
3289
3290   /* go through the bit lengths (k already is bits in shortest code) */
3291   for (; k <= g; k++)
3292   {
3293     a = c[k];
3294     while (a--)
3295     {
3296       /* here i is the Huffman code of length k bits for value *p */
3297       /* make tables up to required level */
3298       while (k > w + l)
3299       {
3300         h++;
3301         w += l;                 /* previous table always l bits */
3302
3303         /* compute minimum size table less than or equal to l bits */
3304         z = g - w;
3305         z = z > (uInt)l ? l : z;        /* table size upper limit */
3306         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
3307         {                       /* too few codes for k-w bit table */
3308           f -= a + 1;           /* deduct codes from patterns left */
3309           xp = c + k;
3310           if (j < z)
3311             while (++j < z)     /* try smaller tables up to z bits */
3312             {
3313               if ((f <<= 1) <= *++xp)
3314                 break;          /* enough codes to use up j bits */
3315               f -= *xp;         /* else deduct codes from patterns */
3316             }
3317         }
3318         z = 1 << j;             /* table entries for j-bit table */
3319
3320         /* allocate new table */
3321         if (*hn + z > MANY)     /* (note: doesn't matter for fixed) */
3322           return Z_MEM_ERROR;   /* not enough memory */
3323         u[h] = q = hp + *hn;
3324         *hn += z;
3325
3326         /* connect to last table, if there is one */
3327         if (h)
3328         {
3329           x[h] = i;             /* save pattern for backing up */
3330           r.bits = (Byte)l;     /* bits to dump before this table */
3331           r.exop = (Byte)j;     /* bits in this table */
3332           j = i >> (w - l);
3333           r.base = (uInt)(q - u[h-1] - j);   /* offset to this table */
3334           u[h-1][j] = r;        /* connect to last table */
3335         }
3336         else
3337           *t = q;               /* first table is returned result */
3338       }
3339
3340       /* set up table entry in r */
3341       r.bits = (Byte)(k - w);
3342       if (p >= v + n)
3343         r.exop = 128 + 64;      /* out of values--invalid code */
3344       else if (*p < s)
3345       {
3346         r.exop = (Byte)(*p < 256 ? 0 : 32 + 64);     /* 256 is end-of-block */
3347         r.base = *p++;          /* simple code is just the value */
3348       }
3349       else
3350       {
3351         r.exop = (Byte)(e[*p - s] + 16 + 64);/* non-simple--look up in lists */
3352         r.base = d[*p++ - s];
3353       }
3354
3355       /* fill code-like entries with r */
3356       f = 1 << (k - w);
3357       for (j = i >> w; j < z; j += f)
3358         q[j] = r;
3359
3360       /* backwards increment the k-bit code i */
3361       for (j = 1 << (k - 1); i & j; j >>= 1)
3362         i ^= j;
3363       i ^= j;
3364
3365       /* backup over finished tables */
3366       mask = (1 << w) - 1;      /* needed on HP, cc -O bug */
3367       while ((i & mask) != x[h])
3368       {
3369         h--;                    /* don't need to update q */
3370         w -= l;
3371         mask = (1 << w) - 1;
3372       }
3373     }
3374   }
3375
3376
3377   /* Return Z_BUF_ERROR if we were given an incomplete table */
3378   return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
3379 }
3380
3381
3382 int inflate_trees_bits(uInt *c, uInt *bb, inflate_huft * *tb, inflate_huft *hp, z_streamp z)
3383 //uInt *c;               /* 19 code lengths */
3384 //uInt *bb;              /* bits tree desired/actual depth */
3385 //inflate_huft * *tb; /* bits tree result */
3386 //inflate_huft *hp;       /* space for trees */
3387 //z_streamp z;            /* for messages */
3388 {
3389   int r;
3390   uInt hn = 0;          /* hufts used in space */
3391   uInt *v;             /* work area for huft_build */
3392
3393   if ((v = (uInt*)ZALLOC(z, 19, sizeof(uInt))) == Z_NULL)
3394     return Z_MEM_ERROR;
3395   r = huft_build(c, 19, 19, (uInt*)Z_NULL, (uInt*)Z_NULL,
3396                  tb, bb, hp, &hn, v);
3397   if (r == Z_DATA_ERROR)
3398     z->msg = (char*)"oversubscribed dynamic bit lengths tree";
3399   else if (r == Z_BUF_ERROR || *bb == 0)
3400   {
3401     z->msg = (char*)"incomplete dynamic bit lengths tree";
3402     r = Z_DATA_ERROR;
3403   }
3404   ZFREE(z, v);
3405   return r;
3406 }
3407
3408
3409 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)
3410 //uInt nl;                /* number of literal/length codes */
3411 //uInt nd;                /* number of distance codes */
3412 //uInt *c;               /* that many (total) code lengths */
3413 //uInt *bl;              /* literal desired/actual bit depth */
3414 //uInt *bd;              /* distance desired/actual bit depth */
3415 //inflate_huft * *tl; /* literal/length tree result */
3416 //inflate_huft * *td; /* distance tree result */
3417 //inflate_huft *hp;       /* space for trees */
3418 //z_streamp z;            /* for messages */
3419 {
3420   int r;
3421   uInt hn = 0;          /* hufts used in space */
3422   uInt *v;             /* work area for huft_build */
3423
3424   /* allocate work area */
3425   if ((v = (uInt*)ZALLOC(z, 288, sizeof(uInt))) == Z_NULL)
3426     return Z_MEM_ERROR;
3427
3428   /* build literal/length tree */
3429   r = huft_build(c, nl, 257, cplens, cplext, tl, bl, hp, &hn, v);
3430   if (r != Z_OK || *bl == 0)
3431   {
3432     if (r == Z_DATA_ERROR)
3433       z->msg = (char*)"oversubscribed literal/length tree";
3434     else if (r != Z_MEM_ERROR)
3435     {
3436       z->msg = (char*)"incomplete literal/length tree";
3437       r = Z_DATA_ERROR;
3438     }
3439     ZFREE(z, v);
3440     return r;
3441   }
3442
3443   /* build distance tree */
3444   r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, hp, &hn, v);
3445   if (r != Z_OK || (*bd == 0 && nl > 257))
3446   {
3447     if (r == Z_DATA_ERROR)
3448       z->msg = (char*)"oversubscribed distance tree";
3449     else if (r == Z_BUF_ERROR) {
3450 #ifdef PKZIP_BUG_WORKAROUND
3451       r = Z_OK;
3452     }
3453 #else
3454       z->msg = (char*)"incomplete distance tree";
3455       r = Z_DATA_ERROR;
3456     }
3457     else if (r != Z_MEM_ERROR)
3458     {
3459       z->msg = (char*)"empty distance tree with lengths";
3460       r = Z_DATA_ERROR;
3461     }
3462     ZFREE(z, v);
3463     return r;
3464 #endif
3465   }
3466
3467   /* done */
3468   ZFREE(z, v);
3469   return Z_OK;
3470 }
3471
3472 /* inffixed.h -- table for decoding fixed codes
3473  * Generated automatically by the maketree.c program
3474  */
3475
3476 /* WARNING: this file should *not* be used by applications. It is
3477    part of the implementation of the compression library and is
3478    subject to change. Applications should only use zlib.h.
3479  */
3480
3481 static uInt fixed_bl = 9;
3482 static uInt fixed_bd = 5;
3483 static inflate_huft fixed_tl[] = {
3484     {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
3485     {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},192},
3486     {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},160},
3487     {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},224},
3488     {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},144},
3489     {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},208},
3490     {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},176},
3491     {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},240},
3492     {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
3493     {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},200},
3494     {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},168},
3495     {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},232},
3496     {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},152},
3497     {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},216},
3498     {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},184},
3499     {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},248},
3500     {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
3501     {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},196},
3502     {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},164},
3503     {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},228},
3504     {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},148},
3505     {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},212},
3506     {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},180},
3507     {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},244},
3508     {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
3509     {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},204},
3510     {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},172},
3511     {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},236},
3512     {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},156},
3513     {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},220},
3514     {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},188},
3515     {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},252},
3516     {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
3517     {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},194},
3518     {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},162},
3519     {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},226},
3520     {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},146},
3521     {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},210},
3522     {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},178},
3523     {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},242},
3524     {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
3525     {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},202},
3526     {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},170},
3527     {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},234},
3528     {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},154},
3529     {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},218},
3530     {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},186},
3531     {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},250},
3532     {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
3533     {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},198},
3534     {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},166},
3535     {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},230},
3536     {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},150},
3537     {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},214},
3538     {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},182},
3539     {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},246},
3540     {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
3541     {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},206},
3542     {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},174},
3543     {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},238},
3544     {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},158},
3545     {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},222},
3546     {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},190},
3547     {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},254},
3548     {{{96,7}},256}, {{{0,8}},80}, {{{0,8}},16}, {{{84,8}},115},
3549     {{{82,7}},31}, {{{0,8}},112}, {{{0,8}},48}, {{{0,9}},193},
3550     {{{80,7}},10}, {{{0,8}},96}, {{{0,8}},32}, {{{0,9}},161},
3551     {{{0,8}},0}, {{{0,8}},128}, {{{0,8}},64}, {{{0,9}},225},
3552     {{{80,7}},6}, {{{0,8}},88}, {{{0,8}},24}, {{{0,9}},145},
3553     {{{83,7}},59}, {{{0,8}},120}, {{{0,8}},56}, {{{0,9}},209},
3554     {{{81,7}},17}, {{{0,8}},104}, {{{0,8}},40}, {{{0,9}},177},
3555     {{{0,8}},8}, {{{0,8}},136}, {{{0,8}},72}, {{{0,9}},241},
3556     {{{80,7}},4}, {{{0,8}},84}, {{{0,8}},20}, {{{85,8}},227},
3557     {{{83,7}},43}, {{{0,8}},116}, {{{0,8}},52}, {{{0,9}},201},
3558     {{{81,7}},13}, {{{0,8}},100}, {{{0,8}},36}, {{{0,9}},169},
3559     {{{0,8}},4}, {{{0,8}},132}, {{{0,8}},68}, {{{0,9}},233},
3560     {{{80,7}},8}, {{{0,8}},92}, {{{0,8}},28}, {{{0,9}},153},
3561     {{{84,7}},83}, {{{0,8}},124}, {{{0,8}},60}, {{{0,9}},217},
3562     {{{82,7}},23}, {{{0,8}},108}, {{{0,8}},44}, {{{0,9}},185},
3563     {{{0,8}},12}, {{{0,8}},140}, {{{0,8}},76}, {{{0,9}},249},
3564     {{{80,7}},3}, {{{0,8}},82}, {{{0,8}},18}, {{{85,8}},163},
3565     {{{83,7}},35}, {{{0,8}},114}, {{{0,8}},50}, {{{0,9}},197},
3566     {{{81,7}},11}, {{{0,8}},98}, {{{0,8}},34}, {{{0,9}},165},
3567     {{{0,8}},2}, {{{0,8}},130}, {{{0,8}},66}, {{{0,9}},229},
3568     {{{80,7}},7}, {{{0,8}},90}, {{{0,8}},26}, {{{0,9}},149},
3569     {{{84,7}},67}, {{{0,8}},122}, {{{0,8}},58}, {{{0,9}},213},
3570     {{{82,7}},19}, {{{0,8}},106}, {{{0,8}},42}, {{{0,9}},181},
3571     {{{0,8}},10}, {{{0,8}},138}, {{{0,8}},74}, {{{0,9}},245},
3572     {{{80,7}},5}, {{{0,8}},86}, {{{0,8}},22}, {{{192,8}},0},
3573     {{{83,7}},51}, {{{0,8}},118}, {{{0,8}},54}, {{{0,9}},205},
3574     {{{81,7}},15}, {{{0,8}},102}, {{{0,8}},38}, {{{0,9}},173},
3575     {{{0,8}},6}, {{{0,8}},134}, {{{0,8}},70}, {{{0,9}},237},
3576     {{{80,7}},9}, {{{0,8}},94}, {{{0,8}},30}, {{{0,9}},157},
3577     {{{84,7}},99}, {{{0,8}},126}, {{{0,8}},62}, {{{0,9}},221},
3578     {{{82,7}},27}, {{{0,8}},110}, {{{0,8}},46}, {{{0,9}},189},
3579     {{{0,8}},14}, {{{0,8}},142}, {{{0,8}},78}, {{{0,9}},253},
3580     {{{96,7}},256}, {{{0,8}},81}, {{{0,8}},17}, {{{85,8}},131},
3581     {{{82,7}},31}, {{{0,8}},113}, {{{0,8}},49}, {{{0,9}},195},
3582     {{{80,7}},10}, {{{0,8}},97}, {{{0,8}},33}, {{{0,9}},163},
3583     {{{0,8}},1}, {{{0,8}},129}, {{{0,8}},65}, {{{0,9}},227},
3584     {{{80,7}},6}, {{{0,8}},89}, {{{0,8}},25}, {{{0,9}},147},
3585     {{{83,7}},59}, {{{0,8}},121}, {{{0,8}},57}, {{{0,9}},211},
3586     {{{81,7}},17}, {{{0,8}},105}, {{{0,8}},41}, {{{0,9}},179},
3587     {{{0,8}},9}, {{{0,8}},137}, {{{0,8}},73}, {{{0,9}},243},
3588     {{{80,7}},4}, {{{0,8}},85}, {{{0,8}},21}, {{{80,8}},258},
3589     {{{83,7}},43}, {{{0,8}},117}, {{{0,8}},53}, {{{0,9}},203},
3590     {{{81,7}},13}, {{{0,8}},101}, {{{0,8}},37}, {{{0,9}},171},
3591     {{{0,8}},5}, {{{0,8}},133}, {{{0,8}},69}, {{{0,9}},235},
3592     {{{80,7}},8}, {{{0,8}},93}, {{{0,8}},29}, {{{0,9}},155},
3593     {{{84,7}},83}, {{{0,8}},125}, {{{0,8}},61}, {{{0,9}},219},
3594     {{{82,7}},23}, {{{0,8}},109}, {{{0,8}},45}, {{{0,9}},187},
3595     {{{0,8}},13}, {{{0,8}},141}, {{{0,8}},77}, {{{0,9}},251},
3596     {{{80,7}},3}, {{{0,8}},83}, {{{0,8}},19}, {{{85,8}},195},
3597     {{{83,7}},35}, {{{0,8}},115}, {{{0,8}},51}, {{{0,9}},199},
3598     {{{81,7}},11}, {{{0,8}},99}, {{{0,8}},35}, {{{0,9}},167},
3599     {{{0,8}},3}, {{{0,8}},131}, {{{0,8}},67}, {{{0,9}},231},
3600     {{{80,7}},7}, {{{0,8}},91}, {{{0,8}},27}, {{{0,9}},151},
3601     {{{84,7}},67}, {{{0,8}},123}, {{{0,8}},59}, {{{0,9}},215},
3602     {{{82,7}},19}, {{{0,8}},107}, {{{0,8}},43}, {{{0,9}},183},
3603     {{{0,8}},11}, {{{0,8}},139}, {{{0,8}},75}, {{{0,9}},247},
3604     {{{80,7}},5}, {{{0,8}},87}, {{{0,8}},23}, {{{192,8}},0},
3605     {{{83,7}},51}, {{{0,8}},119}, {{{0,8}},55}, {{{0,9}},207},
3606     {{{81,7}},15}, {{{0,8}},103}, {{{0,8}},39}, {{{0,9}},175},
3607     {{{0,8}},7}, {{{0,8}},135}, {{{0,8}},71}, {{{0,9}},239},
3608     {{{80,7}},9}, {{{0,8}},95}, {{{0,8}},31}, {{{0,9}},159},
3609     {{{84,7}},99}, {{{0,8}},127}, {{{0,8}},63}, {{{0,9}},223},
3610     {{{82,7}},27}, {{{0,8}},111}, {{{0,8}},47}, {{{0,9}},191},
3611     {{{0,8}},15}, {{{0,8}},143}, {{{0,8}},79}, {{{0,9}},255}
3612   };
3613 static inflate_huft fixed_td[] = {
3614     {{{80,5}},1}, {{{87,5}},257}, {{{83,5}},17}, {{{91,5}},4097},
3615     {{{81,5}},5}, {{{89,5}},1025}, {{{85,5}},65}, {{{93,5}},16385},
3616     {{{80,5}},3}, {{{88,5}},513}, {{{84,5}},33}, {{{92,5}},8193},
3617     {{{82,5}},9}, {{{90,5}},2049}, {{{86,5}},129}, {{{192,5}},24577},
3618     {{{80,5}},2}, {{{87,5}},385}, {{{83,5}},25}, {{{91,5}},6145},
3619     {{{81,5}},7}, {{{89,5}},1537}, {{{85,5}},97}, {{{93,5}},24577},
3620     {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
3621     {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
3622   };
3623
3624 int inflate_trees_fixed(uInt *bl, uInt *bd, inflate_huft * *tl, inflate_huft * *td, z_streamp z)
3625 //uInt *bl;               /* literal desired/actual bit depth */
3626 //uInt *bd;               /* distance desired/actual bit depth */
3627 //inflate_huft * *tl;  /* literal/length tree result */
3628 //inflate_huft * *td;  /* distance tree result */
3629 //z_streamp z;             /* for memory allocation */
3630 {
3631   *bl = fixed_bl;
3632   *bd = fixed_bd;
3633   *tl = fixed_tl;
3634   *td = fixed_td;
3635   return Z_OK;
3636 }
3637
3638 /* simplify the use of the inflate_huft type with some defines */
3639 #define exop word.what.Exop
3640 #define bits word.what.Bits
3641
3642 /* macros for bit input with no checking and for returning unused bytes */
3643 #define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
3644 #define UNGRAB {c=z->avail_in-n;c=(k>>3)<c?k>>3:c;n+=c;p-=c;k-=c<<3;}
3645
3646 /* Called with number of bytes left to write in window at least 258
3647    (the maximum string length) and number of input bytes available
3648    at least ten.  The ten bytes are six bytes for the longest length/
3649    distance pair plus four bytes for overloading the bit buffer. */
3650
3651 int inflate_fast(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, inflate_blocks_statef *s, z_streamp z)
3652 {
3653   inflate_huft *t;      /* temporary pointer */
3654   uInt e;               /* extra bits or operation */
3655   uLong b;              /* bit buffer */
3656   uInt k;               /* bits in bit buffer */
3657   Byte *p;             /* input data pointer */
3658   uInt n;               /* bytes available there */
3659   Byte *q;             /* output window write pointer */
3660   uInt m;               /* bytes to end of window or read pointer */
3661   uInt ml;              /* mask for literal/length tree */
3662   uInt md;              /* mask for distance tree */
3663   uInt c;               /* bytes to copy */
3664   uInt d;               /* distance back to copy from */
3665   Byte *r;             /* copy source pointer */
3666
3667   /* load input, output, bit values */
3668   LOAD
3669
3670   /* initialize masks */
3671   ml = inflate_mask[bl];
3672   md = inflate_mask[bd];
3673
3674   /* do until not enough input or output space for fast loop */
3675   do {                          /* assume called with m >= 258 && n >= 10 */
3676     /* get literal/length code */
3677     GRABBITS(20)                /* max bits for literal/length code */
3678     if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
3679     {
3680       DUMPBITS(t->bits)
3681       Tracevv((t->base >= 0x20 && t->base < 0x7f ?
3682                 "inflate:         * literal '%c'\n" :
3683                 "inflate:         * literal 0x%02x\n", t->base));
3684       *q++ = (Byte)t->base;
3685       m--;
3686       continue;
3687     }
3688     do {
3689       DUMPBITS(t->bits)
3690       if (e & 16)
3691       {
3692         /* get extra bits for length */
3693         e &= 15;
3694         c = t->base + ((uInt)b & inflate_mask[e]);
3695         DUMPBITS(e)
3696         Tracevv(("inflate:         * length %u\n", c));
3697
3698         /* decode distance base of block to copy */
3699         GRABBITS(15);           /* max bits for distance code */
3700         e = (t = td + ((uInt)b & md))->exop;
3701         do {
3702           DUMPBITS(t->bits)
3703           if (e & 16)
3704           {
3705             /* get extra bits to add to distance base */
3706             e &= 15;
3707             GRABBITS(e)         /* get extra bits (up to 13) */
3708             d = t->base + ((uInt)b & inflate_mask[e]);
3709             DUMPBITS(e)
3710             Tracevv(("inflate:         * distance %u\n", d));
3711
3712             /* do the copy */
3713             m -= c;
3714             if ((uInt)(q - s->window) >= d)     /* offset before dest */
3715             {                                   /*  just copy */
3716               r = q - d;
3717               *q++ = *r++;  c--;        /* minimum count is three, */
3718               *q++ = *r++;  c--;        /*  so unroll loop a little */
3719             }
3720             else                        /* else offset after destination */
3721             {
3722               e = d - (uInt)(q - s->window); /* bytes from offset to end */
3723               r = s->end - e;           /* pointer to offset */
3724               if (c > e)                /* if source crosses, */
3725               {
3726                 c -= e;                 /* copy to end of window */
3727                 do {
3728                   *q++ = *r++;
3729                 } while (--e);
3730                 r = s->window;          /* copy rest from start of window */
3731               }
3732             }
3733             do {                        /* copy all or what's left */
3734               *q++ = *r++;
3735             } while (--c);
3736             break;
3737           }
3738           else if ((e & 64) == 0)
3739           {
3740             t += t->base;
3741             e = (t += ((uInt)b & inflate_mask[e]))->exop;
3742           }
3743           else
3744           {
3745             z->msg = (char*)"invalid distance code";
3746             UNGRAB
3747             UPDATE
3748             return Z_DATA_ERROR;
3749           }
3750         } while (1);
3751         break;
3752       }
3753       if ((e & 64) == 0)
3754       {
3755         t += t->base;
3756         if ((e = (t += ((uInt)b & inflate_mask[e]))->exop) == 0)
3757         {
3758           DUMPBITS(t->bits)
3759           Tracevv((t->base >= 0x20 && t->base < 0x7f ?
3760                     "inflate:         * literal '%c'\n" :
3761                     "inflate:         * literal 0x%02x\n", t->base));
3762           *q++ = (Byte)t->base;
3763           m--;
3764           break;
3765         }
3766       }
3767       else if (e & 32)
3768       {
3769         Tracevv(("inflate:         * end of block\n"));
3770         UNGRAB
3771         UPDATE
3772         return Z_STREAM_END;
3773       }
3774       else
3775       {
3776         z->msg = (char*)"invalid literal/length code";
3777         UNGRAB
3778         UPDATE
3779         return Z_DATA_ERROR;
3780       }
3781     } while (1);
3782   } while (m >= 258 && n >= 10);
3783
3784   /* not enough input or output--restore pointers and return */
3785   UNGRAB
3786   UPDATE
3787   return Z_OK;
3788 }
3789
3790 /* infcodes.c -- process literals and length/distance pairs
3791  * Copyright (C) 1995-1998 Mark Adler
3792  * For conditions of distribution and use, see copyright notice in zlib.h 
3793  */
3794
3795 /* simplify the use of the inflate_huft type with some defines */
3796 #define exop word.what.Exop
3797 #define bits word.what.Bits
3798
3799 typedef enum {        /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
3800       START,    /* x: set up for LEN */
3801       LEN,      /* i: get length/literal/eob next */
3802       LENEXT,   /* i: getting length extra (have base) */
3803       DIST,     /* i: get distance next */
3804       DISTEXT,  /* i: getting distance extra */
3805       COPY,     /* o: copying bytes in window, waiting for space */
3806       LIT,      /* o: got literal, waiting for output space */
3807       WASH,     /* o: got eob, possibly still output waiting */
3808       END,      /* x: got eob and all data flushed */
3809       BADCODE}  /* x: got error */
3810 inflate_codes_mode;
3811
3812 /* inflate codes private state */
3813 struct inflate_codes_state {
3814
3815   /* mode */
3816   inflate_codes_mode mode;      /* current inflate_codes mode */
3817
3818   /* mode dependent information */
3819   uInt len;
3820   union {
3821     struct {
3822       inflate_huft *tree;       /* pointer into tree */
3823       uInt need;                /* bits needed */
3824     } code;             /* if LEN or DIST, where in tree */
3825     uInt lit;           /* if LIT, literal */
3826     struct {
3827       uInt get;                 /* bits to get for extra */
3828       uInt dist;                /* distance back to copy from */
3829     } copy;             /* if EXT or COPY, where and how much */
3830   } sub;                /* submode */
3831
3832   /* mode independent information */
3833   Byte lbits;           /* ltree bits decoded per branch */
3834   Byte dbits;           /* dtree bits decoder per branch */
3835   inflate_huft *ltree;          /* literal/length/eob tree */
3836   inflate_huft *dtree;          /* distance tree */
3837
3838 };
3839
3840
3841 inflate_codes_statef *inflate_codes_new(uInt bl, uInt bd, inflate_huft *tl, inflate_huft *td, z_streamp z)
3842 {
3843   inflate_codes_statef *c;
3844
3845   if ((c = (inflate_codes_statef *)
3846        ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
3847   {
3848     c->mode = START;
3849     c->lbits = (Byte)bl;
3850     c->dbits = (Byte)bd;
3851     c->ltree = tl;
3852     c->dtree = td;
3853     Tracev(("inflate:       codes new\n"));
3854   }
3855   return c;
3856 }
3857
3858
3859 int inflate_codes(inflate_blocks_statef *s, z_streamp z, int r)
3860 {
3861   uInt j;               /* temporary storage */
3862   inflate_huft *t;      /* temporary pointer */
3863   uInt e;               /* extra bits or operation */
3864   uLong b;              /* bit buffer */
3865   uInt k;               /* bits in bit buffer */
3866   Byte *p;             /* input data pointer */
3867   uInt n;               /* bytes available there */
3868   Byte *q;             /* output window write pointer */
3869   uInt m;               /* bytes to end of window or read pointer */
3870   Byte *f;             /* pointer to copy strings from */
3871   inflate_codes_statef *c = s->sub.decode.codes;  /* codes state */
3872
3873   /* copy input/output information to locals (UPDATE macro restores) */
3874   LOAD
3875
3876   /* process input and output based on current state */
3877   while (1) switch (c->mode)
3878   {             /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
3879     case START:         /* x: set up for LEN */
3880 #ifndef SLOW
3881       if (m >= 258 && n >= 10)
3882       {
3883         UPDATE
3884         r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
3885         LOAD
3886         if (r != Z_OK)
3887         {
3888           c->mode = r == Z_STREAM_END ? WASH : BADCODE;
3889           break;
3890         }
3891       }
3892 #endif /* !SLOW */
3893       c->sub.code.need = c->lbits;
3894       c->sub.code.tree = c->ltree;
3895       c->mode = LEN;
3896     case LEN:           /* i: get length/literal/eob next */
3897       j = c->sub.code.need;
3898       NEEDBITS(j)
3899       t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
3900       DUMPBITS(t->bits)
3901       e = (uInt)(t->exop);
3902       if (e == 0)               /* literal */
3903       {
3904         c->sub.lit = t->base;
3905         Tracevv((t->base >= 0x20 && t->base < 0x7f ?
3906                  "inflate:         literal '%c'\n" :
3907                  "inflate:         literal 0x%02x\n", t->base));
3908         c->mode = LIT;
3909         break;
3910       }
3911       if (e & 16)               /* length */
3912       {
3913         c->sub.copy.get = e & 15;
3914         c->len = t->base;
3915         c->mode = LENEXT;
3916         break;
3917       }
3918       if ((e & 64) == 0)        /* next table */
3919       {
3920         c->sub.code.need = e;
3921         c->sub.code.tree = t + t->base;
3922         break;
3923       }
3924       if (e & 32)               /* end of block */
3925       {
3926         Tracevv(("inflate:         end of block\n"));
3927         c->mode = WASH;
3928         break;
3929       }
3930       c->mode = BADCODE;        /* invalid code */
3931       z->msg = (char*)"invalid literal/length code";
3932       r = Z_DATA_ERROR;
3933       LEAVE
3934     case LENEXT:        /* i: getting length extra (have base) */
3935       j = c->sub.copy.get;
3936       NEEDBITS(j)
3937       c->len += (uInt)b & inflate_mask[j];
3938       DUMPBITS(j)
3939       c->sub.code.need = c->dbits;
3940       c->sub.code.tree = c->dtree;
3941       Tracevv(("inflate:         length %u\n", c->len));
3942       c->mode = DIST;
3943     case DIST:          /* i: get distance next */
3944       j = c->sub.code.need;
3945       NEEDBITS(j)
3946       t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
3947       DUMPBITS(t->bits)
3948       e = (uInt)(t->exop);
3949       if (e & 16)               /* distance */
3950       {
3951         c->sub.copy.get = e & 15;
3952         c->sub.copy.dist = t->base;
3953         c->mode = DISTEXT;
3954         break;
3955       }
3956       if ((e & 64) == 0)        /* next table */
3957       {
3958         c->sub.code.need = e;
3959         c->sub.code.tree = t + t->base;
3960         break;
3961       }
3962       c->mode = BADCODE;        /* invalid code */
3963       z->msg = (char*)"invalid distance code";
3964       r = Z_DATA_ERROR;
3965       LEAVE
3966     case DISTEXT:       /* i: getting distance extra */
3967       j = c->sub.copy.get;
3968       NEEDBITS(j)
3969       c->sub.copy.dist += (uInt)b & inflate_mask[j];
3970       DUMPBITS(j)
3971       Tracevv(("inflate:         distance %u\n", c->sub.copy.dist));
3972       c->mode = COPY;
3973     case COPY:          /* o: copying bytes in window, waiting for space */
3974 #ifndef __TURBOC__ /* Turbo C bug for following expression */
3975       f = (uInt)(q - s->window) < c->sub.copy.dist ?
3976           s->end - (c->sub.copy.dist - (q - s->window)) :
3977           q - c->sub.copy.dist;
3978 #else
3979       f = q - c->sub.copy.dist;
3980       if ((uInt)(q - s->window) < c->sub.copy.dist)
3981         f = s->end - (c->sub.copy.dist - (uInt)(q - s->window));
3982 #endif
3983       while (c->len)
3984       {
3985         NEEDOUT
3986         OUTBYTE(*f++)
3987         if (f == s->end)
3988           f = s->window;
3989         c->len--;
3990       }
3991       c->mode = START;
3992       break;
3993     case LIT:           /* o: got literal, waiting for output space */
3994       NEEDOUT
3995       OUTBYTE(c->sub.lit)
3996       c->mode = START;
3997       break;
3998     case WASH:          /* o: got eob, possibly more output */
3999       if (k > 7)        /* return unused byte, if any */
4000       {
4001         Assert(k < 16, "inflate_codes grabbed too many bytes")
4002         k -= 8;
4003         n++;
4004         p--;            /* can always return one */
4005       }
4006       FLUSH
4007       if (s->read != s->write)
4008         LEAVE
4009       c->mode = END;
4010     case END:
4011       r = Z_STREAM_END;
4012       LEAVE
4013     case BADCODE:       /* x: got error */
4014       r = Z_DATA_ERROR;
4015       LEAVE
4016     default:
4017       r = Z_STREAM_ERROR;
4018       LEAVE
4019   }
4020 #ifdef NEED_DUMMY_RETURN
4021   return Z_STREAM_ERROR;  /* Some dumb compilers complain without this */
4022 #endif
4023 }
4024
4025
4026 void inflate_codes_free(inflate_codes_statef *c, z_streamp z)
4027 {
4028   ZFREE(z, c);
4029   Tracev(("inflate:       codes free\n"));
4030 }
4031
4032 /* adler32.c -- compute the Adler-32 checksum of a data stream
4033  * Copyright (C) 1995-1998 Mark Adler
4034  * For conditions of distribution and use, see copyright notice in zlib.h 
4035  */
4036
4037 #define BASE 65521L /* largest prime smaller than 65536 */
4038 #define NMAX 5552
4039 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
4040
4041 #undef DO1
4042 #undef DO2
4043 #undef DO4
4044 #undef DO8
4045
4046 #define DO1(buf,i)  {s1 += buf[i]; s2 += s1;}
4047 #define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
4048 #define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
4049 #define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
4050 #define DO16(buf)   DO8(buf,0); DO8(buf,8);
4051
4052 /* ========================================================================= */
4053 uLong adler32(uLong adler, const Byte *buf, uInt len)
4054 {
4055     unsigned long s1 = adler & 0xffff;
4056     unsigned long s2 = (adler >> 16) & 0xffff;
4057     int k;
4058
4059     if (buf == Z_NULL) return 1L;
4060
4061     while (len > 0) {
4062         k = len < NMAX ? len : NMAX;
4063         len -= k;
4064         while (k >= 16) {
4065             DO16(buf);
4066             buf += 16;
4067             k -= 16;
4068         }
4069         if (k != 0) do {
4070             s1 += *buf++;
4071             s2 += s1;
4072         } while (--k);
4073         s1 %= BASE;
4074         s2 %= BASE;
4075     }
4076     return (s2 << 16) | s1;
4077 }
4078
4079 /* @(#) $Id: unzip.c,v 1.2 1999/09/07 20:51:25 zoid Exp $ */
4080
4081 /* infblock.h -- header to use infblock.c
4082  * Copyright (C) 1995-1998 Mark Adler
4083  * For conditions of distribution and use, see copyright notice in zlib.h 
4084  */
4085
4086 /* WARNING: this file should *not* be used by applications. It is
4087    part of the implementation of the compression library and is
4088    subject to change. Applications should only use zlib.h.
4089  */
4090
4091 extern inflate_blocks_statef * inflate_blocks_new OF((
4092     z_streamp z,
4093     check_func c,               /* check function */
4094     uInt w));                   /* window size */
4095
4096 extern int inflate_blocks OF((
4097     inflate_blocks_statef *,
4098     z_streamp ,
4099     int));                      /* initial return code */
4100
4101 extern void inflate_blocks_reset OF((
4102     inflate_blocks_statef *,
4103     z_streamp ,
4104     uLong *));                  /* check value on output */
4105
4106 extern int inflate_blocks_free OF((
4107     inflate_blocks_statef *,
4108     z_streamp));
4109
4110 extern void inflate_set_dictionary OF((
4111     inflate_blocks_statef *s,
4112     const Byte *d,  /* dictionary */
4113     uInt  n));       /* dictionary length */
4114
4115 extern int inflate_blocks_sync_point OF((
4116     inflate_blocks_statef *s));
4117
4118 typedef enum {
4119       imMETHOD,   /* waiting for method byte */
4120       imFLAG,     /* waiting for flag byte */
4121       imDICT4,    /* four dictionary check bytes to go */
4122       imDICT3,    /* three dictionary check bytes to go */
4123       imDICT2,    /* two dictionary check bytes to go */
4124       imDICT1,    /* one dictionary check byte to go */
4125       imDICT0,    /* waiting for inflateSetDictionary */
4126       imBLOCKS,   /* decompressing blocks */
4127       imCHECK4,   /* four check bytes to go */
4128       imCHECK3,   /* three check bytes to go */
4129       imCHECK2,   /* two check bytes to go */
4130       imCHECK1,   /* one check byte to go */
4131       imDONE,     /* finished check, done */
4132       imBAD}      /* got an error--stay here */
4133 inflate_mode;
4134
4135 /* inflate private state */
4136 struct internal_state {
4137
4138   /* mode */
4139   inflate_mode  mode;   /* current inflate mode */
4140
4141   /* mode dependent information */
4142   union {
4143     uInt method;        /* if FLAGS, method byte */
4144     struct {
4145       uLong was;                /* computed check value */
4146       uLong need;               /* stream check value */
4147     } check;            /* if CHECK, check values to compare */
4148     uInt marker;        /* if BAD, inflateSync's marker bytes count */
4149   } sub;        /* submode */
4150
4151   /* mode independent information */
4152   int  nowrap;          /* flag for no wrapper */
4153   uInt wbits;           /* log2(window size)  (8..15, defaults to 15) */
4154   inflate_blocks_statef 
4155     *blocks;            /* current inflate_blocks state */
4156
4157 };
4158
4159
4160 int inflateReset(z_streamp z)
4161 {
4162   if (z == Z_NULL || z->state == Z_NULL)
4163     return Z_STREAM_ERROR;
4164   z->total_in = z->total_out = 0;
4165   z->msg = Z_NULL;
4166   z->state->mode = z->state->nowrap ? imBLOCKS : imMETHOD;
4167   inflate_blocks_reset(z->state->blocks, z, Z_NULL);
4168   Tracev(("inflate: reset\n"));
4169   return Z_OK;
4170 }
4171
4172
4173 int inflateEnd(z_streamp z)
4174 {
4175   if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
4176     return Z_STREAM_ERROR;
4177   if (z->state->blocks != Z_NULL)
4178     inflate_blocks_free(z->state->blocks, z);
4179   ZFREE(z, z->state);
4180   z->state = Z_NULL;
4181   Tracev(("inflate: end\n"));
4182   return Z_OK;
4183 }
4184
4185
4186
4187 int inflateInit2_(z_streamp z, int w, const char *version, int stream_size)
4188 {
4189   if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
4190       stream_size != sizeof(z_stream))
4191       return Z_VERSION_ERROR;
4192
4193   /* initialize state */
4194   if (z == Z_NULL)
4195     return Z_STREAM_ERROR;
4196   z->msg = Z_NULL;
4197   if (z->zalloc == Z_NULL)
4198   {
4199     z->zalloc = (void *(*)(void *, unsigned, unsigned))zcalloc;
4200     z->opaque = (voidp)0;
4201   }
4202   if (z->zfree == Z_NULL) z->zfree = (void (*)(void *, void *))zcfree;
4203   if ((z->state = (struct internal_state *)
4204        ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
4205     return Z_MEM_ERROR;
4206   z->state->blocks = Z_NULL;
4207
4208   /* handle undocumented nowrap option (no zlib header or check) */
4209   z->state->nowrap = 0;
4210   if (w < 0)
4211   {
4212     w = - w;
4213     z->state->nowrap = 1;
4214   }
4215
4216   /* set window size */
4217   if (w < 8 || w > 15)
4218   {
4219     inflateEnd(z);
4220     return Z_STREAM_ERROR;
4221   }
4222   z->state->wbits = (uInt)w;
4223
4224   /* create inflate_blocks state */
4225   if ((z->state->blocks =
4226       inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, (uInt)1 << w))
4227       == Z_NULL)
4228   {
4229     inflateEnd(z);
4230     return Z_MEM_ERROR;
4231   }
4232   Tracev(("inflate: allocated\n"));
4233
4234   /* reset state */
4235   inflateReset(z);
4236   return Z_OK;
4237 }
4238
4239
4240 int inflateInit_(z_streamp z, const char *version, int stream_size)
4241 {
4242   return inflateInit2_(z, DEF_WBITS, version, stream_size);
4243 }
4244
4245
4246 #define iNEEDBYTE {if(z->avail_in==0)return r;r=f;}
4247 #define iNEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
4248
4249 int inflate(z_streamp z, int f)
4250 {
4251   int r;
4252   uInt b;
4253
4254   if (z == Z_NULL || z->state == Z_NULL || z->next_in == Z_NULL)
4255     return Z_STREAM_ERROR;
4256   f = f == Z_FINISH ? Z_BUF_ERROR : Z_OK;
4257   r = Z_BUF_ERROR;
4258   while (1) switch (z->state->mode)
4259   {
4260     case imMETHOD:
4261       iNEEDBYTE
4262       if (((z->state->sub.method = iNEXTBYTE) & 0xf) != Z_DEFLATED)
4263       {
4264         z->state->mode = imBAD;
4265         z->msg = (char*)"unknown compression method";
4266         z->state->sub.marker = 5;       /* can't try inflateSync */
4267         break;
4268       }
4269       if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
4270       {
4271         z->state->mode = imBAD;
4272         z->msg = (char*)"invalid window size";
4273         z->state->sub.marker = 5;       /* can't try inflateSync */
4274         break;
4275       }
4276       z->state->mode = imFLAG;
4277     case imFLAG:
4278       iNEEDBYTE
4279       b = iNEXTBYTE;
4280       if (((z->state->sub.method << 8) + b) % 31)
4281       {
4282         z->state->mode = imBAD;
4283         z->msg = (char*)"incorrect header check";
4284         z->state->sub.marker = 5;       /* can't try inflateSync */
4285         break;
4286       }
4287       Tracev(("inflate: zlib header ok\n"));
4288       if (!(b & PRESET_DICT))
4289       {
4290         z->state->mode = imBLOCKS;
4291         break;
4292       }
4293       z->state->mode = imDICT4;
4294     case imDICT4:
4295       iNEEDBYTE
4296       z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
4297       z->state->mode = imDICT3;
4298     case imDICT3:
4299       iNEEDBYTE
4300       z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
4301       z->state->mode = imDICT2;
4302     case imDICT2:
4303       iNEEDBYTE
4304       z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
4305       z->state->mode = imDICT1;
4306     case imDICT1:
4307       iNEEDBYTE
4308       z->state->sub.check.need += (uLong)iNEXTBYTE;
4309       z->adler = z->state->sub.check.need;
4310       z->state->mode = imDICT0;
4311       return Z_NEED_DICT;
4312     case imDICT0:
4313       z->state->mode = imBAD;
4314       z->msg = (char*)"need dictionary";
4315       z->state->sub.marker = 0;       /* can try inflateSync */
4316       return Z_STREAM_ERROR;
4317     case imBLOCKS:
4318       r = inflate_blocks(z->state->blocks, z, r);
4319       if (r == Z_DATA_ERROR)
4320       {
4321         z->state->mode = imBAD;
4322         z->state->sub.marker = 0;       /* can try inflateSync */
4323         break;
4324       }
4325       if (r == Z_OK)
4326         r = f;
4327       if (r != Z_STREAM_END)
4328         return r;
4329       r = f;
4330       inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
4331       if (z->state->nowrap)
4332       {
4333         z->state->mode = imDONE;
4334         break;
4335       }
4336       z->state->mode = imCHECK4;
4337     case imCHECK4:
4338       iNEEDBYTE
4339       z->state->sub.check.need = (uLong)iNEXTBYTE << 24;
4340       z->state->mode = imCHECK3;
4341     case imCHECK3:
4342       iNEEDBYTE
4343       z->state->sub.check.need += (uLong)iNEXTBYTE << 16;
4344       z->state->mode = imCHECK2;
4345     case imCHECK2:
4346       iNEEDBYTE
4347       z->state->sub.check.need += (uLong)iNEXTBYTE << 8;
4348       z->state->mode = imCHECK1;
4349     case imCHECK1:
4350       iNEEDBYTE
4351       z->state->sub.check.need += (uLong)iNEXTBYTE;
4352
4353       if (z->state->sub.check.was != z->state->sub.check.need)
4354       {
4355         z->state->mode = imBAD;
4356         z->msg = (char*)"incorrect data check";
4357         z->state->sub.marker = 5;       /* can't try inflateSync */
4358         break;
4359       }
4360       Tracev(("inflate: zlib check ok\n"));
4361       z->state->mode = imDONE;
4362     case imDONE:
4363       return Z_STREAM_END;
4364     case imBAD:
4365       return Z_DATA_ERROR;
4366     default:
4367       return Z_STREAM_ERROR;
4368   }
4369 #ifdef NEED_DUMMY_RETURN
4370   return Z_STREAM_ERROR;  /* Some dumb compilers complain without this */
4371 #endif
4372 }
4373
4374
4375 int inflateSetDictionary(z_streamp z, const Byte *dictionary, uInt dictLength)
4376 {
4377   uInt length = dictLength;
4378
4379   if (z == Z_NULL || z->state == Z_NULL || z->state->mode != imDICT0)
4380     return Z_STREAM_ERROR;
4381
4382   if (adler32(1L, dictionary, dictLength) != z->adler) return Z_DATA_ERROR;
4383   z->adler = 1L;
4384
4385   if (length >= ((uInt)1<<z->state->wbits))
4386   {
4387     length = (1<<z->state->wbits)-1;
4388     dictionary += dictLength - length;
4389   }
4390   inflate_set_dictionary(z->state->blocks, dictionary, length);
4391   z->state->mode = imBLOCKS;
4392   return Z_OK;
4393 }
4394
4395
4396 int inflateSync(z_streamp z)
4397 {
4398   uInt n;       /* number of bytes to look at */
4399   Byte *p;     /* pointer to bytes */
4400   uInt m;       /* number of marker bytes found in a row */
4401   uLong r, w;   /* temporaries to save total_in and total_out */
4402
4403   /* set up */
4404   if (z == Z_NULL || z->state == Z_NULL)
4405     return Z_STREAM_ERROR;
4406   if (z->state->mode != imBAD)
4407   {
4408     z->state->mode = imBAD;
4409     z->state->sub.marker = 0;
4410   }
4411   if ((n = z->avail_in) == 0)
4412     return Z_BUF_ERROR;
4413   p = z->next_in;
4414   m = z->state->sub.marker;
4415
4416   /* search */
4417   while (n && m < 4)
4418   {
4419     static const Byte mark[4] = {0, 0, 0xff, 0xff};
4420     if (*p == mark[m])
4421       m++;
4422     else if (*p)
4423       m = 0;
4424     else
4425       m = 4 - m;
4426     p++, n--;
4427   }
4428
4429   /* restore */
4430   z->total_in += p - z->next_in;
4431   z->next_in = p;
4432   z->avail_in = n;
4433   z->state->sub.marker = m;
4434
4435   /* return no joy or set up to restart on a new block */
4436   if (m != 4)
4437     return Z_DATA_ERROR;
4438   r = z->total_in;  w = z->total_out;
4439   inflateReset(z);
4440   z->total_in = r;  z->total_out = w;
4441   z->state->mode = imBLOCKS;
4442   return Z_OK;
4443 }
4444
4445
4446 /* Returns true if inflate is currently at the end of a block generated
4447  * by Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
4448  * implementation to provide an additional safety check. PPP uses Z_SYNC_FLUSH
4449  * but removes the length bytes of the resulting empty stored block. When
4450  * decompressing, PPP checks that at the end of input packet, inflate is
4451  * waiting for these length bytes.
4452  */
4453 int inflateSyncPoint(z_streamp z)
4454 {
4455   if (z == Z_NULL || z->state == Z_NULL || z->state->blocks == Z_NULL)
4456     return Z_STREAM_ERROR;
4457   return inflate_blocks_sync_point(z->state->blocks);
4458 }
4459
4460 voidp zcalloc (voidp opaque, unsigned items, unsigned size)
4461 {
4462     if (opaque) items += size - size; /* make compiler happy */
4463     return (voidp)Mem_ClearedAlloc(items*size);
4464 }
4465
4466 void  zcfree (voidp opaque, voidp ptr)
4467 {
4468     Mem_Free(ptr);
4469     if (opaque) return; /* make compiler happy */
4470 }