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