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