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