Home | History | Annotate | Line # | Download | only in net
zlib.c revision 1.3
      1 /*	$NetBSD: zlib.c,v 1.3 1996/09/18 03:11:03 scottr Exp $	*/
      2 
      3 /*
      4  * This file is derived from various .h and .c files from the zlib-0.95
      5  * distribution by Jean-loup Gailly and Mark Adler, with some additions
      6  * by Paul Mackerras to aid in implementing Deflate compression and
      7  * decompression for PPP packets.  See zlib.h for conditions of
      8  * distribution and use.
      9  *
     10  * Changes that have been made include:
     11  * - changed functions not used outside this file to "local"
     12  * - added minCompression parameter to deflateInit2
     13  * - added Z_PACKET_FLUSH (see zlib.h for details)
     14  * - added inflateIncomp
     15  */
     16 
     17 
     18 /*+++++*/
     19 /* zutil.h -- internal interface and configuration of the compression library
     20  * Copyright (C) 1995 Jean-loup Gailly.
     21  * For conditions of distribution and use, see copyright notice in zlib.h
     22  */
     23 
     24 /* WARNING: this file should *not* be used by applications. It is
     25    part of the implementation of the compression library and is
     26    subject to change. Applications should only use zlib.h.
     27  */
     28 
     29 /* From: zutil.h,v 1.9 1995/05/03 17:27:12 jloup Exp */
     30 
     31 #define _Z_UTIL_H
     32 
     33 #include "zlib.h"
     34 
     35 #ifndef __NetBSD__
     36 #  ifdef STDC
     37 #    include <string.h>
     38 #  endif
     39 #endif
     40 
     41 #ifndef local
     42 #  define local static
     43 #endif
     44 /* compile with -Dlocal if your debugger can't find static symbols */
     45 
     46 #define FAR
     47 
     48 typedef unsigned char  uch;
     49 typedef uch FAR uchf;
     50 typedef unsigned short ush;
     51 typedef ush FAR ushf;
     52 typedef unsigned long  ulg;
     53 
     54 extern char *z_errmsg[]; /* indexed by 1-zlib_error */
     55 
     56 #define ERR_RETURN(strm,err) return (strm->msg=z_errmsg[1-err], err)
     57 /* To be used only when the state is known to be valid */
     58 
     59 #ifndef NULL
     60 #define NULL	((void *) 0)
     61 #endif
     62 
     63         /* common constants */
     64 
     65 #define DEFLATED   8
     66 
     67 #ifndef DEF_WBITS
     68 #  define DEF_WBITS MAX_WBITS
     69 #endif
     70 /* default windowBits for decompression. MAX_WBITS is for compression only */
     71 
     72 #if MAX_MEM_LEVEL >= 8
     73 #  define DEF_MEM_LEVEL 8
     74 #else
     75 #  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
     76 #endif
     77 /* default memLevel */
     78 
     79 #define STORED_BLOCK 0
     80 #define STATIC_TREES 1
     81 #define DYN_TREES    2
     82 /* The three kinds of block type */
     83 
     84 #define MIN_MATCH  3
     85 #define MAX_MATCH  258
     86 /* The minimum and maximum match lengths */
     87 
     88          /* functions */
     89 
     90 #if defined(KERNEL) || defined(_KERNEL)
     91 #  ifdef __NetBSD__
     92 #    include <sys/types.h>
     93 #    include <sys/systm.h>
     94 #  endif
     95 #  define zmemcpy(d, s, n)	bcopy((s), (d), (n))
     96 #  define zmemzero		bzero
     97 #else
     98 #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
     99 #  define HAVE_MEMCPY
    100 #endif
    101 #ifdef HAVE_MEMCPY
    102 #    define zmemcpy memcpy
    103 #    define zmemzero(dest, len) memset(dest, 0, len)
    104 #else
    105    extern void zmemcpy  OF((Bytef* dest, Bytef* source, uInt len));
    106    extern void zmemzero OF((Bytef* dest, uInt len));
    107 #endif
    108 #endif
    109 
    110 /* Diagnostic functions */
    111 #ifdef DEBUG_ZLIB
    112 #  include <stdio.h>
    113 #  ifndef verbose
    114 #    define verbose 0
    115 #  endif
    116 #  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
    117 #  define Trace(x) fprintf x
    118 #  define Tracev(x) {if (verbose) fprintf x ;}
    119 #  define Tracevv(x) {if (verbose>1) fprintf x ;}
    120 #  define Tracec(c,x) {if (verbose && (c)) fprintf x ;}
    121 #  define Tracecv(c,x) {if (verbose>1 && (c)) fprintf x ;}
    122 #else
    123 #  define Assert(cond,msg)
    124 #  define Trace(x)
    125 #  define Tracev(x)
    126 #  define Tracevv(x)
    127 #  define Tracec(c,x)
    128 #  define Tracecv(c,x)
    129 #endif
    130 
    131 
    132 typedef uLong (*check_func) OF((uLong check, Bytef *buf, uInt len));
    133 
    134 /* voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); */
    135 /* void   zcfree  OF((voidpf opaque, voidpf ptr)); */
    136 
    137 #define ZALLOC(strm, items, size) \
    138            (*((strm)->zalloc))((strm)->opaque, (items), (size))
    139 #define ZFREE(strm, addr, size)	\
    140 	   (*((strm)->zfree))((strm)->opaque, (voidpf)(addr), (size))
    141 #define TRY_FREE(s, p, n) {if (p) ZFREE(s, p, n);}
    142 
    143 /* deflate.h -- internal compression state
    144  * Copyright (C) 1995 Jean-loup Gailly
    145  * For conditions of distribution and use, see copyright notice in zlib.h
    146  */
    147 
    148 /* WARNING: this file should *not* be used by applications. It is
    149    part of the implementation of the compression library and is
    150    subject to change. Applications should only use zlib.h.
    151  */
    152 
    153 
    154 /*+++++*/
    155 /* From: deflate.h,v 1.5 1995/05/03 17:27:09 jloup Exp */
    156 
    157 /* ===========================================================================
    158  * Internal compression state.
    159  */
    160 
    161 /* Data type */
    162 #define BINARY  0
    163 #define ASCII   1
    164 #define UNKNOWN 2
    165 
    166 #define LENGTH_CODES 29
    167 /* number of length codes, not counting the special END_BLOCK code */
    168 
    169 #define LITERALS  256
    170 /* number of literal bytes 0..255 */
    171 
    172 #define L_CODES (LITERALS+1+LENGTH_CODES)
    173 /* number of Literal or Length codes, including the END_BLOCK code */
    174 
    175 #define D_CODES   30
    176 /* number of distance codes */
    177 
    178 #define BL_CODES  19
    179 /* number of codes used to transfer the bit lengths */
    180 
    181 #define HEAP_SIZE (2*L_CODES+1)
    182 /* maximum heap size */
    183 
    184 #define MAX_BITS 15
    185 /* All codes must not exceed MAX_BITS bits */
    186 
    187 #define INIT_STATE    42
    188 #define BUSY_STATE   113
    189 #define FLUSH_STATE  124
    190 #define FINISH_STATE 666
    191 /* Stream status */
    192 
    193 
    194 /* Data structure describing a single value and its code string. */
    195 typedef struct ct_data_s {
    196     union {
    197         ush  freq;       /* frequency count */
    198         ush  code;       /* bit string */
    199     } fc;
    200     union {
    201         ush  dad;        /* father node in Huffman tree */
    202         ush  len;        /* length of bit string */
    203     } dl;
    204 } FAR ct_data;
    205 
    206 #define Freq fc.freq
    207 #define Code fc.code
    208 #define Dad  dl.dad
    209 #define Len  dl.len
    210 
    211 typedef struct static_tree_desc_s  static_tree_desc;
    212 
    213 typedef struct tree_desc_s {
    214     ct_data *dyn_tree;           /* the dynamic tree */
    215     int     max_code;            /* largest code with non zero frequency */
    216     static_tree_desc *stat_desc; /* the corresponding static tree */
    217 } FAR tree_desc;
    218 
    219 typedef ush Pos;
    220 typedef Pos FAR Posf;
    221 typedef unsigned IPos;
    222 
    223 /* A Pos is an index in the character window. We use short instead of int to
    224  * save space in the various tables. IPos is used only for parameter passing.
    225  */
    226 
    227 typedef struct deflate_state {
    228     z_stream *strm;      /* pointer back to this zlib stream */
    229     int   status;        /* as the name implies */
    230     Bytef *pending_buf;  /* output still pending */
    231     Bytef *pending_out;  /* next pending byte to output to the stream */
    232     int   pending;       /* nb of bytes in the pending buffer */
    233     uLong adler;         /* adler32 of uncompressed data */
    234     int   noheader;      /* suppress zlib header and adler32 */
    235     Byte  data_type;     /* UNKNOWN, BINARY or ASCII */
    236     Byte  method;        /* STORED (for zip only) or DEFLATED */
    237     int	  minCompr;	 /* min size decrease for Z_FLUSH_NOSTORE */
    238 
    239                 /* used by deflate.c: */
    240 
    241     uInt  w_size;        /* LZ77 window size (32K by default) */
    242     uInt  w_bits;        /* log2(w_size)  (8..16) */
    243     uInt  w_mask;        /* w_size - 1 */
    244 
    245     Bytef *window;
    246     /* Sliding window. Input bytes are read into the second half of the window,
    247      * and move to the first half later to keep a dictionary of at least wSize
    248      * bytes. With this organization, matches are limited to a distance of
    249      * wSize-MAX_MATCH bytes, but this ensures that IO is always
    250      * performed with a length multiple of the block size. Also, it limits
    251      * the window size to 64K, which is quite useful on MSDOS.
    252      * To do: use the user input buffer as sliding window.
    253      */
    254 
    255     ulg window_size;
    256     /* Actual size of window: 2*wSize, except when the user input buffer
    257      * is directly used as sliding window.
    258      */
    259 
    260     Posf *prev;
    261     /* Link to older string with same hash index. To limit the size of this
    262      * array to 64K, this link is maintained only for the last 32K strings.
    263      * An index in this array is thus a window index modulo 32K.
    264      */
    265 
    266     Posf *head; /* Heads of the hash chains or NIL. */
    267 
    268     uInt  ins_h;          /* hash index of string to be inserted */
    269     uInt  hash_size;      /* number of elements in hash table */
    270     uInt  hash_bits;      /* log2(hash_size) */
    271     uInt  hash_mask;      /* hash_size-1 */
    272 
    273     uInt  hash_shift;
    274     /* Number of bits by which ins_h must be shifted at each input
    275      * step. It must be such that after MIN_MATCH steps, the oldest
    276      * byte no longer takes part in the hash key, that is:
    277      *   hash_shift * MIN_MATCH >= hash_bits
    278      */
    279 
    280     long block_start;
    281     /* Window position at the beginning of the current output block. Gets
    282      * negative when the window is moved backwards.
    283      */
    284 
    285     uInt match_length;           /* length of best match */
    286     IPos prev_match;             /* previous match */
    287     int match_available;         /* set if previous match exists */
    288     uInt strstart;               /* start of string to insert */
    289     uInt match_start;            /* start of matching string */
    290     uInt lookahead;              /* number of valid bytes ahead in window */
    291 
    292     uInt prev_length;
    293     /* Length of the best match at previous step. Matches not greater than this
    294      * are discarded. This is used in the lazy match evaluation.
    295      */
    296 
    297     uInt max_chain_length;
    298     /* To speed up deflation, hash chains are never searched beyond this
    299      * length.  A higher limit improves compression ratio but degrades the
    300      * speed.
    301      */
    302 
    303     uInt max_lazy_match;
    304     /* Attempt to find a better match only when the current match is strictly
    305      * smaller than this value. This mechanism is used only for compression
    306      * levels >= 4.
    307      */
    308 #   define max_insert_length  max_lazy_match
    309     /* Insert new strings in the hash table only if the match length is not
    310      * greater than this length. This saves time but degrades compression.
    311      * max_insert_length is used only for compression levels <= 3.
    312      */
    313 
    314     int level;    /* compression level (1..9) */
    315     int strategy; /* favor or force Huffman coding*/
    316 
    317     uInt good_match;
    318     /* Use a faster search when the previous match is longer than this */
    319 
    320      int nice_match; /* Stop searching when current match exceeds this */
    321 
    322                 /* used by trees.c: */
    323     /* Didn't use ct_data typedef below to supress compiler warning */
    324     struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
    325     struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
    326     struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
    327 
    328     struct tree_desc_s l_desc;               /* desc. for literal tree */
    329     struct tree_desc_s d_desc;               /* desc. for distance tree */
    330     struct tree_desc_s bl_desc;              /* desc. for bit length tree */
    331 
    332     ush bl_count[MAX_BITS+1];
    333     /* number of codes at each bit length for an optimal tree */
    334 
    335     int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
    336     int heap_len;               /* number of elements in the heap */
    337     int heap_max;               /* element of largest frequency */
    338     /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
    339      * The same heap array is used to build all trees.
    340      */
    341 
    342     uch depth[2*L_CODES+1];
    343     /* Depth of each subtree used as tie breaker for trees of equal frequency
    344      */
    345 
    346     uchf *l_buf;          /* buffer for literals or lengths */
    347 
    348     uInt  lit_bufsize;
    349     /* Size of match buffer for literals/lengths.  There are 4 reasons for
    350      * limiting lit_bufsize to 64K:
    351      *   - frequencies can be kept in 16 bit counters
    352      *   - if compression is not successful for the first block, all input
    353      *     data is still in the window so we can still emit a stored block even
    354      *     when input comes from standard input.  (This can also be done for
    355      *     all blocks if lit_bufsize is not greater than 32K.)
    356      *   - if compression is not successful for a file smaller than 64K, we can
    357      *     even emit a stored file instead of a stored block (saving 5 bytes).
    358      *     This is applicable only for zip (not gzip or zlib).
    359      *   - creating new Huffman trees less frequently may not provide fast
    360      *     adaptation to changes in the input data statistics. (Take for
    361      *     example a binary file with poorly compressible code followed by
    362      *     a highly compressible string table.) Smaller buffer sizes give
    363      *     fast adaptation but have of course the overhead of transmitting
    364      *     trees more frequently.
    365      *   - I can't count above 4
    366      */
    367 
    368     uInt last_lit;      /* running index in l_buf */
    369 
    370     ushf *d_buf;
    371     /* Buffer for distances. To simplify the code, d_buf and l_buf have
    372      * the same number of elements. To use different lengths, an extra flag
    373      * array would be necessary.
    374      */
    375 
    376     ulg opt_len;        /* bit length of current block with optimal trees */
    377     ulg static_len;     /* bit length of current block with static trees */
    378     ulg compressed_len; /* total bit length of compressed file */
    379     uInt matches;       /* number of string matches in current block */
    380     int last_eob_len;   /* bit length of EOB code for last block */
    381 
    382 #ifdef DEBUG_ZLIB
    383     ulg bits_sent;      /* bit length of the compressed data */
    384 #endif
    385 
    386     ush bi_buf;
    387     /* Output buffer. bits are inserted starting at the bottom (least
    388      * significant bits).
    389      */
    390     int bi_valid;
    391     /* Number of valid bits in bi_buf.  All bits above the last valid bit
    392      * are always zero.
    393      */
    394 
    395     uInt blocks_in_packet;
    396     /* Number of blocks produced since the last time Z_PACKET_FLUSH
    397      * was used.
    398      */
    399 
    400 } FAR deflate_state;
    401 
    402 /* Output a byte on the stream.
    403  * IN assertion: there is enough room in pending_buf.
    404  */
    405 #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
    406 
    407 
    408 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
    409 /* Minimum amount of lookahead, except at the end of the input file.
    410  * See deflate.c for comments about the MIN_MATCH+1.
    411  */
    412 
    413 #define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
    414 /* In order to simplify the code, particularly on 16 bit machines, match
    415  * distances are limited to MAX_DIST instead of WSIZE.
    416  */
    417 
    418         /* in trees.c */
    419 local void ct_init       OF((deflate_state *s));
    420 local int  ct_tally      OF((deflate_state *s, int dist, int lc));
    421 local ulg ct_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
    422 			     int flush));
    423 local void ct_align      OF((deflate_state *s));
    424 local void ct_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
    425                           int eof));
    426 local void ct_stored_type_only OF((deflate_state *s));
    427 
    428 
    429 /*+++++*/
    430 /* deflate.c -- compress data using the deflation algorithm
    431  * Copyright (C) 1995 Jean-loup Gailly.
    432  * For conditions of distribution and use, see copyright notice in zlib.h
    433  */
    434 
    435 /*
    436  *  ALGORITHM
    437  *
    438  *      The "deflation" process depends on being able to identify portions
    439  *      of the input text which are identical to earlier input (within a
    440  *      sliding window trailing behind the input currently being processed).
    441  *
    442  *      The most straightforward technique turns out to be the fastest for
    443  *      most input files: try all possible matches and select the longest.
    444  *      The key feature of this algorithm is that insertions into the string
    445  *      dictionary are very simple and thus fast, and deletions are avoided
    446  *      completely. Insertions are performed at each input character, whereas
    447  *      string matches are performed only when the previous match ends. So it
    448  *      is preferable to spend more time in matches to allow very fast string
    449  *      insertions and avoid deletions. The matching algorithm for small
    450  *      strings is inspired from that of Rabin & Karp. A brute force approach
    451  *      is used to find longer strings when a small match has been found.
    452  *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
    453  *      (by Leonid Broukhis).
    454  *         A previous version of this file used a more sophisticated algorithm
    455  *      (by Fiala and Greene) which is guaranteed to run in linear amortized
    456  *      time, but has a larger average cost, uses more memory and is patented.
    457  *      However the F&G algorithm may be faster for some highly redundant
    458  *      files if the parameter max_chain_length (described below) is too large.
    459  *
    460  *  ACKNOWLEDGEMENTS
    461  *
    462  *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
    463  *      I found it in 'freeze' written by Leonid Broukhis.
    464  *      Thanks to many people for bug reports and testing.
    465  *
    466  *  REFERENCES
    467  *
    468  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
    469  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
    470  *
    471  *      A description of the Rabin and Karp algorithm is given in the book
    472  *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
    473  *
    474  *      Fiala,E.R., and Greene,D.H.
    475  *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
    476  *
    477  */
    478 
    479 /* From: deflate.c,v 1.8 1995/05/03 17:27:08 jloup Exp */
    480 
    481 #if 0
    482 local char zlib_copyright[] = " deflate Copyright 1995 Jean-loup Gailly ";
    483 #endif
    484 /*
    485   If you use the zlib library in a product, an acknowledgment is welcome
    486   in the documentation of your product. If for some reason you cannot
    487   include such an acknowledgment, I would appreciate that you keep this
    488   copyright string in the executable of your product.
    489  */
    490 
    491 #define NIL 0
    492 /* Tail of hash chains */
    493 
    494 #ifndef TOO_FAR
    495 #  define TOO_FAR 4096
    496 #endif
    497 /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
    498 
    499 #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
    500 /* Minimum amount of lookahead, except at the end of the input file.
    501  * See deflate.c for comments about the MIN_MATCH+1.
    502  */
    503 
    504 /* Values for max_lazy_match, good_match and max_chain_length, depending on
    505  * the desired pack level (0..9). The values given below have been tuned to
    506  * exclude worst case performance for pathological files. Better values may be
    507  * found for specific files.
    508  */
    509 
    510 typedef struct config_s {
    511    ush good_length; /* reduce lazy search above this match length */
    512    ush max_lazy;    /* do not perform lazy search above this match length */
    513    ush nice_length; /* quit search above this match length */
    514    ush max_chain;
    515 } config;
    516 
    517 local config configuration_table[10] = {
    518 /*      good lazy nice chain */
    519 /* 0 */ {0,    0,  0,    0},  /* store only */
    520 /* 1 */ {4,    4,  8,    4},  /* maximum speed, no lazy matches */
    521 /* 2 */ {4,    5, 16,    8},
    522 /* 3 */ {4,    6, 32,   32},
    523 
    524 /* 4 */ {4,    4, 16,   16},  /* lazy matches */
    525 /* 5 */ {8,   16, 32,   32},
    526 /* 6 */ {8,   16, 128, 128},
    527 /* 7 */ {8,   32, 128, 256},
    528 /* 8 */ {32, 128, 258, 1024},
    529 /* 9 */ {32, 258, 258, 4096}}; /* maximum compression */
    530 
    531 /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
    532  * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
    533  * meaning.
    534  */
    535 
    536 #define EQUAL 0
    537 /* result of memcmp for equal strings */
    538 
    539 /* ===========================================================================
    540  *  Prototypes for local functions.
    541  */
    542 
    543 local void fill_window   OF((deflate_state *s));
    544 local int  deflate_fast  OF((deflate_state *s, int flush));
    545 local int  deflate_slow  OF((deflate_state *s, int flush));
    546 local void lm_init       OF((deflate_state *s));
    547 local int longest_match  OF((deflate_state *s, IPos cur_match));
    548 local void putShortMSB   OF((deflate_state *s, uInt b));
    549 local void flush_pending OF((z_stream *strm));
    550 local int read_buf       OF((z_stream *strm, charf *buf, unsigned size));
    551 #ifdef ASMV
    552       void match_init OF((void)); /* asm code initialization */
    553 #endif
    554 
    555 #ifdef DEBUG_ZLIB
    556 local  void check_match OF((deflate_state *s, IPos start, IPos match,
    557                             int length));
    558 #endif
    559 
    560 
    561 /* ===========================================================================
    562  * Update a hash value with the given input byte
    563  * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
    564  *    input characters, so that a running hash key can be computed from the
    565  *    previous key instead of complete recalculation each time.
    566  */
    567 #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
    568 
    569 
    570 /* ===========================================================================
    571  * Insert string str in the dictionary and set match_head to the previous head
    572  * of the hash chain (the most recent string with same hash key). Return
    573  * the previous length of the hash chain.
    574  * IN  assertion: all calls to to INSERT_STRING are made with consecutive
    575  *    input characters and the first MIN_MATCH bytes of str are valid
    576  *    (except for the last MIN_MATCH-1 bytes of the input file).
    577  */
    578 #define INSERT_STRING(s, str, match_head) \
    579    (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
    580     s->prev[(str) & s->w_mask] = match_head = s->head[s->ins_h], \
    581     s->head[s->ins_h] = (str))
    582 
    583 /* ===========================================================================
    584  * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
    585  * prev[] will be initialized on the fly.
    586  */
    587 #define CLEAR_HASH(s) \
    588     s->head[s->hash_size-1] = NIL; \
    589     zmemzero((charf *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
    590 
    591 /* ========================================================================= */
    592 int deflateInit (strm, level)
    593     z_stream *strm;
    594     int level;
    595 {
    596     return deflateInit2 (strm, level, DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
    597 			 0, 0);
    598     /* To do: ignore strm->next_in if we use it as window */
    599 }
    600 
    601 /* ========================================================================= */
    602 int deflateInit2 (strm, level, method, windowBits, memLevel,
    603 		  strategy, minCompression)
    604     z_stream *strm;
    605     int  level;
    606     int  method;
    607     int  windowBits;
    608     int  memLevel;
    609     int  strategy;
    610     int  minCompression;
    611 {
    612     deflate_state *s;
    613     int noheader = 0;
    614 
    615     if (strm == Z_NULL) return Z_STREAM_ERROR;
    616 
    617     strm->msg = Z_NULL;
    618 /*    if (strm->zalloc == Z_NULL) strm->zalloc = zcalloc; */
    619 /*    if (strm->zfree == Z_NULL) strm->zfree = zcfree; */
    620 
    621     if (level == Z_DEFAULT_COMPRESSION) level = 6;
    622 
    623     if (windowBits < 0) { /* undocumented feature: suppress zlib header */
    624         noheader = 1;
    625         windowBits = -windowBits;
    626     }
    627     if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != DEFLATED ||
    628         windowBits < 8 || windowBits > 15 || level < 1 || level > 9) {
    629         return Z_STREAM_ERROR;
    630     }
    631     s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
    632     if (s == Z_NULL) return Z_MEM_ERROR;
    633     strm->state = (struct internal_state FAR *)s;
    634     s->strm = strm;
    635 
    636     s->noheader = noheader;
    637     s->w_bits = windowBits;
    638     s->w_size = 1 << s->w_bits;
    639     s->w_mask = s->w_size - 1;
    640 
    641     s->hash_bits = memLevel + 7;
    642     s->hash_size = 1 << s->hash_bits;
    643     s->hash_mask = s->hash_size - 1;
    644     s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
    645 
    646     s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
    647     s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
    648     s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
    649 
    650     s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
    651 
    652     s->pending_buf = (uchf *) ZALLOC(strm, s->lit_bufsize, 2*sizeof(ush));
    653 
    654     if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
    655         s->pending_buf == Z_NULL) {
    656         strm->msg = z_errmsg[1-Z_MEM_ERROR];
    657         deflateEnd (strm);
    658         return Z_MEM_ERROR;
    659     }
    660     s->d_buf = (ushf *) &(s->pending_buf[s->lit_bufsize]);
    661     s->l_buf = (uchf *) &(s->pending_buf[3*s->lit_bufsize]);
    662     /* We overlay pending_buf and d_buf+l_buf. This works since the average
    663      * output size for (length,distance) codes is <= 32 bits (worst case
    664      * is 15+15+13=33).
    665      */
    666 
    667     s->level = level;
    668     s->strategy = strategy;
    669     s->method = (Byte)method;
    670     s->minCompr = minCompression;
    671     s->blocks_in_packet = 0;
    672 
    673     return deflateReset(strm);
    674 }
    675 
    676 /* ========================================================================= */
    677 int deflateReset (strm)
    678     z_stream *strm;
    679 {
    680     deflate_state *s;
    681 
    682     if (strm == Z_NULL || strm->state == Z_NULL ||
    683         strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
    684 
    685     strm->total_in = strm->total_out = 0;
    686     strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
    687     strm->data_type = Z_UNKNOWN;
    688 
    689     s = (deflate_state *)strm->state;
    690     s->pending = 0;
    691     s->pending_out = s->pending_buf;
    692 
    693     if (s->noheader < 0) {
    694         s->noheader = 0; /* was set to -1 by deflate(..., Z_FINISH); */
    695     }
    696     s->status = s->noheader ? BUSY_STATE : INIT_STATE;
    697     s->adler = 1;
    698 
    699     ct_init(s);
    700     lm_init(s);
    701 
    702     return Z_OK;
    703 }
    704 
    705 /* =========================================================================
    706  * Put a short in the pending buffer. The 16-bit value is put in MSB order.
    707  * IN assertion: the stream state is correct and there is enough room in
    708  * pending_buf.
    709  */
    710 local void putShortMSB (s, b)
    711     deflate_state *s;
    712     uInt b;
    713 {
    714     put_byte(s, (Byte)(b >> 8));
    715     put_byte(s, (Byte)(b & 0xff));
    716 }
    717 
    718 /* =========================================================================
    719  * Flush as much pending output as possible.
    720  */
    721 local void flush_pending(strm)
    722     z_stream *strm;
    723 {
    724     deflate_state *state = (deflate_state *) strm->state;
    725     unsigned len = state->pending;
    726 
    727     if (len > strm->avail_out) len = strm->avail_out;
    728     if (len == 0) return;
    729 
    730     if (strm->next_out != NULL) {
    731 	zmemcpy(strm->next_out, state->pending_out, len);
    732 	strm->next_out += len;
    733     }
    734     state->pending_out += len;
    735     strm->total_out += len;
    736     strm->avail_out -= len;
    737     state->pending -= len;
    738     if (state->pending == 0) {
    739         state->pending_out = state->pending_buf;
    740     }
    741 }
    742 
    743 /* ========================================================================= */
    744 int deflate (strm, flush)
    745     z_stream *strm;
    746     int flush;
    747 {
    748     deflate_state *state = (deflate_state *) strm->state;
    749 
    750     if (strm == Z_NULL || state == Z_NULL) return Z_STREAM_ERROR;
    751 
    752     if (strm->next_in == Z_NULL && strm->avail_in != 0) {
    753         ERR_RETURN(strm, Z_STREAM_ERROR);
    754     }
    755     if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
    756 
    757     state->strm = strm; /* just in case */
    758 
    759     /* Write the zlib header */
    760     if (state->status == INIT_STATE) {
    761 
    762         uInt header = (DEFLATED + ((state->w_bits-8)<<4)) << 8;
    763         uInt level_flags = (state->level-1) >> 1;
    764 
    765         if (level_flags > 3) level_flags = 3;
    766         header |= (level_flags << 6);
    767         header += 31 - (header % 31);
    768 
    769         state->status = BUSY_STATE;
    770         putShortMSB(state, header);
    771     }
    772 
    773     /* Flush as much pending output as possible */
    774     if (state->pending != 0) {
    775         flush_pending(strm);
    776         if (strm->avail_out == 0) return Z_OK;
    777     }
    778 
    779     /* If we came back in here to get the last output from
    780      * a previous flush, we're done for now.
    781      */
    782     if (state->status == FLUSH_STATE) {
    783 	state->status = BUSY_STATE;
    784 	if (flush != Z_NO_FLUSH && flush != Z_FINISH)
    785 	    return Z_OK;
    786     }
    787 
    788     /* User must not provide more input after the first FINISH: */
    789     if (state->status == FINISH_STATE && strm->avail_in != 0) {
    790         ERR_RETURN(strm, Z_BUF_ERROR);
    791     }
    792 
    793     /* Start a new block or continue the current one.
    794      */
    795     if (strm->avail_in != 0 || state->lookahead != 0 ||
    796         (flush == Z_FINISH && state->status != FINISH_STATE)) {
    797         int quit;
    798 
    799         if (flush == Z_FINISH) {
    800             state->status = FINISH_STATE;
    801         }
    802         if (state->level <= 3) {
    803             quit = deflate_fast(state, flush);
    804         } else {
    805             quit = deflate_slow(state, flush);
    806         }
    807         if (quit || strm->avail_out == 0)
    808 	    return Z_OK;
    809         /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
    810          * of deflate should use the same flush parameter to make sure
    811          * that the flush is complete. So we don't have to output an
    812          * empty block here, this will be done at next call. This also
    813          * ensures that for a very small output buffer, we emit at most
    814          * one empty block.
    815          */
    816     }
    817 
    818     /* If a flush was requested, we have a little more to output now. */
    819     if (flush != Z_NO_FLUSH && flush != Z_FINISH
    820 	&& state->status != FINISH_STATE) {
    821 	switch (flush) {
    822 	case Z_PARTIAL_FLUSH:
    823 	    ct_align(state);
    824 	    break;
    825 	case Z_PACKET_FLUSH:
    826 	    /* Output just the 3-bit `stored' block type value,
    827 	       but not a zero length. */
    828 	    ct_stored_type_only(state);
    829 	    break;
    830 	default:
    831 	    ct_stored_block(state, (char*)0, 0L, 0);
    832 	    /* For a full flush, this empty block will be recognized
    833 	     * as a special marker by inflate_sync().
    834 	     */
    835 	    if (flush == Z_FULL_FLUSH) {
    836 		CLEAR_HASH(state);             /* forget history */
    837 	    }
    838 	}
    839 	flush_pending(strm);
    840 	if (strm->avail_out == 0) {
    841 	    /* We'll have to come back to get the rest of the output;
    842 	     * this ensures we don't output a second zero-length stored
    843 	     * block (or whatever).
    844 	     */
    845 	    state->status = FLUSH_STATE;
    846 	    return Z_OK;
    847 	}
    848     }
    849 
    850     Assert(strm->avail_out > 0, "bug2");
    851 
    852     if (flush != Z_FINISH) return Z_OK;
    853     if (state->noheader) return Z_STREAM_END;
    854 
    855     /* Write the zlib trailer (adler32) */
    856     putShortMSB(state, (uInt)(state->adler >> 16));
    857     putShortMSB(state, (uInt)(state->adler & 0xffff));
    858     flush_pending(strm);
    859     /* If avail_out is zero, the application will call deflate again
    860      * to flush the rest.
    861      */
    862     state->noheader = -1; /* write the trailer only once! */
    863     return state->pending != 0 ? Z_OK : Z_STREAM_END;
    864 }
    865 
    866 /* ========================================================================= */
    867 int deflateEnd (strm)
    868     z_stream *strm;
    869 {
    870     deflate_state *state = (deflate_state *) strm->state;
    871 
    872     if (strm == Z_NULL || state == Z_NULL) return Z_STREAM_ERROR;
    873 
    874     TRY_FREE(strm, state->window, state->w_size * 2 * sizeof(Byte));
    875     TRY_FREE(strm, state->prev, state->w_size * sizeof(Pos));
    876     TRY_FREE(strm, state->head, state->hash_size * sizeof(Pos));
    877     TRY_FREE(strm, state->pending_buf, state->lit_bufsize * 2 * sizeof(ush));
    878 
    879     ZFREE(strm, state, sizeof(deflate_state));
    880     strm->state = Z_NULL;
    881 
    882     return Z_OK;
    883 }
    884 
    885 /* ===========================================================================
    886  * Read a new buffer from the current input stream, update the adler32
    887  * and total number of bytes read.
    888  */
    889 local int read_buf(strm, buf, size)
    890     z_stream *strm;
    891     charf *buf;
    892     unsigned size;
    893 {
    894     unsigned len = strm->avail_in;
    895     deflate_state *state = (deflate_state *) strm->state;
    896 
    897     if (len > size) len = size;
    898     if (len == 0) return 0;
    899 
    900     strm->avail_in  -= len;
    901 
    902     if (!state->noheader) {
    903         state->adler = adler32(state->adler, strm->next_in, len);
    904     }
    905     zmemcpy(buf, strm->next_in, len);
    906     strm->next_in  += len;
    907     strm->total_in += len;
    908 
    909     return (int)len;
    910 }
    911 
    912 /* ===========================================================================
    913  * Initialize the "longest match" routines for a new zlib stream
    914  */
    915 local void lm_init (s)
    916     deflate_state *s;
    917 {
    918     s->window_size = (ulg)2L*s->w_size;
    919 
    920     CLEAR_HASH(s);
    921 
    922     /* Set the default configuration parameters:
    923      */
    924     s->max_lazy_match   = configuration_table[s->level].max_lazy;
    925     s->good_match       = configuration_table[s->level].good_length;
    926     s->nice_match       = configuration_table[s->level].nice_length;
    927     s->max_chain_length = configuration_table[s->level].max_chain;
    928 
    929     s->strstart = 0;
    930     s->block_start = 0L;
    931     s->lookahead = 0;
    932     s->match_length = MIN_MATCH-1;
    933     s->match_available = 0;
    934     s->ins_h = 0;
    935 #ifdef ASMV
    936     match_init(); /* initialize the asm code */
    937 #endif
    938 }
    939 
    940 /* ===========================================================================
    941  * Set match_start to the longest match starting at the given string and
    942  * return its length. Matches shorter or equal to prev_length are discarded,
    943  * in which case the result is equal to prev_length and match_start is
    944  * garbage.
    945  * IN assertions: cur_match is the head of the hash chain for the current
    946  *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
    947  */
    948 #ifndef ASMV
    949 /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
    950  * match.S. The code will be functionally equivalent.
    951  */
    952 local int longest_match(s, cur_match)
    953     deflate_state *s;
    954     IPos cur_match;                             /* current match */
    955 {
    956     unsigned chain_length = s->max_chain_length;/* max hash chain length */
    957     register Bytef *scan = s->window + s->strstart; /* current string */
    958     register Bytef *match;                       /* matched string */
    959     register int len;                           /* length of current match */
    960     int best_len = s->prev_length;              /* best match length so far */
    961     IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
    962         s->strstart - (IPos)MAX_DIST(s) : NIL;
    963     /* Stop when cur_match becomes <= limit. To simplify the code,
    964      * we prevent matches with the string of window index 0.
    965      */
    966     Posf *prev = s->prev;
    967     uInt wmask = s->w_mask;
    968 
    969 #ifdef UNALIGNED_OK
    970     /* Compare two bytes at a time. Note: this is not always beneficial.
    971      * Try with and without -DUNALIGNED_OK to check.
    972      */
    973     register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
    974     register ush scan_start = *(ushf*)scan;
    975     register ush scan_end   = *(ushf*)(scan+best_len-1);
    976 #else
    977     register Bytef *strend = s->window + s->strstart + MAX_MATCH;
    978     register Byte scan_end1  = scan[best_len-1];
    979     register Byte scan_end   = scan[best_len];
    980 #endif
    981 
    982     /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
    983      * It is easy to get rid of this optimization if necessary.
    984      */
    985     Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
    986 
    987     /* Do not waste too much time if we already have a good match: */
    988     if (s->prev_length >= s->good_match) {
    989         chain_length >>= 2;
    990     }
    991     Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
    992 
    993     do {
    994         Assert(cur_match < s->strstart, "no future");
    995         match = s->window + cur_match;
    996 
    997         /* Skip to next match if the match length cannot increase
    998          * or if the match length is less than 2:
    999          */
   1000 #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
   1001         /* This code assumes sizeof(unsigned short) == 2. Do not use
   1002          * UNALIGNED_OK if your compiler uses a different size.
   1003          */
   1004         if (*(ushf*)(match+best_len-1) != scan_end ||
   1005             *(ushf*)match != scan_start) continue;
   1006 
   1007         /* It is not necessary to compare scan[2] and match[2] since they are
   1008          * always equal when the other bytes match, given that the hash keys
   1009          * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
   1010          * strstart+3, +5, ... up to strstart+257. We check for insufficient
   1011          * lookahead only every 4th comparison; the 128th check will be made
   1012          * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
   1013          * necessary to put more guard bytes at the end of the window, or
   1014          * to check more often for insufficient lookahead.
   1015          */
   1016         Assert(scan[2] == match[2], "scan[2]?");
   1017         scan++, match++;
   1018         do {
   1019         } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
   1020                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
   1021                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
   1022                  *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
   1023                  scan < strend);
   1024         /* The funny "do {}" generates better code on most compilers */
   1025 
   1026         /* Here, scan <= window+strstart+257 */
   1027         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
   1028         if (*scan == *match) scan++;
   1029 
   1030         len = (MAX_MATCH - 1) - (int)(strend-scan);
   1031         scan = strend - (MAX_MATCH-1);
   1032 
   1033 #else /* UNALIGNED_OK */
   1034 
   1035         if (match[best_len]   != scan_end  ||
   1036             match[best_len-1] != scan_end1 ||
   1037             *match            != *scan     ||
   1038             *++match          != scan[1])      continue;
   1039 
   1040         /* The check at best_len-1 can be removed because it will be made
   1041          * again later. (This heuristic is not always a win.)
   1042          * It is not necessary to compare scan[2] and match[2] since they
   1043          * are always equal when the other bytes match, given that
   1044          * the hash keys are equal and that HASH_BITS >= 8.
   1045          */
   1046         scan += 2, match++;
   1047         Assert(*scan == *match, "match[2]?");
   1048 
   1049         /* We check for insufficient lookahead only every 8th comparison;
   1050          * the 256th check will be made at strstart+258.
   1051          */
   1052         do {
   1053         } while (*++scan == *++match && *++scan == *++match &&
   1054                  *++scan == *++match && *++scan == *++match &&
   1055                  *++scan == *++match && *++scan == *++match &&
   1056                  *++scan == *++match && *++scan == *++match &&
   1057                  scan < strend);
   1058 
   1059         Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
   1060 
   1061         len = MAX_MATCH - (int)(strend - scan);
   1062         scan = strend - MAX_MATCH;
   1063 
   1064 #endif /* UNALIGNED_OK */
   1065 
   1066         if (len > best_len) {
   1067             s->match_start = cur_match;
   1068             best_len = len;
   1069             if (len >= s->nice_match) break;
   1070 #ifdef UNALIGNED_OK
   1071             scan_end = *(ushf*)(scan+best_len-1);
   1072 #else
   1073             scan_end1  = scan[best_len-1];
   1074             scan_end   = scan[best_len];
   1075 #endif
   1076         }
   1077     } while ((cur_match = prev[cur_match & wmask]) > limit
   1078              && --chain_length != 0);
   1079 
   1080     return best_len;
   1081 }
   1082 #endif /* ASMV */
   1083 
   1084 #ifdef DEBUG_ZLIB
   1085 /* ===========================================================================
   1086  * Check that the match at match_start is indeed a match.
   1087  */
   1088 local void check_match(s, start, match, length)
   1089     deflate_state *s;
   1090     IPos start, match;
   1091     int length;
   1092 {
   1093     /* check that the match is indeed a match */
   1094     if (memcmp((charf *)s->window + match,
   1095                 (charf *)s->window + start, length) != EQUAL) {
   1096         fprintf(stderr,
   1097             " start %u, match %u, length %d\n",
   1098             start, match, length);
   1099         do { fprintf(stderr, "%c%c", s->window[match++],
   1100                      s->window[start++]); } while (--length != 0);
   1101         z_error("invalid match");
   1102     }
   1103     if (verbose > 1) {
   1104         fprintf(stderr,"\\[%d,%d]", start-match, length);
   1105         do { putc(s->window[start++], stderr); } while (--length != 0);
   1106     }
   1107 }
   1108 #else
   1109 #  define check_match(s, start, match, length)
   1110 #endif
   1111 
   1112 /* ===========================================================================
   1113  * Fill the window when the lookahead becomes insufficient.
   1114  * Updates strstart and lookahead.
   1115  *
   1116  * IN assertion: lookahead < MIN_LOOKAHEAD
   1117  * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
   1118  *    At least one byte has been read, or avail_in == 0; reads are
   1119  *    performed for at least two bytes (required for the zip translate_eol
   1120  *    option -- not supported here).
   1121  */
   1122 local void fill_window(s)
   1123     deflate_state *s;
   1124 {
   1125     register unsigned n, m;
   1126     register Posf *p;
   1127     unsigned more;    /* Amount of free space at the end of the window. */
   1128     uInt wsize = s->w_size;
   1129 
   1130     do {
   1131         more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
   1132 
   1133         /* Deal with !@#$% 64K limit: */
   1134         if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
   1135             more = wsize;
   1136         } else if (more == (unsigned)(-1)) {
   1137             /* Very unlikely, but possible on 16 bit machine if strstart == 0
   1138              * and lookahead == 1 (input done one byte at time)
   1139              */
   1140             more--;
   1141 
   1142         /* If the window is almost full and there is insufficient lookahead,
   1143          * move the upper half to the lower one to make room in the upper half.
   1144          */
   1145         } else if (s->strstart >= wsize+MAX_DIST(s)) {
   1146 
   1147             /* By the IN assertion, the window is not empty so we can't confuse
   1148              * more == 0 with more == 64K on a 16 bit machine.
   1149              */
   1150             zmemcpy((charf *)s->window, (charf *)s->window+wsize,
   1151                    (unsigned)wsize);
   1152             s->match_start -= wsize;
   1153             s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
   1154 
   1155             s->block_start -= (long) wsize;
   1156 
   1157             /* Slide the hash table (could be avoided with 32 bit values
   1158                at the expense of memory usage):
   1159              */
   1160             n = s->hash_size;
   1161             p = &s->head[n];
   1162             do {
   1163                 m = *--p;
   1164                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
   1165             } while (--n);
   1166 
   1167             n = wsize;
   1168             p = &s->prev[n];
   1169             do {
   1170                 m = *--p;
   1171                 *p = (Pos)(m >= wsize ? m-wsize : NIL);
   1172                 /* If n is not on any hash chain, prev[n] is garbage but
   1173                  * its value will never be used.
   1174                  */
   1175             } while (--n);
   1176 
   1177             more += wsize;
   1178         }
   1179         if (s->strm->avail_in == 0) return;
   1180 
   1181         /* If there was no sliding:
   1182          *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
   1183          *    more == window_size - lookahead - strstart
   1184          * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
   1185          * => more >= window_size - 2*WSIZE + 2
   1186          * In the BIG_MEM or MMAP case (not yet supported),
   1187          *   window_size == input_size + MIN_LOOKAHEAD  &&
   1188          *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
   1189          * Otherwise, window_size == 2*WSIZE so more >= 2.
   1190          * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
   1191          */
   1192         Assert(more >= 2, "more < 2");
   1193 
   1194         n = read_buf(s->strm, (charf *)s->window + s->strstart + s->lookahead,
   1195                      more);
   1196         s->lookahead += n;
   1197 
   1198         /* Initialize the hash value now that we have some input: */
   1199         if (s->lookahead >= MIN_MATCH) {
   1200             s->ins_h = s->window[s->strstart];
   1201             UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
   1202 #if MIN_MATCH != 3
   1203             Call UPDATE_HASH() MIN_MATCH-3 more times
   1204 #endif
   1205         }
   1206         /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
   1207          * but this is not important since only literal bytes will be emitted.
   1208          */
   1209 
   1210     } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
   1211 }
   1212 
   1213 /* ===========================================================================
   1214  * Flush the current block, with given end-of-file flag.
   1215  * IN assertion: strstart is set to the end of the current match.
   1216  */
   1217 #define FLUSH_BLOCK_ONLY(s, flush) { \
   1218    ct_flush_block(s, (s->block_start >= 0L ? \
   1219            (charf *)&s->window[(unsigned)s->block_start] : \
   1220            (charf *)Z_NULL), (long)s->strstart - s->block_start, (flush)); \
   1221    s->block_start = s->strstart; \
   1222    flush_pending(s->strm); \
   1223    Tracev((stderr,"[FLUSH]")); \
   1224 }
   1225 
   1226 /* Same but force premature exit if necessary. */
   1227 #define FLUSH_BLOCK(s, flush) { \
   1228    FLUSH_BLOCK_ONLY(s, flush); \
   1229    if (s->strm->avail_out == 0) return 1; \
   1230 }
   1231 
   1232 /* ===========================================================================
   1233  * Compress as much as possible from the input stream, return true if
   1234  * processing was terminated prematurely (no more input or output space).
   1235  * This function does not perform lazy evaluationof matches and inserts
   1236  * new strings in the dictionary only for unmatched strings or for short
   1237  * matches. It is used only for the fast compression options.
   1238  */
   1239 local int deflate_fast(s, flush)
   1240     deflate_state *s;
   1241     int flush;
   1242 {
   1243     IPos hash_head = NIL; /* head of the hash chain */
   1244     int bflush;     /* set if current block must be flushed */
   1245 
   1246     s->prev_length = MIN_MATCH-1;
   1247 
   1248     for (;;) {
   1249         /* Make sure that we always have enough lookahead, except
   1250          * at the end of the input file. We need MAX_MATCH bytes
   1251          * for the next match, plus MIN_MATCH bytes to insert the
   1252          * string following the next match.
   1253          */
   1254         if (s->lookahead < MIN_LOOKAHEAD) {
   1255             fill_window(s);
   1256             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
   1257 
   1258             if (s->lookahead == 0) break; /* flush the current block */
   1259         }
   1260 
   1261         /* Insert the string window[strstart .. strstart+2] in the
   1262          * dictionary, and set hash_head to the head of the hash chain:
   1263          */
   1264         if (s->lookahead >= MIN_MATCH) {
   1265             INSERT_STRING(s, s->strstart, hash_head);
   1266         }
   1267 
   1268         /* Find the longest match, discarding those <= prev_length.
   1269          * At this point we have always match_length < MIN_MATCH
   1270          */
   1271         if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
   1272             /* To simplify the code, we prevent matches with the string
   1273              * of window index 0 (in particular we have to avoid a match
   1274              * of the string with itself at the start of the input file).
   1275              */
   1276             if (s->strategy != Z_HUFFMAN_ONLY) {
   1277                 s->match_length = longest_match (s, hash_head);
   1278             }
   1279             /* longest_match() sets match_start */
   1280 
   1281             if (s->match_length > s->lookahead) s->match_length = s->lookahead;
   1282         }
   1283         if (s->match_length >= MIN_MATCH) {
   1284             check_match(s, s->strstart, s->match_start, s->match_length);
   1285 
   1286             bflush = ct_tally(s, s->strstart - s->match_start,
   1287                               s->match_length - MIN_MATCH);
   1288 
   1289             s->lookahead -= s->match_length;
   1290 
   1291             /* Insert new strings in the hash table only if the match length
   1292              * is not too large. This saves time but degrades compression.
   1293              */
   1294             if (s->match_length <= s->max_insert_length &&
   1295                 s->lookahead >= MIN_MATCH) {
   1296                 s->match_length--; /* string at strstart already in hash table */
   1297                 do {
   1298                     s->strstart++;
   1299                     INSERT_STRING(s, s->strstart, hash_head);
   1300                     /* strstart never exceeds WSIZE-MAX_MATCH, so there are
   1301                      * always MIN_MATCH bytes ahead.
   1302                      */
   1303                 } while (--s->match_length != 0);
   1304                 s->strstart++;
   1305             } else {
   1306                 s->strstart += s->match_length;
   1307                 s->match_length = 0;
   1308                 s->ins_h = s->window[s->strstart];
   1309                 UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
   1310 #if MIN_MATCH != 3
   1311                 Call UPDATE_HASH() MIN_MATCH-3 more times
   1312 #endif
   1313                 /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
   1314                  * matter since it will be recomputed at next deflate call.
   1315                  */
   1316             }
   1317         } else {
   1318             /* No match, output a literal byte */
   1319             Tracevv((stderr,"%c", s->window[s->strstart]));
   1320             bflush = ct_tally (s, 0, s->window[s->strstart]);
   1321             s->lookahead--;
   1322             s->strstart++;
   1323         }
   1324         if (bflush) FLUSH_BLOCK(s, Z_NO_FLUSH);
   1325     }
   1326     FLUSH_BLOCK(s, flush);
   1327     return 0; /* normal exit */
   1328 }
   1329 
   1330 /* ===========================================================================
   1331  * Same as above, but achieves better compression. We use a lazy
   1332  * evaluation for matches: a match is finally adopted only if there is
   1333  * no better match at the next window position.
   1334  */
   1335 local int deflate_slow(s, flush)
   1336     deflate_state *s;
   1337     int flush;
   1338 {
   1339     IPos hash_head = NIL;    /* head of hash chain */
   1340     int bflush;              /* set if current block must be flushed */
   1341 
   1342     /* Process the input block. */
   1343     for (;;) {
   1344         /* Make sure that we always have enough lookahead, except
   1345          * at the end of the input file. We need MAX_MATCH bytes
   1346          * for the next match, plus MIN_MATCH bytes to insert the
   1347          * string following the next match.
   1348          */
   1349         if (s->lookahead < MIN_LOOKAHEAD) {
   1350             fill_window(s);
   1351             if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) return 1;
   1352 
   1353             if (s->lookahead == 0) break; /* flush the current block */
   1354         }
   1355 
   1356         /* Insert the string window[strstart .. strstart+2] in the
   1357          * dictionary, and set hash_head to the head of the hash chain:
   1358          */
   1359         if (s->lookahead >= MIN_MATCH) {
   1360             INSERT_STRING(s, s->strstart, hash_head);
   1361         }
   1362 
   1363         /* Find the longest match, discarding those <= prev_length.
   1364          */
   1365         s->prev_length = s->match_length, s->prev_match = s->match_start;
   1366         s->match_length = MIN_MATCH-1;
   1367 
   1368         if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
   1369             s->strstart - hash_head <= MAX_DIST(s)) {
   1370             /* To simplify the code, we prevent matches with the string
   1371              * of window index 0 (in particular we have to avoid a match
   1372              * of the string with itself at the start of the input file).
   1373              */
   1374             if (s->strategy != Z_HUFFMAN_ONLY) {
   1375                 s->match_length = longest_match (s, hash_head);
   1376             }
   1377             /* longest_match() sets match_start */
   1378             if (s->match_length > s->lookahead) s->match_length = s->lookahead;
   1379 
   1380             if (s->match_length <= 5 && (s->strategy == Z_FILTERED ||
   1381                  (s->match_length == MIN_MATCH &&
   1382                   s->strstart - s->match_start > TOO_FAR))) {
   1383 
   1384                 /* If prev_match is also MIN_MATCH, match_start is garbage
   1385                  * but we will ignore the current match anyway.
   1386                  */
   1387                 s->match_length = MIN_MATCH-1;
   1388             }
   1389         }
   1390         /* If there was a match at the previous step and the current
   1391          * match is not better, output the previous match:
   1392          */
   1393         if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
   1394             uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
   1395             /* Do not insert strings in hash table beyond this. */
   1396 
   1397             check_match(s, s->strstart-1, s->prev_match, s->prev_length);
   1398 
   1399             bflush = ct_tally(s, s->strstart -1 - s->prev_match,
   1400                               s->prev_length - MIN_MATCH);
   1401 
   1402             /* Insert in hash table all strings up to the end of the match.
   1403              * strstart-1 and strstart are already inserted. If there is not
   1404              * enough lookahead, the last two strings are not inserted in
   1405              * the hash table.
   1406              */
   1407             s->lookahead -= s->prev_length-1;
   1408             s->prev_length -= 2;
   1409             do {
   1410                 if (++s->strstart <= max_insert) {
   1411                     INSERT_STRING(s, s->strstart, hash_head);
   1412                 }
   1413             } while (--s->prev_length != 0);
   1414             s->match_available = 0;
   1415             s->match_length = MIN_MATCH-1;
   1416             s->strstart++;
   1417 
   1418             if (bflush) FLUSH_BLOCK(s, Z_NO_FLUSH);
   1419 
   1420         } else if (s->match_available) {
   1421             /* If there was no match at the previous position, output a
   1422              * single literal. If there was a match but the current match
   1423              * is longer, truncate the previous match to a single literal.
   1424              */
   1425             Tracevv((stderr,"%c", s->window[s->strstart-1]));
   1426             if (ct_tally (s, 0, s->window[s->strstart-1])) {
   1427                 FLUSH_BLOCK_ONLY(s, Z_NO_FLUSH);
   1428             }
   1429             s->strstart++;
   1430             s->lookahead--;
   1431             if (s->strm->avail_out == 0) return 1;
   1432         } else {
   1433             /* There is no previous match to compare with, wait for
   1434              * the next step to decide.
   1435              */
   1436             s->match_available = 1;
   1437             s->strstart++;
   1438             s->lookahead--;
   1439         }
   1440     }
   1441     Assert (flush != Z_NO_FLUSH, "no flush?");
   1442     if (s->match_available) {
   1443         Tracevv((stderr,"%c", s->window[s->strstart-1]));
   1444         ct_tally (s, 0, s->window[s->strstart-1]);
   1445         s->match_available = 0;
   1446     }
   1447     FLUSH_BLOCK(s, flush);
   1448     return 0;
   1449 }
   1450 
   1451 
   1452 /*+++++*/
   1453 /* trees.c -- output deflated data using Huffman coding
   1454  * Copyright (C) 1995 Jean-loup Gailly
   1455  * For conditions of distribution and use, see copyright notice in zlib.h
   1456  */
   1457 
   1458 /*
   1459  *  ALGORITHM
   1460  *
   1461  *      The "deflation" process uses several Huffman trees. The more
   1462  *      common source values are represented by shorter bit sequences.
   1463  *
   1464  *      Each code tree is stored in a compressed form which is itself
   1465  * a Huffman encoding of the lengths of all the code strings (in
   1466  * ascending order by source values).  The actual code strings are
   1467  * reconstructed from the lengths in the inflate process, as described
   1468  * in the deflate specification.
   1469  *
   1470  *  REFERENCES
   1471  *
   1472  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
   1473  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
   1474  *
   1475  *      Storer, James A.
   1476  *          Data Compression:  Methods and Theory, pp. 49-50.
   1477  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
   1478  *
   1479  *      Sedgewick, R.
   1480  *          Algorithms, p290.
   1481  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
   1482  */
   1483 
   1484 /* From: trees.c,v 1.5 1995/05/03 17:27:12 jloup Exp */
   1485 
   1486 #ifdef DEBUG_ZLIB
   1487 #  include <ctype.h>
   1488 #endif
   1489 
   1490 /* ===========================================================================
   1491  * Constants
   1492  */
   1493 
   1494 #define MAX_BL_BITS 7
   1495 /* Bit length codes must not exceed MAX_BL_BITS bits */
   1496 
   1497 #define END_BLOCK 256
   1498 /* end of block literal code */
   1499 
   1500 #define REP_3_6      16
   1501 /* repeat previous bit length 3-6 times (2 bits of repeat count) */
   1502 
   1503 #define REPZ_3_10    17
   1504 /* repeat a zero length 3-10 times  (3 bits of repeat count) */
   1505 
   1506 #define REPZ_11_138  18
   1507 /* repeat a zero length 11-138 times  (7 bits of repeat count) */
   1508 
   1509 local int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
   1510    = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
   1511 
   1512 local int extra_dbits[D_CODES] /* extra bits for each distance code */
   1513    = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
   1514 
   1515 local int extra_blbits[BL_CODES]/* extra bits for each bit length code */
   1516    = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
   1517 
   1518 local uch bl_order[BL_CODES]
   1519    = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
   1520 /* The lengths of the bit length codes are sent in order of decreasing
   1521  * probability, to avoid transmitting the lengths for unused bit length codes.
   1522  */
   1523 
   1524 #define Buf_size (8 * 2*sizeof(char))
   1525 /* Number of bits used within bi_buf. (bi_buf might be implemented on
   1526  * more than 16 bits on some systems.)
   1527  */
   1528 
   1529 /* ===========================================================================
   1530  * Local data. These are initialized only once.
   1531  * To do: initialize at compile time to be completely reentrant. ???
   1532  */
   1533 
   1534 local ct_data static_ltree[L_CODES+2];
   1535 /* The static literal tree. Since the bit lengths are imposed, there is no
   1536  * need for the L_CODES extra codes used during heap construction. However
   1537  * The codes 286 and 287 are needed to build a canonical tree (see ct_init
   1538  * below).
   1539  */
   1540 
   1541 local ct_data static_dtree[D_CODES];
   1542 /* The static distance tree. (Actually a trivial tree since all codes use
   1543  * 5 bits.)
   1544  */
   1545 
   1546 local uch dist_code[512];
   1547 /* distance codes. The first 256 values correspond to the distances
   1548  * 3 .. 258, the last 256 values correspond to the top 8 bits of
   1549  * the 15 bit distances.
   1550  */
   1551 
   1552 local uch length_code[MAX_MATCH-MIN_MATCH+1];
   1553 /* length code for each normalized match length (0 == MIN_MATCH) */
   1554 
   1555 local int base_length[LENGTH_CODES];
   1556 /* First normalized length for each code (0 = MIN_MATCH) */
   1557 
   1558 local int base_dist[D_CODES];
   1559 /* First normalized distance for each code (0 = distance of 1) */
   1560 
   1561 struct static_tree_desc_s {
   1562     ct_data *static_tree;        /* static tree or NULL */
   1563     intf    *extra_bits;         /* extra bits for each code or NULL */
   1564     int     extra_base;          /* base index for extra_bits */
   1565     int     elems;               /* max number of elements in the tree */
   1566     int     max_length;          /* max bit length for the codes */
   1567 };
   1568 
   1569 local static_tree_desc  static_l_desc =
   1570 {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
   1571 
   1572 local static_tree_desc  static_d_desc =
   1573 {static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
   1574 
   1575 local static_tree_desc  static_bl_desc =
   1576 {(ct_data *)0, extra_blbits, 0,      BL_CODES, MAX_BL_BITS};
   1577 
   1578 /* ===========================================================================
   1579  * Local (static) routines in this file.
   1580  */
   1581 
   1582 local void ct_static_init OF((void));
   1583 local void init_block     OF((deflate_state *s));
   1584 local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
   1585 local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
   1586 local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
   1587 local void build_tree     OF((deflate_state *s, tree_desc *desc));
   1588 local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
   1589 local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
   1590 local int  build_bl_tree  OF((deflate_state *s));
   1591 local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
   1592                               int blcodes));
   1593 local void compress_block OF((deflate_state *s, ct_data *ltree,
   1594                               ct_data *dtree));
   1595 local void set_data_type  OF((deflate_state *s));
   1596 local unsigned bi_reverse OF((unsigned value, int length));
   1597 local void bi_windup      OF((deflate_state *s));
   1598 local void bi_flush       OF((deflate_state *s));
   1599 local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
   1600                               int header));
   1601 
   1602 #ifndef DEBUG_ZLIB
   1603 #  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
   1604    /* Send a code of the given tree. c and tree must not have side effects */
   1605 
   1606 #else /* DEBUG_ZLIB */
   1607 #  define send_code(s, c, tree) \
   1608      { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \
   1609        send_bits(s, tree[c].Code, tree[c].Len); }
   1610 #endif
   1611 
   1612 #define d_code(dist) \
   1613    ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
   1614 /* Mapping from a distance to a distance code. dist is the distance - 1 and
   1615  * must not have side effects. dist_code[256] and dist_code[257] are never
   1616  * used.
   1617  */
   1618 
   1619 /* ===========================================================================
   1620  * Output a short LSB first on the stream.
   1621  * IN assertion: there is enough room in pendingBuf.
   1622  */
   1623 #define put_short(s, w) { \
   1624     put_byte(s, (uch)((w) & 0xff)); \
   1625     put_byte(s, (uch)((ush)(w) >> 8)); \
   1626 }
   1627 
   1628 /* ===========================================================================
   1629  * Send a value on a given number of bits.
   1630  * IN assertion: length <= 16 and value fits in length bits.
   1631  */
   1632 #ifdef DEBUG_ZLIB
   1633 local void send_bits      OF((deflate_state *s, int value, int length));
   1634 
   1635 local void send_bits(s, value, length)
   1636     deflate_state *s;
   1637     int value;  /* value to send */
   1638     int length; /* number of bits */
   1639 {
   1640     Tracev((stderr," l %2d v %4x ", length, value));
   1641     Assert(length > 0 && length <= 15, "invalid length");
   1642     s->bits_sent += (ulg)length;
   1643 
   1644     /* If not enough room in bi_buf, use (valid) bits from bi_buf and
   1645      * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
   1646      * unused bits in value.
   1647      */
   1648     if (s->bi_valid > (int)Buf_size - length) {
   1649         s->bi_buf |= (value << s->bi_valid);
   1650         put_short(s, s->bi_buf);
   1651         s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
   1652         s->bi_valid += length - Buf_size;
   1653     } else {
   1654         s->bi_buf |= value << s->bi_valid;
   1655         s->bi_valid += length;
   1656     }
   1657 }
   1658 #else /* !DEBUG_ZLIB */
   1659 
   1660 #define send_bits(s, value, length) \
   1661 { int len = length;\
   1662   if (s->bi_valid > (int)Buf_size - len) {\
   1663     int val = value;\
   1664     s->bi_buf |= (val << s->bi_valid);\
   1665     put_short(s, s->bi_buf);\
   1666     s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
   1667     s->bi_valid += len - Buf_size;\
   1668   } else {\
   1669     s->bi_buf |= (value) << s->bi_valid;\
   1670     s->bi_valid += len;\
   1671   }\
   1672 }
   1673 #endif /* DEBUG_ZLIB */
   1674 
   1675 
   1676 #define MAX(a,b) (a >= b ? a : b)
   1677 /* the arguments must not have side effects */
   1678 
   1679 /* ===========================================================================
   1680  * Initialize the various 'constant' tables.
   1681  * To do: do this at compile time.
   1682  */
   1683 local void ct_static_init()
   1684 {
   1685     int n;        /* iterates over tree elements */
   1686     int bits;     /* bit counter */
   1687     int length;   /* length value */
   1688     int code;     /* code value */
   1689     int dist;     /* distance index */
   1690     ush bl_count[MAX_BITS+1];
   1691     /* number of codes at each bit length for an optimal tree */
   1692 
   1693     /* Initialize the mapping length (0..255) -> length code (0..28) */
   1694     length = 0;
   1695     for (code = 0; code < LENGTH_CODES-1; code++) {
   1696         base_length[code] = length;
   1697         for (n = 0; n < (1<<extra_lbits[code]); n++) {
   1698             length_code[length++] = (uch)code;
   1699         }
   1700     }
   1701     Assert (length == 256, "ct_static_init: length != 256");
   1702     /* Note that the length 255 (match length 258) can be represented
   1703      * in two different ways: code 284 + 5 bits or code 285, so we
   1704      * overwrite length_code[255] to use the best encoding:
   1705      */
   1706     length_code[length-1] = (uch)code;
   1707 
   1708     /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
   1709     dist = 0;
   1710     for (code = 0 ; code < 16; code++) {
   1711         base_dist[code] = dist;
   1712         for (n = 0; n < (1<<extra_dbits[code]); n++) {
   1713             dist_code[dist++] = (uch)code;
   1714         }
   1715     }
   1716     Assert (dist == 256, "ct_static_init: dist != 256");
   1717     dist >>= 7; /* from now on, all distances are divided by 128 */
   1718     for ( ; code < D_CODES; code++) {
   1719         base_dist[code] = dist << 7;
   1720         for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
   1721             dist_code[256 + dist++] = (uch)code;
   1722         }
   1723     }
   1724     Assert (dist == 256, "ct_static_init: 256+dist != 512");
   1725 
   1726     /* Construct the codes of the static literal tree */
   1727     for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
   1728     n = 0;
   1729     while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
   1730     while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
   1731     while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
   1732     while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
   1733     /* Codes 286 and 287 do not exist, but we must include them in the
   1734      * tree construction to get a canonical Huffman tree (longest code
   1735      * all ones)
   1736      */
   1737     gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
   1738 
   1739     /* The static distance tree is trivial: */
   1740     for (n = 0; n < D_CODES; n++) {
   1741         static_dtree[n].Len = 5;
   1742         static_dtree[n].Code = bi_reverse(n, 5);
   1743     }
   1744 }
   1745 
   1746 /* ===========================================================================
   1747  * Initialize the tree data structures for a new zlib stream.
   1748  */
   1749 local void ct_init(s)
   1750     deflate_state *s;
   1751 {
   1752     if (static_dtree[0].Len == 0) {
   1753         ct_static_init();              /* To do: at compile time */
   1754     }
   1755 
   1756     s->compressed_len = 0L;
   1757 
   1758     s->l_desc.dyn_tree = s->dyn_ltree;
   1759     s->l_desc.stat_desc = &static_l_desc;
   1760 
   1761     s->d_desc.dyn_tree = s->dyn_dtree;
   1762     s->d_desc.stat_desc = &static_d_desc;
   1763 
   1764     s->bl_desc.dyn_tree = s->bl_tree;
   1765     s->bl_desc.stat_desc = &static_bl_desc;
   1766 
   1767     s->bi_buf = 0;
   1768     s->bi_valid = 0;
   1769     s->last_eob_len = 8; /* enough lookahead for inflate */
   1770 #ifdef DEBUG_ZLIB
   1771     s->bits_sent = 0L;
   1772 #endif
   1773     s->blocks_in_packet = 0;
   1774 
   1775     /* Initialize the first block of the first file: */
   1776     init_block(s);
   1777 }
   1778 
   1779 /* ===========================================================================
   1780  * Initialize a new block.
   1781  */
   1782 local void init_block(s)
   1783     deflate_state *s;
   1784 {
   1785     int n; /* iterates over tree elements */
   1786 
   1787     /* Initialize the trees. */
   1788     for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
   1789     for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
   1790     for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
   1791 
   1792     s->dyn_ltree[END_BLOCK].Freq = 1;
   1793     s->opt_len = s->static_len = 0L;
   1794     s->last_lit = s->matches = 0;
   1795 }
   1796 
   1797 #define SMALLEST 1
   1798 /* Index within the heap array of least frequent node in the Huffman tree */
   1799 
   1800 
   1801 /* ===========================================================================
   1802  * Remove the smallest element from the heap and recreate the heap with
   1803  * one less element. Updates heap and heap_len.
   1804  */
   1805 #define pqremove(s, tree, top) \
   1806 {\
   1807     top = s->heap[SMALLEST]; \
   1808     s->heap[SMALLEST] = s->heap[s->heap_len--]; \
   1809     pqdownheap(s, tree, SMALLEST); \
   1810 }
   1811 
   1812 /* ===========================================================================
   1813  * Compares to subtrees, using the tree depth as tie breaker when
   1814  * the subtrees have equal frequency. This minimizes the worst case length.
   1815  */
   1816 #define smaller(tree, n, m, depth) \
   1817    (tree[n].Freq < tree[m].Freq || \
   1818    (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
   1819 
   1820 /* ===========================================================================
   1821  * Restore the heap property by moving down the tree starting at node k,
   1822  * exchanging a node with the smallest of its two sons if necessary, stopping
   1823  * when the heap property is re-established (each father smaller than its
   1824  * two sons).
   1825  */
   1826 local void pqdownheap(s, tree, k)
   1827     deflate_state *s;
   1828     ct_data *tree;  /* the tree to restore */
   1829     int k;               /* node to move down */
   1830 {
   1831     int v = s->heap[k];
   1832     int j = k << 1;  /* left son of k */
   1833     while (j <= s->heap_len) {
   1834         /* Set j to the smallest of the two sons: */
   1835         if (j < s->heap_len &&
   1836             smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
   1837             j++;
   1838         }
   1839         /* Exit if v is smaller than both sons */
   1840         if (smaller(tree, v, s->heap[j], s->depth)) break;
   1841 
   1842         /* Exchange v with the smallest son */
   1843         s->heap[k] = s->heap[j];  k = j;
   1844 
   1845         /* And continue down the tree, setting j to the left son of k */
   1846         j <<= 1;
   1847     }
   1848     s->heap[k] = v;
   1849 }
   1850 
   1851 /* ===========================================================================
   1852  * Compute the optimal bit lengths for a tree and update the total bit length
   1853  * for the current block.
   1854  * IN assertion: the fields freq and dad are set, heap[heap_max] and
   1855  *    above are the tree nodes sorted by increasing frequency.
   1856  * OUT assertions: the field len is set to the optimal bit length, the
   1857  *     array bl_count contains the frequencies for each bit length.
   1858  *     The length opt_len is updated; static_len is also updated if stree is
   1859  *     not null.
   1860  */
   1861 local void gen_bitlen(s, desc)
   1862     deflate_state *s;
   1863     tree_desc *desc;    /* the tree descriptor */
   1864 {
   1865     ct_data *tree  = desc->dyn_tree;
   1866     int max_code   = desc->max_code;
   1867     ct_data *stree = desc->stat_desc->static_tree;
   1868     intf *extra    = desc->stat_desc->extra_bits;
   1869     int base       = desc->stat_desc->extra_base;
   1870     int max_length = desc->stat_desc->max_length;
   1871     int h;              /* heap index */
   1872     int n, m;           /* iterate over the tree elements */
   1873     int bits;           /* bit length */
   1874     int xbits;          /* extra bits */
   1875     ush f;              /* frequency */
   1876     int overflow = 0;   /* number of elements with bit length too large */
   1877 
   1878     for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
   1879 
   1880     /* In a first pass, compute the optimal bit lengths (which may
   1881      * overflow in the case of the bit length tree).
   1882      */
   1883     tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
   1884 
   1885     for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
   1886         n = s->heap[h];
   1887         bits = tree[tree[n].Dad].Len + 1;
   1888         if (bits > max_length) bits = max_length, overflow++;
   1889         tree[n].Len = (ush)bits;
   1890         /* We overwrite tree[n].Dad which is no longer needed */
   1891 
   1892         if (n > max_code) continue; /* not a leaf node */
   1893 
   1894         s->bl_count[bits]++;
   1895         xbits = 0;
   1896         if (n >= base) xbits = extra[n-base];
   1897         f = tree[n].Freq;
   1898         s->opt_len += (ulg)f * (bits + xbits);
   1899         if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
   1900     }
   1901     if (overflow == 0) return;
   1902 
   1903     Trace((stderr,"\nbit length overflow\n"));
   1904     /* This happens for example on obj2 and pic of the Calgary corpus */
   1905 
   1906     /* Find the first bit length which could increase: */
   1907     do {
   1908         bits = max_length-1;
   1909         while (s->bl_count[bits] == 0) bits--;
   1910         s->bl_count[bits]--;      /* move one leaf down the tree */
   1911         s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
   1912         s->bl_count[max_length]--;
   1913         /* The brother of the overflow item also moves one step up,
   1914          * but this does not affect bl_count[max_length]
   1915          */
   1916         overflow -= 2;
   1917     } while (overflow > 0);
   1918 
   1919     /* Now recompute all bit lengths, scanning in increasing frequency.
   1920      * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
   1921      * lengths instead of fixing only the wrong ones. This idea is taken
   1922      * from 'ar' written by Haruhiko Okumura.)
   1923      */
   1924     for (bits = max_length; bits != 0; bits--) {
   1925         n = s->bl_count[bits];
   1926         while (n != 0) {
   1927             m = s->heap[--h];
   1928             if (m > max_code) continue;
   1929             if (tree[m].Len != (unsigned) bits) {
   1930                 Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
   1931                 s->opt_len += ((long)bits - (long)tree[m].Len)
   1932                               *(long)tree[m].Freq;
   1933                 tree[m].Len = (ush)bits;
   1934             }
   1935             n--;
   1936         }
   1937     }
   1938 }
   1939 
   1940 /* ===========================================================================
   1941  * Generate the codes for a given tree and bit counts (which need not be
   1942  * optimal).
   1943  * IN assertion: the array bl_count contains the bit length statistics for
   1944  * the given tree and the field len is set for all tree elements.
   1945  * OUT assertion: the field code is set for all tree elements of non
   1946  *     zero code length.
   1947  */
   1948 local void gen_codes (tree, max_code, bl_count)
   1949     ct_data *tree;             /* the tree to decorate */
   1950     int max_code;              /* largest code with non zero frequency */
   1951     ushf *bl_count;            /* number of codes at each bit length */
   1952 {
   1953     ush next_code[MAX_BITS+1]; /* next code value for each bit length */
   1954     ush code = 0;              /* running code value */
   1955     int bits;                  /* bit index */
   1956     int n;                     /* code index */
   1957 
   1958     /* The distribution counts are first used to generate the code values
   1959      * without bit reversal.
   1960      */
   1961     for (bits = 1; bits <= MAX_BITS; bits++) {
   1962         next_code[bits] = code = (code + bl_count[bits-1]) << 1;
   1963     }
   1964     /* Check that the bit counts in bl_count are consistent. The last code
   1965      * must be all ones.
   1966      */
   1967     Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
   1968             "inconsistent bit counts");
   1969     Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
   1970 
   1971     for (n = 0;  n <= max_code; n++) {
   1972         int len = tree[n].Len;
   1973         if (len == 0) continue;
   1974         /* Now reverse the bits */
   1975         tree[n].Code = bi_reverse(next_code[len]++, len);
   1976 
   1977         Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
   1978              n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
   1979     }
   1980 }
   1981 
   1982 /* ===========================================================================
   1983  * Construct one Huffman tree and assigns the code bit strings and lengths.
   1984  * Update the total bit length for the current block.
   1985  * IN assertion: the field freq is set for all tree elements.
   1986  * OUT assertions: the fields len and code are set to the optimal bit length
   1987  *     and corresponding code. The length opt_len is updated; static_len is
   1988  *     also updated if stree is not null. The field max_code is set.
   1989  */
   1990 local void build_tree(s, desc)
   1991     deflate_state *s;
   1992     tree_desc *desc; /* the tree descriptor */
   1993 {
   1994     ct_data *tree   = desc->dyn_tree;
   1995     ct_data *stree  = desc->stat_desc->static_tree;
   1996     int elems       = desc->stat_desc->elems;
   1997     int n, m;          /* iterate over heap elements */
   1998     int max_code = -1; /* largest code with non zero frequency */
   1999     int node;          /* new node being created */
   2000 
   2001     /* Construct the initial heap, with least frequent element in
   2002      * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
   2003      * heap[0] is not used.
   2004      */
   2005     s->heap_len = 0, s->heap_max = HEAP_SIZE;
   2006 
   2007     for (n = 0; n < elems; n++) {
   2008         if (tree[n].Freq != 0) {
   2009             s->heap[++(s->heap_len)] = max_code = n;
   2010             s->depth[n] = 0;
   2011         } else {
   2012             tree[n].Len = 0;
   2013         }
   2014     }
   2015 
   2016     /* The pkzip format requires that at least one distance code exists,
   2017      * and that at least one bit should be sent even if there is only one
   2018      * possible code. So to avoid special checks later on we force at least
   2019      * two codes of non zero frequency.
   2020      */
   2021     while (s->heap_len < 2) {
   2022         node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
   2023         tree[node].Freq = 1;
   2024         s->depth[node] = 0;
   2025         s->opt_len--; if (stree) s->static_len -= stree[node].Len;
   2026         /* node is 0 or 1 so it does not have extra bits */
   2027     }
   2028     desc->max_code = max_code;
   2029 
   2030     /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
   2031      * establish sub-heaps of increasing lengths:
   2032      */
   2033     for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
   2034 
   2035     /* Construct the Huffman tree by repeatedly combining the least two
   2036      * frequent nodes.
   2037      */
   2038     node = elems;              /* next internal node of the tree */
   2039     do {
   2040         pqremove(s, tree, n);  /* n = node of least frequency */
   2041         m = s->heap[SMALLEST]; /* m = node of next least frequency */
   2042 
   2043         s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
   2044         s->heap[--(s->heap_max)] = m;
   2045 
   2046         /* Create a new node father of n and m */
   2047         tree[node].Freq = tree[n].Freq + tree[m].Freq;
   2048         s->depth[node] = (uch) (MAX(s->depth[n], s->depth[m]) + 1);
   2049         tree[n].Dad = tree[m].Dad = (ush)node;
   2050 #ifdef DUMP_BL_TREE
   2051         if (tree == s->bl_tree) {
   2052             fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
   2053                     node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
   2054         }
   2055 #endif
   2056         /* and insert the new node in the heap */
   2057         s->heap[SMALLEST] = node++;
   2058         pqdownheap(s, tree, SMALLEST);
   2059 
   2060     } while (s->heap_len >= 2);
   2061 
   2062     s->heap[--(s->heap_max)] = s->heap[SMALLEST];
   2063 
   2064     /* At this point, the fields freq and dad are set. We can now
   2065      * generate the bit lengths.
   2066      */
   2067     gen_bitlen(s, (tree_desc *)desc);
   2068 
   2069     /* The field len is now set, we can generate the bit codes */
   2070     gen_codes ((ct_data *)tree, max_code, s->bl_count);
   2071 }
   2072 
   2073 /* ===========================================================================
   2074  * Scan a literal or distance tree to determine the frequencies of the codes
   2075  * in the bit length tree.
   2076  */
   2077 local void scan_tree (s, tree, max_code)
   2078     deflate_state *s;
   2079     ct_data *tree;   /* the tree to be scanned */
   2080     int max_code;    /* and its largest code of non zero frequency */
   2081 {
   2082     int n;                     /* iterates over all tree elements */
   2083     int prevlen = -1;          /* last emitted length */
   2084     int curlen;                /* length of current code */
   2085     int nextlen = tree[0].Len; /* length of next code */
   2086     int count = 0;             /* repeat count of the current code */
   2087     int max_count = 7;         /* max repeat count */
   2088     int min_count = 4;         /* min repeat count */
   2089 
   2090     if (nextlen == 0) max_count = 138, min_count = 3;
   2091     tree[max_code+1].Len = (ush)0xffff; /* guard */
   2092 
   2093     for (n = 0; n <= max_code; n++) {
   2094         curlen = nextlen; nextlen = tree[n+1].Len;
   2095         if (++count < max_count && curlen == nextlen) {
   2096             continue;
   2097         } else if (count < min_count) {
   2098             s->bl_tree[curlen].Freq += count;
   2099         } else if (curlen != 0) {
   2100             if (curlen != prevlen) s->bl_tree[curlen].Freq++;
   2101             s->bl_tree[REP_3_6].Freq++;
   2102         } else if (count <= 10) {
   2103             s->bl_tree[REPZ_3_10].Freq++;
   2104         } else {
   2105             s->bl_tree[REPZ_11_138].Freq++;
   2106         }
   2107         count = 0; prevlen = curlen;
   2108         if (nextlen == 0) {
   2109             max_count = 138, min_count = 3;
   2110         } else if (curlen == nextlen) {
   2111             max_count = 6, min_count = 3;
   2112         } else {
   2113             max_count = 7, min_count = 4;
   2114         }
   2115     }
   2116 }
   2117 
   2118 /* ===========================================================================
   2119  * Send a literal or distance tree in compressed form, using the codes in
   2120  * bl_tree.
   2121  */
   2122 local void send_tree (s, tree, max_code)
   2123     deflate_state *s;
   2124     ct_data *tree; /* the tree to be scanned */
   2125     int max_code;       /* and its largest code of non zero frequency */
   2126 {
   2127     int n;                     /* iterates over all tree elements */
   2128     int prevlen = -1;          /* last emitted length */
   2129     int curlen;                /* length of current code */
   2130     int nextlen = tree[0].Len; /* length of next code */
   2131     int count = 0;             /* repeat count of the current code */
   2132     int max_count = 7;         /* max repeat count */
   2133     int min_count = 4;         /* min repeat count */
   2134 
   2135     /* tree[max_code+1].Len = -1; */  /* guard already set */
   2136     if (nextlen == 0) max_count = 138, min_count = 3;
   2137 
   2138     for (n = 0; n <= max_code; n++) {
   2139         curlen = nextlen; nextlen = tree[n+1].Len;
   2140         if (++count < max_count && curlen == nextlen) {
   2141             continue;
   2142         } else if (count < min_count) {
   2143             do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
   2144 
   2145         } else if (curlen != 0) {
   2146             if (curlen != prevlen) {
   2147                 send_code(s, curlen, s->bl_tree); count--;
   2148             }
   2149             Assert(count >= 3 && count <= 6, " 3_6?");
   2150             send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
   2151 
   2152         } else if (count <= 10) {
   2153             send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
   2154 
   2155         } else {
   2156             send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
   2157         }
   2158         count = 0; prevlen = curlen;
   2159         if (nextlen == 0) {
   2160             max_count = 138, min_count = 3;
   2161         } else if (curlen == nextlen) {
   2162             max_count = 6, min_count = 3;
   2163         } else {
   2164             max_count = 7, min_count = 4;
   2165         }
   2166     }
   2167 }
   2168 
   2169 /* ===========================================================================
   2170  * Construct the Huffman tree for the bit lengths and return the index in
   2171  * bl_order of the last bit length code to send.
   2172  */
   2173 local int build_bl_tree(s)
   2174     deflate_state *s;
   2175 {
   2176     int max_blindex;  /* index of last bit length code of non zero freq */
   2177 
   2178     /* Determine the bit length frequencies for literal and distance trees */
   2179     scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
   2180     scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
   2181 
   2182     /* Build the bit length tree: */
   2183     build_tree(s, (tree_desc *)(&(s->bl_desc)));
   2184     /* opt_len now includes the length of the tree representations, except
   2185      * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
   2186      */
   2187 
   2188     /* Determine the number of bit length codes to send. The pkzip format
   2189      * requires that at least 4 bit length codes be sent. (appnote.txt says
   2190      * 3 but the actual value used is 4.)
   2191      */
   2192     for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
   2193         if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
   2194     }
   2195     /* Update opt_len to include the bit length tree and counts */
   2196     s->opt_len += 3*(max_blindex+1) + 5+5+4;
   2197     Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
   2198             s->opt_len, s->static_len));
   2199 
   2200     return max_blindex;
   2201 }
   2202 
   2203 /* ===========================================================================
   2204  * Send the header for a block using dynamic Huffman trees: the counts, the
   2205  * lengths of the bit length codes, the literal tree and the distance tree.
   2206  * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
   2207  */
   2208 local void send_all_trees(s, lcodes, dcodes, blcodes)
   2209     deflate_state *s;
   2210     int lcodes, dcodes, blcodes; /* number of codes for each tree */
   2211 {
   2212     int rank;                    /* index in bl_order */
   2213 
   2214     Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
   2215     Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
   2216             "too many codes");
   2217     Tracev((stderr, "\nbl counts: "));
   2218     send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
   2219     send_bits(s, dcodes-1,   5);
   2220     send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
   2221     for (rank = 0; rank < blcodes; rank++) {
   2222         Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
   2223         send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
   2224     }
   2225     Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
   2226 
   2227     send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
   2228     Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
   2229 
   2230     send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
   2231     Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
   2232 }
   2233 
   2234 /* ===========================================================================
   2235  * Send a stored block
   2236  */
   2237 local void ct_stored_block(s, buf, stored_len, eof)
   2238     deflate_state *s;
   2239     charf *buf;       /* input block */
   2240     ulg stored_len;   /* length of input block */
   2241     int eof;          /* true if this is the last block for a file */
   2242 {
   2243     send_bits(s, (STORED_BLOCK<<1)+eof, 3);  /* send block type */
   2244     s->compressed_len = (s->compressed_len + 3 + 7) & ~7L;
   2245     s->compressed_len += (stored_len + 4) << 3;
   2246 
   2247     copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
   2248 }
   2249 
   2250 /* Send just the `stored block' type code without any length bytes or data.
   2251  */
   2252 local void ct_stored_type_only(s)
   2253     deflate_state *s;
   2254 {
   2255     send_bits(s, (STORED_BLOCK << 1), 3);
   2256     bi_windup(s);
   2257     s->compressed_len = (s->compressed_len + 3) & ~7L;
   2258 }
   2259 
   2260 
   2261 /* ===========================================================================
   2262  * Send one empty static block to give enough lookahead for inflate.
   2263  * This takes 10 bits, of which 7 may remain in the bit buffer.
   2264  * The current inflate code requires 9 bits of lookahead. If the EOB
   2265  * code for the previous block was coded on 5 bits or less, inflate
   2266  * may have only 5+3 bits of lookahead to decode this EOB.
   2267  * (There are no problems if the previous block is stored or fixed.)
   2268  */
   2269 local void ct_align(s)
   2270     deflate_state *s;
   2271 {
   2272     send_bits(s, STATIC_TREES<<1, 3);
   2273     send_code(s, END_BLOCK, static_ltree);
   2274     s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
   2275     bi_flush(s);
   2276     /* Of the 10 bits for the empty block, we have already sent
   2277      * (10 - bi_valid) bits. The lookahead for the EOB of the previous
   2278      * block was thus its length plus what we have just sent.
   2279      */
   2280     if (s->last_eob_len + 10 - s->bi_valid < 9) {
   2281         send_bits(s, STATIC_TREES<<1, 3);
   2282         send_code(s, END_BLOCK, static_ltree);
   2283         s->compressed_len += 10L;
   2284         bi_flush(s);
   2285     }
   2286     s->last_eob_len = 7;
   2287 }
   2288 
   2289 /* ===========================================================================
   2290  * Determine the best encoding for the current block: dynamic trees, static
   2291  * trees or store, and output the encoded block to the zip file. This function
   2292  * returns the total compressed length for the file so far.
   2293  */
   2294 local ulg ct_flush_block(s, buf, stored_len, flush)
   2295     deflate_state *s;
   2296     charf *buf;       /* input block, or NULL if too old */
   2297     ulg stored_len;   /* length of input block */
   2298     int flush;        /* Z_FINISH if this is the last block for a file */
   2299 {
   2300     ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
   2301     int max_blindex;  /* index of last bit length code of non zero freq */
   2302     int eof = flush == Z_FINISH;
   2303 
   2304     ++s->blocks_in_packet;
   2305 
   2306     /* Check if the file is ascii or binary */
   2307     if (s->data_type == UNKNOWN) set_data_type(s);
   2308 
   2309     /* Construct the literal and distance trees */
   2310     build_tree(s, (tree_desc *)(&(s->l_desc)));
   2311     Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
   2312             s->static_len));
   2313 
   2314     build_tree(s, (tree_desc *)(&(s->d_desc)));
   2315     Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
   2316             s->static_len));
   2317     /* At this point, opt_len and static_len are the total bit lengths of
   2318      * the compressed block data, excluding the tree representations.
   2319      */
   2320 
   2321     /* Build the bit length tree for the above two trees, and get the index
   2322      * in bl_order of the last bit length code to send.
   2323      */
   2324     max_blindex = build_bl_tree(s);
   2325 
   2326     /* Determine the best encoding. Compute first the block length in bytes */
   2327     opt_lenb = (s->opt_len+3+7)>>3;
   2328     static_lenb = (s->static_len+3+7)>>3;
   2329 
   2330     Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
   2331             opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
   2332             s->last_lit));
   2333 
   2334     if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
   2335 
   2336     /* If compression failed and this is the first and last block,
   2337      * and if the .zip file can be seeked (to rewrite the local header),
   2338      * the whole file is transformed into a stored file:
   2339      */
   2340 #ifdef STORED_FILE_OK
   2341 #  ifdef FORCE_STORED_FILE
   2342     if (eof && compressed_len == 0L) /* force stored file */
   2343 #  else
   2344     if (stored_len <= opt_lenb && eof && s->compressed_len==0L && seekable())
   2345 #  endif
   2346     {
   2347         /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
   2348         if (buf == (charf*)0) error ("block vanished");
   2349 
   2350         copy_block(buf, (unsigned)stored_len, 0); /* without header */
   2351         s->compressed_len = stored_len << 3;
   2352         s->method = STORED;
   2353     } else
   2354 #endif /* STORED_FILE_OK */
   2355 
   2356     /* For Z_PACKET_FLUSH, if we don't achieve the required minimum
   2357      * compression, and this block contains all the data since the last
   2358      * time we used Z_PACKET_FLUSH, then just omit this block completely
   2359      * from the output.
   2360      */
   2361     if (flush == Z_PACKET_FLUSH && s->blocks_in_packet == 1
   2362 	&& opt_lenb > stored_len - s->minCompr) {
   2363 	s->blocks_in_packet = 0;
   2364 	/* output nothing */
   2365     } else
   2366 
   2367 #ifdef FORCE_STORED
   2368     if (buf != (char*)0) /* force stored block */
   2369 #else
   2370     if (stored_len+4 <= opt_lenb && buf != (char*)0)
   2371                        /* 4: two words for the lengths */
   2372 #endif
   2373     {
   2374         /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
   2375          * Otherwise we can't have processed more than WSIZE input bytes since
   2376          * the last block flush, because compression would have been
   2377          * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
   2378          * transform a block into a stored block.
   2379          */
   2380         ct_stored_block(s, buf, stored_len, eof);
   2381     } else
   2382 
   2383 #ifdef FORCE_STATIC
   2384     if (static_lenb >= 0) /* force static trees */
   2385 #else
   2386     if (static_lenb == opt_lenb)
   2387 #endif
   2388     {
   2389         send_bits(s, (STATIC_TREES<<1)+eof, 3);
   2390         compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
   2391         s->compressed_len += 3 + s->static_len;
   2392     } else {
   2393         send_bits(s, (DYN_TREES<<1)+eof, 3);
   2394         send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
   2395                        max_blindex+1);
   2396         compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
   2397         s->compressed_len += 3 + s->opt_len;
   2398     }
   2399     Assert (s->compressed_len == s->bits_sent, "bad compressed size");
   2400     init_block(s);
   2401 
   2402     if (eof) {
   2403         bi_windup(s);
   2404         s->compressed_len += 7;  /* align on byte boundary */
   2405     }
   2406     Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
   2407            s->compressed_len-7*eof));
   2408 
   2409     return s->compressed_len >> 3;
   2410 }
   2411 
   2412 /* ===========================================================================
   2413  * Save the match info and tally the frequency counts. Return true if
   2414  * the current block must be flushed.
   2415  */
   2416 local int ct_tally (s, dist, lc)
   2417     deflate_state *s;
   2418     int dist;  /* distance of matched string */
   2419     int lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
   2420 {
   2421     s->d_buf[s->last_lit] = (ush)dist;
   2422     s->l_buf[s->last_lit++] = (uch)lc;
   2423     if (dist == 0) {
   2424         /* lc is the unmatched char */
   2425         s->dyn_ltree[lc].Freq++;
   2426     } else {
   2427         s->matches++;
   2428         /* Here, lc is the match length - MIN_MATCH */
   2429         dist--;             /* dist = match distance - 1 */
   2430         Assert((ush)dist < (ush)MAX_DIST(s) &&
   2431                (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
   2432                (ush)d_code(dist) < (ush)D_CODES,  "ct_tally: bad match");
   2433 
   2434         s->dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
   2435         s->dyn_dtree[d_code(dist)].Freq++;
   2436     }
   2437 
   2438     /* Try to guess if it is profitable to stop the current block here */
   2439     if (s->level > 2 && (s->last_lit & 0xfff) == 0) {
   2440         /* Compute an upper bound for the compressed length */
   2441         ulg out_length = (ulg)s->last_lit*8L;
   2442         ulg in_length = (ulg)s->strstart - s->block_start;
   2443         int dcode;
   2444         for (dcode = 0; dcode < D_CODES; dcode++) {
   2445             out_length += (ulg)s->dyn_dtree[dcode].Freq *
   2446                 (5L+extra_dbits[dcode]);
   2447         }
   2448         out_length >>= 3;
   2449         Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
   2450                s->last_lit, in_length, out_length,
   2451                100L - out_length*100L/in_length));
   2452         if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
   2453     }
   2454     return (s->last_lit == s->lit_bufsize-1);
   2455     /* We avoid equality with lit_bufsize because of wraparound at 64K
   2456      * on 16 bit machines and because stored blocks are restricted to
   2457      * 64K-1 bytes.
   2458      */
   2459 }
   2460 
   2461 /* ===========================================================================
   2462  * Send the block data compressed using the given Huffman trees
   2463  */
   2464 local void compress_block(s, ltree, dtree)
   2465     deflate_state *s;
   2466     ct_data *ltree; /* literal tree */
   2467     ct_data *dtree; /* distance tree */
   2468 {
   2469     unsigned dist;      /* distance of matched string */
   2470     int lc;             /* match length or unmatched char (if dist == 0) */
   2471     unsigned lx = 0;    /* running index in l_buf */
   2472     unsigned code;      /* the code to send */
   2473     int extra;          /* number of extra bits to send */
   2474 
   2475     if (s->last_lit != 0) do {
   2476         dist = s->d_buf[lx];
   2477         lc = s->l_buf[lx++];
   2478         if (dist == 0) {
   2479             send_code(s, lc, ltree); /* send a literal byte */
   2480             Tracecv(isgraph(lc), (stderr," '%c' ", lc));
   2481         } else {
   2482             /* Here, lc is the match length - MIN_MATCH */
   2483             code = length_code[lc];
   2484             send_code(s, code+LITERALS+1, ltree); /* send the length code */
   2485             extra = extra_lbits[code];
   2486             if (extra != 0) {
   2487                 lc -= base_length[code];
   2488                 send_bits(s, lc, extra);       /* send the extra length bits */
   2489             }
   2490             dist--; /* dist is now the match distance - 1 */
   2491             code = d_code(dist);
   2492             Assert (code < D_CODES, "bad d_code");
   2493 
   2494             send_code(s, code, dtree);       /* send the distance code */
   2495             extra = extra_dbits[code];
   2496             if (extra != 0) {
   2497                 dist -= base_dist[code];
   2498                 send_bits(s, dist, extra);   /* send the extra distance bits */
   2499             }
   2500         } /* literal or match pair ? */
   2501 
   2502         /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
   2503         Assert(s->pending < s->lit_bufsize + 2*lx, "pendingBuf overflow");
   2504 
   2505     } while (lx < s->last_lit);
   2506 
   2507     send_code(s, END_BLOCK, ltree);
   2508     s->last_eob_len = ltree[END_BLOCK].Len;
   2509 }
   2510 
   2511 /* ===========================================================================
   2512  * Set the data type to ASCII or BINARY, using a crude approximation:
   2513  * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
   2514  * IN assertion: the fields freq of dyn_ltree are set and the total of all
   2515  * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
   2516  */
   2517 local void set_data_type(s)
   2518     deflate_state *s;
   2519 {
   2520     int n = 0;
   2521     unsigned ascii_freq = 0;
   2522     unsigned bin_freq = 0;
   2523     while (n < 7)        bin_freq += s->dyn_ltree[n++].Freq;
   2524     while (n < 128)    ascii_freq += s->dyn_ltree[n++].Freq;
   2525     while (n < LITERALS) bin_freq += s->dyn_ltree[n++].Freq;
   2526     s->data_type = (Byte)(bin_freq > (ascii_freq >> 2) ? BINARY : ASCII);
   2527 }
   2528 
   2529 /* ===========================================================================
   2530  * Reverse the first len bits of a code, using straightforward code (a faster
   2531  * method would use a table)
   2532  * IN assertion: 1 <= len <= 15
   2533  */
   2534 local unsigned bi_reverse(code, len)
   2535     unsigned code; /* the value to invert */
   2536     int len;       /* its bit length */
   2537 {
   2538     register unsigned res = 0;
   2539     do {
   2540         res |= code & 1;
   2541         code >>= 1, res <<= 1;
   2542     } while (--len > 0);
   2543     return res >> 1;
   2544 }
   2545 
   2546 /* ===========================================================================
   2547  * Flush the bit buffer, keeping at most 7 bits in it.
   2548  */
   2549 local void bi_flush(s)
   2550     deflate_state *s;
   2551 {
   2552     if (s->bi_valid == 16) {
   2553         put_short(s, s->bi_buf);
   2554         s->bi_buf = 0;
   2555         s->bi_valid = 0;
   2556     } else if (s->bi_valid >= 8) {
   2557         put_byte(s, (Byte)s->bi_buf);
   2558         s->bi_buf >>= 8;
   2559         s->bi_valid -= 8;
   2560     }
   2561 }
   2562 
   2563 /* ===========================================================================
   2564  * Flush the bit buffer and align the output on a byte boundary
   2565  */
   2566 local void bi_windup(s)
   2567     deflate_state *s;
   2568 {
   2569     if (s->bi_valid > 8) {
   2570         put_short(s, s->bi_buf);
   2571     } else if (s->bi_valid > 0) {
   2572         put_byte(s, (Byte)s->bi_buf);
   2573     }
   2574     s->bi_buf = 0;
   2575     s->bi_valid = 0;
   2576 #ifdef DEBUG_ZLIB
   2577     s->bits_sent = (s->bits_sent+7) & ~7;
   2578 #endif
   2579 }
   2580 
   2581 /* ===========================================================================
   2582  * Copy a stored block, storing first the length and its
   2583  * one's complement if requested.
   2584  */
   2585 local void copy_block(s, buf, len, header)
   2586     deflate_state *s;
   2587     charf    *buf;    /* the input data */
   2588     unsigned len;     /* its length */
   2589     int      header;  /* true if block header must be written */
   2590 {
   2591     bi_windup(s);        /* align on byte boundary */
   2592     s->last_eob_len = 8; /* enough lookahead for inflate */
   2593 
   2594     if (header) {
   2595         put_short(s, (ush)len);
   2596         put_short(s, (ush)~len);
   2597 #ifdef DEBUG_ZLIB
   2598         s->bits_sent += 2*16;
   2599 #endif
   2600     }
   2601 #ifdef DEBUG_ZLIB
   2602     s->bits_sent += (ulg)len<<3;
   2603 #endif
   2604     while (len--) {
   2605         put_byte(s, *buf++);
   2606     }
   2607 }
   2608 
   2609 
   2610 /*+++++*/
   2611 /* infblock.h -- header to use infblock.c
   2612  * Copyright (C) 1995 Mark Adler
   2613  * For conditions of distribution and use, see copyright notice in zlib.h
   2614  */
   2615 
   2616 /* WARNING: this file should *not* be used by applications. It is
   2617    part of the implementation of the compression library and is
   2618    subject to change. Applications should only use zlib.h.
   2619  */
   2620 
   2621 struct inflate_blocks_state;
   2622 typedef struct inflate_blocks_state FAR inflate_blocks_statef;
   2623 
   2624 local inflate_blocks_statef * inflate_blocks_new OF((
   2625     z_stream *z,
   2626     check_func c,               /* check function */
   2627     uInt w));                   /* window size */
   2628 
   2629 local int inflate_blocks OF((
   2630     inflate_blocks_statef *,
   2631     z_stream *,
   2632     int));                      /* initial return code */
   2633 
   2634 local void inflate_blocks_reset OF((
   2635     inflate_blocks_statef *,
   2636     z_stream *,
   2637     uLongf *));                  /* check value on output */
   2638 
   2639 local int inflate_blocks_free OF((
   2640     inflate_blocks_statef *,
   2641     z_stream *,
   2642     uLongf *));                  /* check value on output */
   2643 
   2644 local int inflate_addhistory OF((
   2645     inflate_blocks_statef *,
   2646     z_stream *));
   2647 
   2648 local int inflate_packet_flush OF((
   2649     inflate_blocks_statef *));
   2650 
   2651 /*+++++*/
   2652 /* inftrees.h -- header to use inftrees.c
   2653  * Copyright (C) 1995 Mark Adler
   2654  * For conditions of distribution and use, see copyright notice in zlib.h
   2655  */
   2656 
   2657 /* WARNING: this file should *not* be used by applications. It is
   2658    part of the implementation of the compression library and is
   2659    subject to change. Applications should only use zlib.h.
   2660  */
   2661 
   2662 /* Huffman code lookup table entry--this entry is four bytes for machines
   2663    that have 16-bit pointers (e.g. PC's in the small or medium model). */
   2664 
   2665 typedef struct inflate_huft_s FAR inflate_huft;
   2666 
   2667 struct inflate_huft_s {
   2668   union {
   2669     struct {
   2670       Byte Exop;        /* number of extra bits or operation */
   2671       Byte Bits;        /* number of bits in this code or subcode */
   2672     } what;
   2673     uInt Nalloc;	/* number of these allocated here */
   2674     Bytef *pad;         /* pad structure to a power of 2 (4 bytes for */
   2675   } word;               /*  16-bit, 8 bytes for 32-bit machines) */
   2676   union {
   2677     uInt Base;          /* literal, length base, or distance base */
   2678     inflate_huft *Next; /* pointer to next level of table */
   2679   } more;
   2680 };
   2681 
   2682 #ifdef DEBUG_ZLIB
   2683   local uInt inflate_hufts;
   2684 #endif
   2685 
   2686 local int inflate_trees_bits OF((
   2687     uIntf *,                    /* 19 code lengths */
   2688     uIntf *,                    /* bits tree desired/actual depth */
   2689     inflate_huft * FAR *,       /* bits tree result */
   2690     z_stream *));               /* for zalloc, zfree functions */
   2691 
   2692 local int inflate_trees_dynamic OF((
   2693     uInt,                       /* number of literal/length codes */
   2694     uInt,                       /* number of distance codes */
   2695     uIntf *,                    /* that many (total) code lengths */
   2696     uIntf *,                    /* literal desired/actual bit depth */
   2697     uIntf *,                    /* distance desired/actual bit depth */
   2698     inflate_huft * FAR *,       /* literal/length tree result */
   2699     inflate_huft * FAR *,       /* distance tree result */
   2700     z_stream *));               /* for zalloc, zfree functions */
   2701 
   2702 local int inflate_trees_fixed OF((
   2703     uIntf *,                    /* literal desired/actual bit depth */
   2704     uIntf *,                    /* distance desired/actual bit depth */
   2705     inflate_huft * FAR *,       /* literal/length tree result */
   2706     inflate_huft * FAR *));     /* distance tree result */
   2707 
   2708 local int inflate_trees_free OF((
   2709     inflate_huft *,             /* tables to free */
   2710     z_stream *));               /* for zfree function */
   2711 
   2712 
   2713 /*+++++*/
   2714 /* infcodes.h -- header to use infcodes.c
   2715  * Copyright (C) 1995 Mark Adler
   2716  * For conditions of distribution and use, see copyright notice in zlib.h
   2717  */
   2718 
   2719 /* WARNING: this file should *not* be used by applications. It is
   2720    part of the implementation of the compression library and is
   2721    subject to change. Applications should only use zlib.h.
   2722  */
   2723 
   2724 struct inflate_codes_state;
   2725 typedef struct inflate_codes_state FAR inflate_codes_statef;
   2726 
   2727 local inflate_codes_statef *inflate_codes_new OF((
   2728     uInt, uInt,
   2729     inflate_huft *, inflate_huft *,
   2730     z_stream *));
   2731 
   2732 local int inflate_codes OF((
   2733     inflate_blocks_statef *,
   2734     z_stream *,
   2735     int));
   2736 
   2737 local void inflate_codes_free OF((
   2738     inflate_codes_statef *,
   2739     z_stream *));
   2740 
   2741 
   2742 /*+++++*/
   2743 /* inflate.c -- zlib interface to inflate modules
   2744  * Copyright (C) 1995 Mark Adler
   2745  * For conditions of distribution and use, see copyright notice in zlib.h
   2746  */
   2747 
   2748 /* inflate private state */
   2749 struct internal_state {
   2750 
   2751   /* mode */
   2752   enum {
   2753       METHOD,   /* waiting for method byte */
   2754       FLAG,     /* waiting for flag byte */
   2755       BLOCKS,   /* decompressing blocks */
   2756       CHECK4,   /* four check bytes to go */
   2757       CHECK3,   /* three check bytes to go */
   2758       CHECK2,   /* two check bytes to go */
   2759       CHECK1,   /* one check byte to go */
   2760       DONE,     /* finished check, done */
   2761       BAD}      /* got an error--stay here */
   2762     mode;               /* current inflate mode */
   2763 
   2764   /* mode dependent information */
   2765   union {
   2766     uInt method;        /* if FLAGS, method byte */
   2767     struct {
   2768       uLong was;                /* computed check value */
   2769       uLong need;               /* stream check value */
   2770     } check;            /* if CHECK, check values to compare */
   2771     uInt marker;        /* if BAD, inflateSync's marker bytes count */
   2772   } sub;        /* submode */
   2773 
   2774   /* mode independent information */
   2775   int  nowrap;          /* flag for no wrapper */
   2776   uInt wbits;           /* log2(window size)  (8..15, defaults to 15) */
   2777   inflate_blocks_statef
   2778     *blocks;            /* current inflate_blocks state */
   2779 
   2780 };
   2781 
   2782 
   2783 int inflateReset(z)
   2784 z_stream *z;
   2785 {
   2786   uLong c;
   2787 
   2788   if (z == Z_NULL || z->state == Z_NULL)
   2789     return Z_STREAM_ERROR;
   2790   z->total_in = z->total_out = 0;
   2791   z->msg = Z_NULL;
   2792   z->state->mode = z->state->nowrap ? BLOCKS : METHOD;
   2793   inflate_blocks_reset(z->state->blocks, z, &c);
   2794   Trace((stderr, "inflate: reset\n"));
   2795   return Z_OK;
   2796 }
   2797 
   2798 
   2799 int inflateEnd(z)
   2800 z_stream *z;
   2801 {
   2802   uLong c;
   2803 
   2804   if (z == Z_NULL || z->state == Z_NULL || z->zfree == Z_NULL)
   2805     return Z_STREAM_ERROR;
   2806   if (z->state->blocks != Z_NULL)
   2807     inflate_blocks_free(z->state->blocks, z, &c);
   2808   ZFREE(z, z->state, sizeof(struct internal_state));
   2809   z->state = Z_NULL;
   2810   Trace((stderr, "inflate: end\n"));
   2811   return Z_OK;
   2812 }
   2813 
   2814 
   2815 int inflateInit2(z, w)
   2816 z_stream *z;
   2817 int w;
   2818 {
   2819   /* initialize state */
   2820   if (z == Z_NULL)
   2821     return Z_STREAM_ERROR;
   2822 /*  if (z->zalloc == Z_NULL) z->zalloc = zcalloc; */
   2823 /*  if (z->zfree == Z_NULL) z->zfree = zcfree; */
   2824   if ((z->state = (struct internal_state FAR *)
   2825        ZALLOC(z,1,sizeof(struct internal_state))) == Z_NULL)
   2826     return Z_MEM_ERROR;
   2827   z->state->blocks = Z_NULL;
   2828 
   2829   /* handle undocumented nowrap option (no zlib header or check) */
   2830   z->state->nowrap = 0;
   2831   if (w < 0)
   2832   {
   2833     w = - w;
   2834     z->state->nowrap = 1;
   2835   }
   2836 
   2837   /* set window size */
   2838   if (w < 8 || w > 15)
   2839   {
   2840     inflateEnd(z);
   2841     return Z_STREAM_ERROR;
   2842   }
   2843   z->state->wbits = (uInt)w;
   2844 
   2845   /* create inflate_blocks state */
   2846   if ((z->state->blocks =
   2847        inflate_blocks_new(z, z->state->nowrap ? Z_NULL : adler32, 1 << w))
   2848       == Z_NULL)
   2849   {
   2850     inflateEnd(z);
   2851     return Z_MEM_ERROR;
   2852   }
   2853   Trace((stderr, "inflate: allocated\n"));
   2854 
   2855   /* reset state */
   2856   inflateReset(z);
   2857   return Z_OK;
   2858 }
   2859 
   2860 
   2861 int inflateInit(z)
   2862 z_stream *z;
   2863 {
   2864   return inflateInit2(z, DEF_WBITS);
   2865 }
   2866 
   2867 
   2868 #define NEEDBYTE {if(z->avail_in==0)goto empty;r=Z_OK;}
   2869 #define NEXTBYTE (z->avail_in--,z->total_in++,*z->next_in++)
   2870 
   2871 int inflate(z, f)
   2872 z_stream *z;
   2873 int f;
   2874 {
   2875   int r;
   2876   uInt b;
   2877 
   2878   if (z == Z_NULL || z->next_in == Z_NULL)
   2879     return Z_STREAM_ERROR;
   2880   r = Z_BUF_ERROR;
   2881   while (1) switch (z->state->mode)
   2882   {
   2883     case METHOD:
   2884       NEEDBYTE
   2885       if (((z->state->sub.method = NEXTBYTE) & 0xf) != DEFLATED)
   2886       {
   2887         z->state->mode = BAD;
   2888         z->msg = "unknown compression method";
   2889         z->state->sub.marker = 5;       /* can't try inflateSync */
   2890         break;
   2891       }
   2892       if ((z->state->sub.method >> 4) + 8 > z->state->wbits)
   2893       {
   2894         z->state->mode = BAD;
   2895         z->msg = "invalid window size";
   2896         z->state->sub.marker = 5;       /* can't try inflateSync */
   2897         break;
   2898       }
   2899       z->state->mode = FLAG;
   2900     case FLAG:
   2901       NEEDBYTE
   2902       if ((b = NEXTBYTE) & 0x20)
   2903       {
   2904         z->state->mode = BAD;
   2905         z->msg = "invalid reserved bit";
   2906         z->state->sub.marker = 5;       /* can't try inflateSync */
   2907         break;
   2908       }
   2909       if (((z->state->sub.method << 8) + b) % 31)
   2910       {
   2911         z->state->mode = BAD;
   2912         z->msg = "incorrect header check";
   2913         z->state->sub.marker = 5;       /* can't try inflateSync */
   2914         break;
   2915       }
   2916       Trace((stderr, "inflate: zlib header ok\n"));
   2917       z->state->mode = BLOCKS;
   2918     case BLOCKS:
   2919       r = inflate_blocks(z->state->blocks, z, r);
   2920       if (f == Z_PACKET_FLUSH && z->avail_in == 0 && z->avail_out != 0)
   2921 	  r = inflate_packet_flush(z->state->blocks);
   2922       if (r == Z_DATA_ERROR)
   2923       {
   2924         z->state->mode = BAD;
   2925         z->state->sub.marker = 0;       /* can try inflateSync */
   2926         break;
   2927       }
   2928       if (r != Z_STREAM_END)
   2929         return r;
   2930       r = Z_OK;
   2931       inflate_blocks_reset(z->state->blocks, z, &z->state->sub.check.was);
   2932       if (z->state->nowrap)
   2933       {
   2934         z->state->mode = DONE;
   2935         break;
   2936       }
   2937       z->state->mode = CHECK4;
   2938     case CHECK4:
   2939       NEEDBYTE
   2940       z->state->sub.check.need = (uLong)NEXTBYTE << 24;
   2941       z->state->mode = CHECK3;
   2942     case CHECK3:
   2943       NEEDBYTE
   2944       z->state->sub.check.need += (uLong)NEXTBYTE << 16;
   2945       z->state->mode = CHECK2;
   2946     case CHECK2:
   2947       NEEDBYTE
   2948       z->state->sub.check.need += (uLong)NEXTBYTE << 8;
   2949       z->state->mode = CHECK1;
   2950     case CHECK1:
   2951       NEEDBYTE
   2952       z->state->sub.check.need += (uLong)NEXTBYTE;
   2953 
   2954       if (z->state->sub.check.was != z->state->sub.check.need)
   2955       {
   2956         z->state->mode = BAD;
   2957         z->msg = "incorrect data check";
   2958         z->state->sub.marker = 5;       /* can't try inflateSync */
   2959         break;
   2960       }
   2961       Trace((stderr, "inflate: zlib check ok\n"));
   2962       z->state->mode = DONE;
   2963     case DONE:
   2964       return Z_STREAM_END;
   2965     case BAD:
   2966       return Z_DATA_ERROR;
   2967     default:
   2968       return Z_STREAM_ERROR;
   2969   }
   2970 
   2971  empty:
   2972   if (f != Z_PACKET_FLUSH)
   2973     return r;
   2974   z->state->mode = BAD;
   2975   z->state->sub.marker = 0;       /* can try inflateSync */
   2976   return Z_DATA_ERROR;
   2977 }
   2978 
   2979 /*
   2980  * This subroutine adds the data at next_in/avail_in to the output history
   2981  * without performing any output.  The output buffer must be "caught up";
   2982  * i.e. no pending output (hence s->read equals s->write), and the state must
   2983  * be BLOCKS (i.e. we should be willing to see the start of a series of
   2984  * BLOCKS).  On exit, the output will also be caught up, and the checksum
   2985  * will have been updated if need be.
   2986  */
   2987 
   2988 int inflateIncomp(z)
   2989 z_stream *z;
   2990 {
   2991     if (z->state->mode != BLOCKS)
   2992 	return Z_DATA_ERROR;
   2993     return inflate_addhistory(z->state->blocks, z);
   2994 }
   2995 
   2996 
   2997 int inflateSync(z)
   2998 z_stream *z;
   2999 {
   3000   uInt n;       /* number of bytes to look at */
   3001   Bytef *p;     /* pointer to bytes */
   3002   uInt m;       /* number of marker bytes found in a row */
   3003   uLong r, w;   /* temporaries to save total_in and total_out */
   3004 
   3005   /* set up */
   3006   if (z == Z_NULL || z->state == Z_NULL)
   3007     return Z_STREAM_ERROR;
   3008   if (z->state->mode != BAD)
   3009   {
   3010     z->state->mode = BAD;
   3011     z->state->sub.marker = 0;
   3012   }
   3013   if ((n = z->avail_in) == 0)
   3014     return Z_BUF_ERROR;
   3015   p = z->next_in;
   3016   m = z->state->sub.marker;
   3017 
   3018   /* search */
   3019   while (n && m < 4)
   3020   {
   3021     if (*p == (Byte)(m < 2 ? 0 : 0xff))
   3022       m++;
   3023     else if (*p)
   3024       m = 0;
   3025     else
   3026       m = 4 - m;
   3027     p++, n--;
   3028   }
   3029 
   3030   /* restore */
   3031   z->total_in += p - z->next_in;
   3032   z->next_in = p;
   3033   z->avail_in = n;
   3034   z->state->sub.marker = m;
   3035 
   3036   /* return no joy or set up to restart on a new block */
   3037   if (m != 4)
   3038     return Z_DATA_ERROR;
   3039   r = z->total_in;  w = z->total_out;
   3040   inflateReset(z);
   3041   z->total_in = r;  z->total_out = w;
   3042   z->state->mode = BLOCKS;
   3043   return Z_OK;
   3044 }
   3045 
   3046 #undef NEEDBYTE
   3047 #undef NEXTBYTE
   3048 
   3049 /*+++++*/
   3050 /* infutil.h -- types and macros common to blocks and codes
   3051  * Copyright (C) 1995 Mark Adler
   3052  * For conditions of distribution and use, see copyright notice in zlib.h
   3053  */
   3054 
   3055 /* WARNING: this file should *not* be used by applications. It is
   3056    part of the implementation of the compression library and is
   3057    subject to change. Applications should only use zlib.h.
   3058  */
   3059 
   3060 /* inflate blocks semi-private state */
   3061 struct inflate_blocks_state {
   3062 
   3063   /* mode */
   3064   enum {
   3065       TYPE,     /* get type bits (3, including end bit) */
   3066       LENS,     /* get lengths for stored */
   3067       STORED,   /* processing stored block */
   3068       TABLE,    /* get table lengths */
   3069       BTREE,    /* get bit lengths tree for a dynamic block */
   3070       DTREE,    /* get length, distance trees for a dynamic block */
   3071       CODES,    /* processing fixed or dynamic block */
   3072       DRY,      /* output remaining window bytes */
   3073       DONEB,     /* finished last block, done */
   3074       BADB}      /* got a data error--stuck here */
   3075     mode;               /* current inflate_block mode */
   3076 
   3077   /* mode dependent information */
   3078   union {
   3079     uInt left;          /* if STORED, bytes left to copy */
   3080     struct {
   3081       uInt table;               /* table lengths (14 bits) */
   3082       uInt index;               /* index into blens (or border) */
   3083       uIntf *blens;             /* bit lengths of codes */
   3084       uInt bb;                  /* bit length tree depth */
   3085       inflate_huft *tb;         /* bit length decoding tree */
   3086       int nblens;		/* # elements allocated at blens */
   3087     } trees;            /* if DTREE, decoding info for trees */
   3088     struct {
   3089       inflate_huft *tl, *td;    /* trees to free */
   3090       inflate_codes_statef
   3091          *codes;
   3092     } decode;           /* if CODES, current state */
   3093   } sub;                /* submode */
   3094   uInt last;            /* true if this block is the last block */
   3095 
   3096   /* mode independent information */
   3097   uInt bitk;            /* bits in bit buffer */
   3098   uLong bitb;           /* bit buffer */
   3099   Bytef *window;        /* sliding window */
   3100   Bytef *end;           /* one byte after sliding window */
   3101   Bytef *read;          /* window read pointer */
   3102   Bytef *write;         /* window write pointer */
   3103   check_func checkfn;   /* check function */
   3104   uLong check;          /* check on output */
   3105 
   3106 };
   3107 
   3108 
   3109 /* defines for inflate input/output */
   3110 /*   update pointers and return */
   3111 #define UPDBITS {s->bitb=b;s->bitk=k;}
   3112 #define UPDIN {z->avail_in=n;z->total_in+=p-z->next_in;z->next_in=p;}
   3113 #define UPDOUT {s->write=q;}
   3114 #define UPDATE {UPDBITS UPDIN UPDOUT}
   3115 #define LEAVE {UPDATE return inflate_flush(s,z,r);}
   3116 /*   get bytes and bits */
   3117 #define LOADIN {p=z->next_in;n=z->avail_in;b=s->bitb;k=s->bitk;}
   3118 #define NEEDBYTE {if(n)r=Z_OK;else LEAVE}
   3119 #define NEXTBYTE (n--,*p++)
   3120 #define NEEDBITS(j) {while(k<(j)){NEEDBYTE;b|=((uLong)NEXTBYTE)<<k;k+=8;}}
   3121 #define DUMPBITS(j) {b>>=(j);k-=(j);}
   3122 /*   output bytes */
   3123 #define WAVAIL (q<s->read?s->read-q-1:s->end-q)
   3124 #define LOADOUT {q=s->write;m=WAVAIL;}
   3125 #define WRAP {if(q==s->end&&s->read!=s->window){q=s->window;m=WAVAIL;}}
   3126 #define FLUSH {UPDOUT r=inflate_flush(s,z,r); LOADOUT}
   3127 #define NEEDOUT {if(m==0){WRAP if(m==0){FLUSH WRAP if(m==0) LEAVE}}r=Z_OK;}
   3128 #define OUTBYTE(a) {*q++=(Byte)(a);m--;}
   3129 /*   load local pointers */
   3130 #define LOAD {LOADIN LOADOUT}
   3131 
   3132 /* And'ing with mask[n] masks the lower n bits */
   3133 local uInt inflate_mask[] = {
   3134     0x0000,
   3135     0x0001, 0x0003, 0x0007, 0x000f, 0x001f, 0x003f, 0x007f, 0x00ff,
   3136     0x01ff, 0x03ff, 0x07ff, 0x0fff, 0x1fff, 0x3fff, 0x7fff, 0xffff
   3137 };
   3138 
   3139 /* copy as much as possible from the sliding window to the output area */
   3140 local int inflate_flush OF((
   3141     inflate_blocks_statef *,
   3142     z_stream *,
   3143     int));
   3144 
   3145 /*+++++*/
   3146 /* inffast.h -- header to use inffast.c
   3147  * Copyright (C) 1995 Mark Adler
   3148  * For conditions of distribution and use, see copyright notice in zlib.h
   3149  */
   3150 
   3151 /* WARNING: this file should *not* be used by applications. It is
   3152    part of the implementation of the compression library and is
   3153    subject to change. Applications should only use zlib.h.
   3154  */
   3155 
   3156 local int inflate_fast OF((
   3157     uInt,
   3158     uInt,
   3159     inflate_huft *,
   3160     inflate_huft *,
   3161     inflate_blocks_statef *,
   3162     z_stream *));
   3163 
   3164 
   3165 /*+++++*/
   3166 /* infblock.c -- interpret and process block types to last block
   3167  * Copyright (C) 1995 Mark Adler
   3168  * For conditions of distribution and use, see copyright notice in zlib.h
   3169  */
   3170 
   3171 /* Table for deflate from PKZIP's appnote.txt. */
   3172 local uInt border[] = { /* Order of the bit length code lengths */
   3173         16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
   3174 
   3175 /*
   3176    Notes beyond the 1.93a appnote.txt:
   3177 
   3178    1. Distance pointers never point before the beginning of the output
   3179       stream.
   3180    2. Distance pointers can point back across blocks, up to 32k away.
   3181    3. There is an implied maximum of 7 bits for the bit length table and
   3182       15 bits for the actual data.
   3183    4. If only one code exists, then it is encoded using one bit.  (Zero
   3184       would be more efficient, but perhaps a little confusing.)  If two
   3185       codes exist, they are coded using one bit each (0 and 1).
   3186    5. There is no way of sending zero distance codes--a dummy must be
   3187       sent if there are none.  (History: a pre 2.0 version of PKZIP would
   3188       store blocks with no distance codes, but this was discovered to be
   3189       too harsh a criterion.)  Valid only for 1.93a.  2.04c does allow
   3190       zero distance codes, which is sent as one code of zero bits in
   3191       length.
   3192    6. There are up to 286 literal/length codes.  Code 256 represents the
   3193       end-of-block.  Note however that the static length tree defines
   3194       288 codes just to fill out the Huffman codes.  Codes 286 and 287
   3195       cannot be used though, since there is no length base or extra bits
   3196       defined for them.  Similarily, there are up to 30 distance codes.
   3197       However, static trees define 32 codes (all 5 bits) to fill out the
   3198       Huffman codes, but the last two had better not show up in the data.
   3199    7. Unzip can check dynamic Huffman blocks for complete code sets.
   3200       The exception is that a single code would not be complete (see #4).
   3201    8. The five bits following the block type is really the number of
   3202       literal codes sent minus 257.
   3203    9. Length codes 8,16,16 are interpreted as 13 length codes of 8 bits
   3204       (1+6+6).  Therefore, to output three times the length, you output
   3205       three codes (1+1+1), whereas to output four times the same length,
   3206       you only need two codes (1+3).  Hmm.
   3207   10. In the tree reconstruction algorithm, Code = Code + Increment
   3208       only if BitLength(i) is not zero.  (Pretty obvious.)
   3209   11. Correction: 4 Bits: # of Bit Length codes - 4     (4 - 19)
   3210   12. Note: length code 284 can represent 227-258, but length code 285
   3211       really is 258.  The last length deserves its own, short code
   3212       since it gets used a lot in very redundant files.  The length
   3213       258 is special since 258 - 3 (the min match length) is 255.
   3214   13. The literal/length and distance code bit lengths are read as a
   3215       single stream of lengths.  It is possible (and advantageous) for
   3216       a repeat code (16, 17, or 18) to go across the boundary between
   3217       the two sets of lengths.
   3218  */
   3219 
   3220 
   3221 local void inflate_blocks_reset(s, z, c)
   3222 inflate_blocks_statef *s;
   3223 z_stream *z;
   3224 uLongf *c;
   3225 {
   3226   if (s->checkfn != Z_NULL)
   3227     *c = s->check;
   3228   if (s->mode == BTREE || s->mode == DTREE)
   3229     ZFREE(z, s->sub.trees.blens, s->sub.trees.nblens * sizeof(uInt));
   3230   if (s->mode == CODES)
   3231   {
   3232     inflate_codes_free(s->sub.decode.codes, z);
   3233     inflate_trees_free(s->sub.decode.td, z);
   3234     inflate_trees_free(s->sub.decode.tl, z);
   3235   }
   3236   s->mode = TYPE;
   3237   s->bitk = 0;
   3238   s->bitb = 0;
   3239   s->read = s->write = s->window;
   3240   if (s->checkfn != Z_NULL)
   3241     s->check = (*s->checkfn)(0L, Z_NULL, 0);
   3242   Trace((stderr, "inflate:   blocks reset\n"));
   3243 }
   3244 
   3245 
   3246 local inflate_blocks_statef *inflate_blocks_new(z, c, w)
   3247 z_stream *z;
   3248 check_func c;
   3249 uInt w;
   3250 {
   3251   inflate_blocks_statef *s;
   3252 
   3253   if ((s = (inflate_blocks_statef *)ZALLOC
   3254        (z,1,sizeof(struct inflate_blocks_state))) == Z_NULL)
   3255     return s;
   3256   if ((s->window = (Bytef *)ZALLOC(z, 1, w)) == Z_NULL)
   3257   {
   3258     ZFREE(z, s, sizeof(struct inflate_blocks_state));
   3259     return Z_NULL;
   3260   }
   3261   s->end = s->window + w;
   3262   s->checkfn = c;
   3263   s->mode = TYPE;
   3264   Trace((stderr, "inflate:   blocks allocated\n"));
   3265   inflate_blocks_reset(s, z, &s->check);
   3266   return s;
   3267 }
   3268 
   3269 
   3270 local int inflate_blocks(s, z, r)
   3271 inflate_blocks_statef *s;
   3272 z_stream *z;
   3273 int r;
   3274 {
   3275   uInt t;               /* temporary storage */
   3276   uLong b;              /* bit buffer */
   3277   uInt k;               /* bits in bit buffer */
   3278   Bytef *p;             /* input data pointer */
   3279   uInt n;               /* bytes available there */
   3280   Bytef *q;             /* output window write pointer */
   3281   uInt m;               /* bytes to end of window or read pointer */
   3282 
   3283   /* copy input/output information to locals (UPDATE macro restores) */
   3284   LOAD
   3285 
   3286   /* process input based on current state */
   3287   while (1) switch (s->mode)
   3288   {
   3289     case TYPE:
   3290       NEEDBITS(3)
   3291       t = (uInt)b & 7;
   3292       s->last = t & 1;
   3293       switch (t >> 1)
   3294       {
   3295         case 0:                         /* stored */
   3296           Trace((stderr, "inflate:     stored block%s\n",
   3297                  s->last ? " (last)" : ""));
   3298           DUMPBITS(3)
   3299           t = k & 7;                    /* go to byte boundary */
   3300           DUMPBITS(t)
   3301           s->mode = LENS;               /* get length of stored block */
   3302           break;
   3303         case 1:                         /* fixed */
   3304           Trace((stderr, "inflate:     fixed codes block%s\n",
   3305                  s->last ? " (last)" : ""));
   3306           {
   3307             uInt bl, bd;
   3308             inflate_huft *tl, *td;
   3309 
   3310             inflate_trees_fixed(&bl, &bd, &tl, &td);
   3311             s->sub.decode.codes = inflate_codes_new(bl, bd, tl, td, z);
   3312             if (s->sub.decode.codes == Z_NULL)
   3313             {
   3314               r = Z_MEM_ERROR;
   3315               LEAVE
   3316             }
   3317             s->sub.decode.tl = Z_NULL;  /* don't try to free these */
   3318             s->sub.decode.td = Z_NULL;
   3319           }
   3320           DUMPBITS(3)
   3321           s->mode = CODES;
   3322           break;
   3323         case 2:                         /* dynamic */
   3324           Trace((stderr, "inflate:     dynamic codes block%s\n",
   3325                  s->last ? " (last)" : ""));
   3326           DUMPBITS(3)
   3327           s->mode = TABLE;
   3328           break;
   3329         case 3:                         /* illegal */
   3330           DUMPBITS(3)
   3331           s->mode = BADB;
   3332           z->msg = "invalid block type";
   3333           r = Z_DATA_ERROR;
   3334           LEAVE
   3335       }
   3336       break;
   3337     case LENS:
   3338       NEEDBITS(32)
   3339       if (((~b) >> 16) != (b & 0xffff))
   3340       {
   3341         s->mode = BADB;
   3342         z->msg = "invalid stored block lengths";
   3343         r = Z_DATA_ERROR;
   3344         LEAVE
   3345       }
   3346       s->sub.left = (uInt)b & 0xffff;
   3347       b = k = 0;                      /* dump bits */
   3348       Tracev((stderr, "inflate:       stored length %u\n", s->sub.left));
   3349       s->mode = s->sub.left ? STORED : TYPE;
   3350       break;
   3351     case STORED:
   3352       if (n == 0)
   3353         LEAVE
   3354       NEEDOUT
   3355       t = s->sub.left;
   3356       if (t > n) t = n;
   3357       if (t > m) t = m;
   3358       zmemcpy(q, p, t);
   3359       p += t;  n -= t;
   3360       q += t;  m -= t;
   3361       if ((s->sub.left -= t) != 0)
   3362         break;
   3363       Tracev((stderr, "inflate:       stored end, %lu total out\n",
   3364               z->total_out + (q >= s->read ? q - s->read :
   3365               (s->end - s->read) + (q - s->window))));
   3366       s->mode = s->last ? DRY : TYPE;
   3367       break;
   3368     case TABLE:
   3369       NEEDBITS(14)
   3370       s->sub.trees.table = t = (uInt)b & 0x3fff;
   3371 #ifndef PKZIP_BUG_WORKAROUND
   3372       if ((t & 0x1f) > 29 || ((t >> 5) & 0x1f) > 29)
   3373       {
   3374         s->mode = BADB;
   3375         z->msg = "too many length or distance symbols";
   3376         r = Z_DATA_ERROR;
   3377         LEAVE
   3378       }
   3379 #endif
   3380       t = 258 + (t & 0x1f) + ((t >> 5) & 0x1f);
   3381       if (t < 19)
   3382         t = 19;
   3383       if ((s->sub.trees.blens = (uIntf*)ZALLOC(z, t, sizeof(uInt))) == Z_NULL)
   3384       {
   3385         r = Z_MEM_ERROR;
   3386         LEAVE
   3387       }
   3388       s->sub.trees.nblens = t;
   3389       DUMPBITS(14)
   3390       s->sub.trees.index = 0;
   3391       Tracev((stderr, "inflate:       table sizes ok\n"));
   3392       s->mode = BTREE;
   3393     case BTREE:
   3394       while (s->sub.trees.index < 4 + (s->sub.trees.table >> 10))
   3395       {
   3396         NEEDBITS(3)
   3397         s->sub.trees.blens[border[s->sub.trees.index++]] = (uInt)b & 7;
   3398         DUMPBITS(3)
   3399       }
   3400       while (s->sub.trees.index < 19)
   3401         s->sub.trees.blens[border[s->sub.trees.index++]] = 0;
   3402       s->sub.trees.bb = 7;
   3403       t = inflate_trees_bits(s->sub.trees.blens, &s->sub.trees.bb,
   3404                              &s->sub.trees.tb, z);
   3405       if (t != Z_OK)
   3406       {
   3407         r = t;
   3408         if (r == Z_DATA_ERROR)
   3409           s->mode = BADB;
   3410         LEAVE
   3411       }
   3412       s->sub.trees.index = 0;
   3413       Tracev((stderr, "inflate:       bits tree ok\n"));
   3414       s->mode = DTREE;
   3415     case DTREE:
   3416       while (t = s->sub.trees.table,
   3417              s->sub.trees.index < 258 + (t & 0x1f) + ((t >> 5) & 0x1f))
   3418       {
   3419         inflate_huft *h;
   3420         uInt i, j, c;
   3421 
   3422         t = s->sub.trees.bb;
   3423         NEEDBITS(t)
   3424         h = s->sub.trees.tb + ((uInt)b & inflate_mask[t]);
   3425         t = h->word.what.Bits;
   3426         c = h->more.Base;
   3427         if (c < 16)
   3428         {
   3429           DUMPBITS(t)
   3430           s->sub.trees.blens[s->sub.trees.index++] = c;
   3431         }
   3432         else /* c == 16..18 */
   3433         {
   3434           i = c == 18 ? 7 : c - 14;
   3435           j = c == 18 ? 11 : 3;
   3436           NEEDBITS(t + i)
   3437           DUMPBITS(t)
   3438           j += (uInt)b & inflate_mask[i];
   3439           DUMPBITS(i)
   3440           i = s->sub.trees.index;
   3441           t = s->sub.trees.table;
   3442           if (i + j > 258 + (t & 0x1f) + ((t >> 5) & 0x1f) ||
   3443               (c == 16 && i < 1))
   3444           {
   3445             s->mode = BADB;
   3446             z->msg = "invalid bit length repeat";
   3447             r = Z_DATA_ERROR;
   3448             LEAVE
   3449           }
   3450           c = c == 16 ? s->sub.trees.blens[i - 1] : 0;
   3451           do {
   3452             s->sub.trees.blens[i++] = c;
   3453           } while (--j);
   3454           s->sub.trees.index = i;
   3455         }
   3456       }
   3457       inflate_trees_free(s->sub.trees.tb, z);
   3458       s->sub.trees.tb = Z_NULL;
   3459       {
   3460         uInt bl, bd;
   3461         inflate_huft *tl, *td;
   3462         inflate_codes_statef *c;
   3463 
   3464         bl = 9;         /* must be <= 9 for lookahead assumptions */
   3465         bd = 6;         /* must be <= 9 for lookahead assumptions */
   3466         t = s->sub.trees.table;
   3467         t = inflate_trees_dynamic(257 + (t & 0x1f), 1 + ((t >> 5) & 0x1f),
   3468                                   s->sub.trees.blens, &bl, &bd, &tl, &td, z);
   3469         if (t != Z_OK)
   3470         {
   3471           if (t == (uInt)Z_DATA_ERROR)
   3472             s->mode = BADB;
   3473           r = t;
   3474           LEAVE
   3475         }
   3476         Tracev((stderr, "inflate:       trees ok\n"));
   3477         if ((c = inflate_codes_new(bl, bd, tl, td, z)) == Z_NULL)
   3478         {
   3479           inflate_trees_free(td, z);
   3480           inflate_trees_free(tl, z);
   3481           r = Z_MEM_ERROR;
   3482           LEAVE
   3483         }
   3484         ZFREE(z, s->sub.trees.blens, s->sub.trees.nblens * sizeof(uInt));
   3485         s->sub.decode.codes = c;
   3486         s->sub.decode.tl = tl;
   3487         s->sub.decode.td = td;
   3488       }
   3489       s->mode = CODES;
   3490     case CODES:
   3491       UPDATE
   3492       if ((r = inflate_codes(s, z, r)) != Z_STREAM_END)
   3493         return inflate_flush(s, z, r);
   3494       r = Z_OK;
   3495       inflate_codes_free(s->sub.decode.codes, z);
   3496       inflate_trees_free(s->sub.decode.td, z);
   3497       inflate_trees_free(s->sub.decode.tl, z);
   3498       LOAD
   3499       Tracev((stderr, "inflate:       codes end, %lu total out\n",
   3500               z->total_out + (q >= s->read ? q - s->read :
   3501               (s->end - s->read) + (q - s->window))));
   3502       if (!s->last)
   3503       {
   3504         s->mode = TYPE;
   3505         break;
   3506       }
   3507       if (k > 7)              /* return unused byte, if any */
   3508       {
   3509         Assert(k < 16, "inflate_codes grabbed too many bytes")
   3510         k -= 8;
   3511         n++;
   3512         p--;                    /* can always return one */
   3513       }
   3514       s->mode = DRY;
   3515     case DRY:
   3516       FLUSH
   3517       if (s->read != s->write)
   3518         LEAVE
   3519       s->mode = DONEB;
   3520     case DONEB:
   3521       r = Z_STREAM_END;
   3522       LEAVE
   3523     case BADB:
   3524       r = Z_DATA_ERROR;
   3525       LEAVE
   3526     default:
   3527       r = Z_STREAM_ERROR;
   3528       LEAVE
   3529   }
   3530 }
   3531 
   3532 
   3533 local int inflate_blocks_free(s, z, c)
   3534 inflate_blocks_statef *s;
   3535 z_stream *z;
   3536 uLongf *c;
   3537 {
   3538   inflate_blocks_reset(s, z, c);
   3539   ZFREE(z, s->window, s->end - s->window);
   3540   ZFREE(z, s, sizeof(struct inflate_blocks_state));
   3541   Trace((stderr, "inflate:   blocks freed\n"));
   3542   return Z_OK;
   3543 }
   3544 
   3545 /*
   3546  * This subroutine adds the data at next_in/avail_in to the output history
   3547  * without performing any output.  The output buffer must be "caught up";
   3548  * i.e. no pending output (hence s->read equals s->write), and the state must
   3549  * be BLOCKS (i.e. we should be willing to see the start of a series of
   3550  * BLOCKS).  On exit, the output will also be caught up, and the checksum
   3551  * will have been updated if need be.
   3552  */
   3553 local int inflate_addhistory(s, z)
   3554 inflate_blocks_statef *s;
   3555 z_stream *z;
   3556 {
   3557     uLong b;              /* bit buffer */  /* NOT USED HERE */
   3558     uInt k;               /* bits in bit buffer */ /* NOT USED HERE */
   3559     uInt t;               /* temporary storage */
   3560     Bytef *p;             /* input data pointer */
   3561     uInt n;               /* bytes available there */
   3562     Bytef *q;             /* output window write pointer */
   3563     uInt m;               /* bytes to end of window or read pointer */
   3564 
   3565     if (s->read != s->write)
   3566 	return Z_STREAM_ERROR;
   3567     if (s->mode != TYPE)
   3568 	return Z_DATA_ERROR;
   3569 
   3570     /* we're ready to rock */
   3571     LOAD
   3572     /* while there is input ready, copy to output buffer, moving
   3573      * pointers as needed.
   3574      */
   3575     while (n) {
   3576 	t = n;  /* how many to do */
   3577 	/* is there room until end of buffer? */
   3578 	if (t > m) t = m;
   3579 	/* update check information */
   3580 	if (s->checkfn != Z_NULL)
   3581 	    s->check = (*s->checkfn)(s->check, q, t);
   3582 	zmemcpy(q, p, t);
   3583 	q += t;
   3584 	p += t;
   3585 	n -= t;
   3586 	z->total_out += t;
   3587 	s->read = q;    /* drag read pointer forward */
   3588 /*      WRAP  */ 	/* expand WRAP macro by hand to handle s->read */
   3589 	if (q == s->end) {
   3590 	    s->read = q = s->window;
   3591 	    m = WAVAIL;
   3592 	}
   3593     }
   3594     UPDATE
   3595     return Z_OK;
   3596 }
   3597 
   3598 
   3599 /*
   3600  * At the end of a Deflate-compressed PPP packet, we expect to have seen
   3601  * a `stored' block type value but not the (zero) length bytes.
   3602  */
   3603 local int inflate_packet_flush(s)
   3604     inflate_blocks_statef *s;
   3605 {
   3606     if (s->mode != LENS)
   3607 	return Z_DATA_ERROR;
   3608     s->mode = TYPE;
   3609     return Z_OK;
   3610 }
   3611 
   3612 
   3613 /*+++++*/
   3614 /* inftrees.c -- generate Huffman trees for efficient decoding
   3615  * Copyright (C) 1995 Mark Adler
   3616  * For conditions of distribution and use, see copyright notice in zlib.h
   3617  */
   3618 
   3619 /* simplify the use of the inflate_huft type with some defines */
   3620 #define base more.Base
   3621 #define next more.Next
   3622 #define exop word.what.Exop
   3623 #define bits word.what.Bits
   3624 
   3625 
   3626 local int huft_build OF((
   3627     uIntf *,            /* code lengths in bits */
   3628     uInt,               /* number of codes */
   3629     uInt,               /* number of "simple" codes */
   3630     uIntf *,            /* list of base values for non-simple codes */
   3631     uIntf *,            /* list of extra bits for non-simple codes */
   3632     inflate_huft * FAR*,/* result: starting table */
   3633     uIntf *,            /* maximum lookup bits (returns actual) */
   3634     z_stream *));       /* for zalloc function */
   3635 
   3636 local voidpf falloc OF((
   3637     voidpf,             /* opaque pointer (not used) */
   3638     uInt,               /* number of items */
   3639     uInt));             /* size of item */
   3640 
   3641 local void ffree OF((
   3642     voidpf q,           /* opaque pointer (not used) */
   3643     voidpf p,           /* what to free (not used) */
   3644     uInt n));		/* number of bytes (not used) */
   3645 
   3646 /* Tables for deflate from PKZIP's appnote.txt. */
   3647 local uInt cplens[] = { /* Copy lengths for literal codes 257..285 */
   3648         3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
   3649         35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
   3650         /* actually lengths - 2; also see note #13 above about 258 */
   3651 local uInt cplext[] = { /* Extra bits for literal codes 257..285 */
   3652         0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2,
   3653         3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0, 192, 192}; /* 192==invalid */
   3654 local uInt cpdist[] = { /* Copy offsets for distance codes 0..29 */
   3655         1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
   3656         257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
   3657         8193, 12289, 16385, 24577};
   3658 local uInt cpdext[] = { /* Extra bits for distance codes */
   3659         0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
   3660         7, 7, 8, 8, 9, 9, 10, 10, 11, 11,
   3661         12, 12, 13, 13};
   3662 
   3663 /*
   3664    Huffman code decoding is performed using a multi-level table lookup.
   3665    The fastest way to decode is to simply build a lookup table whose
   3666    size is determined by the longest code.  However, the time it takes
   3667    to build this table can also be a factor if the data being decoded
   3668    is not very long.  The most common codes are necessarily the
   3669    shortest codes, so those codes dominate the decoding time, and hence
   3670    the speed.  The idea is you can have a shorter table that decodes the
   3671    shorter, more probable codes, and then point to subsidiary tables for
   3672    the longer codes.  The time it costs to decode the longer codes is
   3673    then traded against the time it takes to make longer tables.
   3674 
   3675    This results of this trade are in the variables lbits and dbits
   3676    below.  lbits is the number of bits the first level table for literal/
   3677    length codes can decode in one step, and dbits is the same thing for
   3678    the distance codes.  Subsequent tables are also less than or equal to
   3679    those sizes.  These values may be adjusted either when all of the
   3680    codes are shorter than that, in which case the longest code length in
   3681    bits is used, or when the shortest code is *longer* than the requested
   3682    table size, in which case the length of the shortest code in bits is
   3683    used.
   3684 
   3685    There are two different values for the two tables, since they code a
   3686    different number of possibilities each.  The literal/length table
   3687    codes 286 possible values, or in a flat code, a little over eight
   3688    bits.  The distance table codes 30 possible values, or a little less
   3689    than five bits, flat.  The optimum values for speed end up being
   3690    about one bit more than those, so lbits is 8+1 and dbits is 5+1.
   3691    The optimum values may differ though from machine to machine, and
   3692    possibly even between compilers.  Your mileage may vary.
   3693  */
   3694 
   3695 
   3696 /* If BMAX needs to be larger than 16, then h and x[] should be uLong. */
   3697 #define BMAX 15         /* maximum bit length of any code */
   3698 #define N_MAX 288       /* maximum number of codes in any set */
   3699 
   3700 #ifdef DEBUG_ZLIB
   3701   uInt inflate_hufts;
   3702 #endif
   3703 
   3704 local int huft_build(b, n, s, d, e, t, m, zs)
   3705 uIntf *b;               /* code lengths in bits (all assumed <= BMAX) */
   3706 uInt n;                 /* number of codes (assumed <= N_MAX) */
   3707 uInt s;                 /* number of simple-valued codes (0..s-1) */
   3708 uIntf *d;               /* list of base values for non-simple codes */
   3709 uIntf *e;               /* list of extra bits for non-simple codes */
   3710 inflate_huft * FAR *t;  /* result: starting table */
   3711 uIntf *m;               /* maximum lookup bits, returns actual */
   3712 z_stream *zs;           /* for zalloc function */
   3713 /* Given a list of code lengths and a maximum table size, make a set of
   3714    tables to decode that set of codes.  Return Z_OK on success, Z_BUF_ERROR
   3715    if the given code set is incomplete (the tables are still built in this
   3716    case), Z_DATA_ERROR if the input is invalid (all zero length codes or an
   3717    over-subscribed set of lengths), or Z_MEM_ERROR if not enough memory. */
   3718 {
   3719 
   3720   uInt a;                       /* counter for codes of length k */
   3721   uInt c[BMAX+1];               /* bit length count table */
   3722   uInt f;                       /* i repeats in table every f entries */
   3723   int g;                        /* maximum code length */
   3724   int h;                        /* table level */
   3725   register uInt i;              /* counter, current code */
   3726   register uInt j;              /* counter */
   3727   register int k;               /* number of bits in current code */
   3728   int l;                        /* bits per table (returned in m) */
   3729   register uIntf *p;            /* pointer into c[], b[], or v[] */
   3730   inflate_huft *q;              /* points to current table */
   3731   struct inflate_huft_s r;      /* table entry for structure assignment */
   3732   inflate_huft *u[BMAX];        /* table stack */
   3733   uInt v[N_MAX];                /* values in order of bit length */
   3734   register int w;               /* bits before this table == (l * h) */
   3735   uInt x[BMAX+1];               /* bit offsets, then code stack */
   3736   uIntf *xp;                    /* pointer into x */
   3737   int y;                        /* number of dummy codes added */
   3738   uInt z;                       /* number of entries in current table */
   3739 
   3740 
   3741   /* Generate counts for each bit length */
   3742   p = c;
   3743 #define C0 *p++ = 0;
   3744 #define C2 C0 C0 C0 C0
   3745 #define C4 C2 C2 C2 C2
   3746   C4                            /* clear c[]--assume BMAX+1 is 16 */
   3747   p = b;  i = n;
   3748   do {
   3749     c[*p++]++;                  /* assume all entries <= BMAX */
   3750   } while (--i);
   3751   if (c[0] == n)                /* null input--all zero length codes */
   3752   {
   3753     *t = (inflate_huft *)Z_NULL;
   3754     *m = 0;
   3755     return Z_OK;
   3756   }
   3757 
   3758 
   3759   /* Find minimum and maximum length, bound *m by those */
   3760   l = *m;
   3761   for (j = 1; j <= BMAX; j++)
   3762     if (c[j])
   3763       break;
   3764   k = j;                        /* minimum code length */
   3765   if ((uInt)l < j)
   3766     l = j;
   3767   for (i = BMAX; i; i--)
   3768     if (c[i])
   3769       break;
   3770   g = i;                        /* maximum code length */
   3771   if ((uInt)l > i)
   3772     l = i;
   3773   *m = l;
   3774 
   3775 
   3776   /* Adjust last length count to fill out codes, if needed */
   3777   for (y = 1 << j; j < i; j++, y <<= 1)
   3778     if ((y -= c[j]) < 0)
   3779       return Z_DATA_ERROR;
   3780   if ((y -= c[i]) < 0)
   3781     return Z_DATA_ERROR;
   3782   c[i] += y;
   3783 
   3784 
   3785   /* Generate starting offsets into the value table for each length */
   3786   x[1] = j = 0;
   3787   p = c + 1;  xp = x + 2;
   3788   while (--i) {                 /* note that i == g from above */
   3789     *xp++ = (j += *p++);
   3790   }
   3791 
   3792 
   3793   /* Make a table of values in order of bit lengths */
   3794   p = b;  i = 0;
   3795   do {
   3796     if ((j = *p++) != 0)
   3797       v[x[j]++] = i;
   3798   } while (++i < n);
   3799 
   3800 
   3801   /* Generate the Huffman codes and for each, make the table entries */
   3802   x[0] = i = 0;                 /* first Huffman code is zero */
   3803   p = v;                        /* grab values in bit order */
   3804   h = -1;                       /* no tables yet--level -1 */
   3805   w = -l;                       /* bits decoded == (l * h) */
   3806   u[0] = (inflate_huft *)Z_NULL;        /* just to keep compilers happy */
   3807   q = (inflate_huft *)Z_NULL;   /* ditto */
   3808   z = 0;                        /* ditto */
   3809 
   3810   /* go through the bit lengths (k already is bits in shortest code) */
   3811   for (; k <= g; k++)
   3812   {
   3813     a = c[k];
   3814     while (a--)
   3815     {
   3816       /* here i is the Huffman code of length k bits for value *p */
   3817       /* make tables up to required level */
   3818       while (k > w + l)
   3819       {
   3820         h++;
   3821         w += l;                 /* previous table always l bits */
   3822 
   3823         /* compute minimum size table less than or equal to l bits */
   3824         z = (z = g - w) > (uInt)l ? l : z;      /* table size upper limit */
   3825         if ((f = 1 << (j = k - w)) > a + 1)     /* try a k-w bit table */
   3826         {                       /* too few codes for k-w bit table */
   3827           f -= a + 1;           /* deduct codes from patterns left */
   3828           xp = c + k;
   3829           if (j < z)
   3830             while (++j < z)     /* try smaller tables up to z bits */
   3831             {
   3832               if ((f <<= 1) <= *++xp)
   3833                 break;          /* enough codes to use up j bits */
   3834               f -= *xp;         /* else deduct codes from patterns */
   3835             }
   3836         }
   3837         z = 1 << j;             /* table entries for j-bit table */
   3838 
   3839         /* allocate and link in new table */
   3840         if ((q = (inflate_huft *)ZALLOC
   3841              (zs,z + 1,sizeof(inflate_huft))) == Z_NULL)
   3842         {
   3843           if (h)
   3844             inflate_trees_free(u[0], zs);
   3845           return Z_MEM_ERROR;   /* not enough memory */
   3846         }
   3847 	q->word.Nalloc = z + 1;
   3848 #ifdef DEBUG_ZLIB
   3849         inflate_hufts += z + 1;
   3850 #endif
   3851         *t = q + 1;             /* link to list for huft_free() */
   3852         *(t = &(q->next)) = Z_NULL;
   3853         u[h] = ++q;             /* table starts after link */
   3854 
   3855         /* connect to last table, if there is one */
   3856         if (h)
   3857         {
   3858           x[h] = i;             /* save pattern for backing up */
   3859           r.bits = (Byte)l;     /* bits to dump before this table */
   3860           r.exop = (Byte)j;     /* bits in this table */
   3861           r.next = q;           /* pointer to this table */
   3862           j = i >> (w - l);     /* (get around Turbo C bug) */
   3863           u[h-1][j] = r;        /* connect to last table */
   3864         }
   3865       }
   3866 
   3867       /* set up table entry in r */
   3868       r.bits = (Byte)(k - w);
   3869       if (p >= v + n)
   3870         r.exop = 128 + 64;      /* out of values--invalid code */
   3871       else if (*p < s)
   3872       {
   3873         r.exop = (Byte)(*p < 256 ? 0 : 32 + 64);     /* 256 is end-of-block */
   3874         r.base = *p++;          /* simple code is just the value */
   3875       }
   3876       else
   3877       {
   3878         r.exop = (Byte)e[*p - s] + 16 + 64; /* non-simple--look up in lists */
   3879         r.base = d[*p++ - s];
   3880       }
   3881 
   3882       /* fill code-like entries with r */
   3883       f = 1 << (k - w);
   3884       for (j = i >> w; j < z; j += f)
   3885         q[j] = r;
   3886 
   3887       /* backwards increment the k-bit code i */
   3888       for (j = 1 << (k - 1); i & j; j >>= 1)
   3889         i ^= j;
   3890       i ^= j;
   3891 
   3892       /* backup over finished tables */
   3893       while ((i & ((1 << w) - 1)) != x[h])
   3894       {
   3895         h--;                    /* don't need to update q */
   3896         w -= l;
   3897       }
   3898     }
   3899   }
   3900 
   3901 
   3902   /* Return Z_BUF_ERROR if we were given an incomplete table */
   3903   return y != 0 && g != 1 ? Z_BUF_ERROR : Z_OK;
   3904 }
   3905 
   3906 
   3907 local int inflate_trees_bits(c, bb, tb, z)
   3908 uIntf *c;               /* 19 code lengths */
   3909 uIntf *bb;              /* bits tree desired/actual depth */
   3910 inflate_huft * FAR *tb; /* bits tree result */
   3911 z_stream *z;            /* for zfree function */
   3912 {
   3913   int r;
   3914 
   3915   r = huft_build(c, 19, 19, (uIntf*)Z_NULL, (uIntf*)Z_NULL, tb, bb, z);
   3916   if (r == Z_DATA_ERROR)
   3917     z->msg = "oversubscribed dynamic bit lengths tree";
   3918   else if (r == Z_BUF_ERROR)
   3919   {
   3920     inflate_trees_free(*tb, z);
   3921     z->msg = "incomplete dynamic bit lengths tree";
   3922     r = Z_DATA_ERROR;
   3923   }
   3924   return r;
   3925 }
   3926 
   3927 
   3928 local int inflate_trees_dynamic(nl, nd, c, bl, bd, tl, td, z)
   3929 uInt nl;                /* number of literal/length codes */
   3930 uInt nd;                /* number of distance codes */
   3931 uIntf *c;               /* that many (total) code lengths */
   3932 uIntf *bl;              /* literal desired/actual bit depth */
   3933 uIntf *bd;              /* distance desired/actual bit depth */
   3934 inflate_huft * FAR *tl; /* literal/length tree result */
   3935 inflate_huft * FAR *td; /* distance tree result */
   3936 z_stream *z;            /* for zfree function */
   3937 {
   3938   int r;
   3939 
   3940   /* build literal/length tree */
   3941   if ((r = huft_build(c, nl, 257, cplens, cplext, tl, bl, z)) != Z_OK)
   3942   {
   3943     if (r == Z_DATA_ERROR)
   3944       z->msg = "oversubscribed literal/length tree";
   3945     else if (r == Z_BUF_ERROR)
   3946     {
   3947       inflate_trees_free(*tl, z);
   3948       z->msg = "incomplete literal/length tree";
   3949       r = Z_DATA_ERROR;
   3950     }
   3951     return r;
   3952   }
   3953 
   3954   /* build distance tree */
   3955   if ((r = huft_build(c + nl, nd, 0, cpdist, cpdext, td, bd, z)) != Z_OK)
   3956   {
   3957     if (r == Z_DATA_ERROR)
   3958       z->msg = "oversubscribed literal/length tree";
   3959     else if (r == Z_BUF_ERROR) {
   3960 #ifdef PKZIP_BUG_WORKAROUND
   3961       r = Z_OK;
   3962     }
   3963 #else
   3964       inflate_trees_free(*td, z);
   3965       z->msg = "incomplete literal/length tree";
   3966       r = Z_DATA_ERROR;
   3967     }
   3968     inflate_trees_free(*tl, z);
   3969     return r;
   3970 #endif
   3971   }
   3972 
   3973   /* done */
   3974   return Z_OK;
   3975 }
   3976 
   3977 
   3978 /* build fixed tables only once--keep them here */
   3979 local int fixed_lock = 0;
   3980 local int fixed_built = 0;
   3981 #define FIXEDH 530      /* number of hufts used by fixed tables */
   3982 local uInt fixed_left = FIXEDH;
   3983 local inflate_huft fixed_mem[FIXEDH];
   3984 local uInt fixed_bl;
   3985 local uInt fixed_bd;
   3986 local inflate_huft *fixed_tl;
   3987 local inflate_huft *fixed_td;
   3988 
   3989 
   3990 local voidpf falloc(q, n, s)
   3991 voidpf q;        /* opaque pointer (not used) */
   3992 uInt n;         /* number of items */
   3993 uInt s;         /* size of item */
   3994 {
   3995   Assert(s == sizeof(inflate_huft) && n <= fixed_left,
   3996          "inflate_trees falloc overflow");
   3997   if (q) s++; /* to make some compilers happy */
   3998   fixed_left -= n;
   3999   return (voidpf)(fixed_mem + fixed_left);
   4000 }
   4001 
   4002 
   4003 local void ffree(q, p, n)
   4004 voidpf q;
   4005 voidpf p;
   4006 uInt n;
   4007 {
   4008   Assert(0, "inflate_trees ffree called!");
   4009   if (q) q = p; /* to make some compilers happy */
   4010 }
   4011 
   4012 
   4013 local int inflate_trees_fixed(bl, bd, tl, td)
   4014 uIntf *bl;               /* literal desired/actual bit depth */
   4015 uIntf *bd;               /* distance desired/actual bit depth */
   4016 inflate_huft * FAR *tl;  /* literal/length tree result */
   4017 inflate_huft * FAR *td;  /* distance tree result */
   4018 {
   4019   /* build fixed tables if not built already--lock out other instances */
   4020   while (++fixed_lock > 1)
   4021     fixed_lock--;
   4022   if (!fixed_built)
   4023   {
   4024     int k;              /* temporary variable */
   4025     unsigned c[288];    /* length list for huft_build */
   4026     z_stream z;         /* for falloc function */
   4027 
   4028     /* set up fake z_stream for memory routines */
   4029     z.zalloc = falloc;
   4030     z.zfree = ffree;
   4031     z.opaque = Z_NULL;
   4032 
   4033     /* literal table */
   4034     for (k = 0; k < 144; k++)
   4035       c[k] = 8;
   4036     for (; k < 256; k++)
   4037       c[k] = 9;
   4038     for (; k < 280; k++)
   4039       c[k] = 7;
   4040     for (; k < 288; k++)
   4041       c[k] = 8;
   4042     fixed_bl = 7;
   4043     huft_build(c, 288, 257, cplens, cplext, &fixed_tl, &fixed_bl, &z);
   4044 
   4045     /* distance table */
   4046     for (k = 0; k < 30; k++)
   4047       c[k] = 5;
   4048     fixed_bd = 5;
   4049     huft_build(c, 30, 0, cpdist, cpdext, &fixed_td, &fixed_bd, &z);
   4050 
   4051     /* done */
   4052     fixed_built = 1;
   4053   }
   4054   fixed_lock--;
   4055   *bl = fixed_bl;
   4056   *bd = fixed_bd;
   4057   *tl = fixed_tl;
   4058   *td = fixed_td;
   4059   return Z_OK;
   4060 }
   4061 
   4062 
   4063 local int inflate_trees_free(t, z)
   4064 inflate_huft *t;        /* table to free */
   4065 z_stream *z;            /* for zfree function */
   4066 /* Free the malloc'ed tables built by huft_build(), which makes a linked
   4067    list of the tables it made, with the links in a dummy first entry of
   4068    each table. */
   4069 {
   4070   register inflate_huft *p, *q;
   4071 
   4072   /* Go through linked list, freeing from the malloced (t[-1]) address. */
   4073   p = t;
   4074   while (p != Z_NULL)
   4075   {
   4076     q = (--p)->next;
   4077     ZFREE(z, p, p->word.Nalloc * sizeof(inflate_huft));
   4078     p = q;
   4079   }
   4080   return Z_OK;
   4081 }
   4082 
   4083 /*+++++*/
   4084 /* infcodes.c -- process literals and length/distance pairs
   4085  * Copyright (C) 1995 Mark Adler
   4086  * For conditions of distribution and use, see copyright notice in zlib.h
   4087  */
   4088 
   4089 /* simplify the use of the inflate_huft type with some defines */
   4090 #define base more.Base
   4091 #define next more.Next
   4092 #define exop word.what.Exop
   4093 #define bits word.what.Bits
   4094 
   4095 /* inflate codes private state */
   4096 struct inflate_codes_state {
   4097 
   4098   /* mode */
   4099   enum {        /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
   4100       START,    /* x: set up for LEN */
   4101       LEN,      /* i: get length/literal/eob next */
   4102       LENEXT,   /* i: getting length extra (have base) */
   4103       DIST,     /* i: get distance next */
   4104       DISTEXT,  /* i: getting distance extra */
   4105       COPY,     /* o: copying bytes in window, waiting for space */
   4106       LIT,      /* o: got literal, waiting for output space */
   4107       WASH,     /* o: got eob, possibly still output waiting */
   4108       END,      /* x: got eob and all data flushed */
   4109       BADCODE}  /* x: got error */
   4110     mode;               /* current inflate_codes mode */
   4111 
   4112   /* mode dependent information */
   4113   uInt len;
   4114   union {
   4115     struct {
   4116       inflate_huft *tree;       /* pointer into tree */
   4117       uInt need;                /* bits needed */
   4118     } code;             /* if LEN or DIST, where in tree */
   4119     uInt lit;           /* if LIT, literal */
   4120     struct {
   4121       uInt get;                 /* bits to get for extra */
   4122       uInt dist;                /* distance back to copy from */
   4123     } copy;             /* if EXT or COPY, where and how much */
   4124   } sub;                /* submode */
   4125 
   4126   /* mode independent information */
   4127   Byte lbits;           /* ltree bits decoded per branch */
   4128   Byte dbits;           /* dtree bits decoder per branch */
   4129   inflate_huft *ltree;          /* literal/length/eob tree */
   4130   inflate_huft *dtree;          /* distance tree */
   4131 
   4132 };
   4133 
   4134 
   4135 local inflate_codes_statef *inflate_codes_new(bl, bd, tl, td, z)
   4136 uInt bl, bd;
   4137 inflate_huft *tl, *td;
   4138 z_stream *z;
   4139 {
   4140   inflate_codes_statef *c;
   4141 
   4142   if ((c = (inflate_codes_statef *)
   4143        ZALLOC(z,1,sizeof(struct inflate_codes_state))) != Z_NULL)
   4144   {
   4145     c->mode = START;
   4146     c->lbits = (Byte)bl;
   4147     c->dbits = (Byte)bd;
   4148     c->ltree = tl;
   4149     c->dtree = td;
   4150     Tracev((stderr, "inflate:       codes new\n"));
   4151   }
   4152   return c;
   4153 }
   4154 
   4155 
   4156 local int inflate_codes(s, z, r)
   4157 inflate_blocks_statef *s;
   4158 z_stream *z;
   4159 int r;
   4160 {
   4161   uInt j;               /* temporary storage */
   4162   inflate_huft *t;      /* temporary pointer */
   4163   uInt e;               /* extra bits or operation */
   4164   uLong b;              /* bit buffer */
   4165   uInt k;               /* bits in bit buffer */
   4166   Bytef *p;             /* input data pointer */
   4167   uInt n;               /* bytes available there */
   4168   Bytef *q;             /* output window write pointer */
   4169   uInt m;               /* bytes to end of window or read pointer */
   4170   Bytef *f;             /* pointer to copy strings from */
   4171   inflate_codes_statef *c = s->sub.decode.codes;  /* codes state */
   4172 
   4173   /* copy input/output information to locals (UPDATE macro restores) */
   4174   LOAD
   4175 
   4176   /* process input and output based on current state */
   4177   while (1) switch (c->mode)
   4178   {             /* waiting for "i:"=input, "o:"=output, "x:"=nothing */
   4179     case START:         /* x: set up for LEN */
   4180 #ifndef SLOW
   4181       if (m >= 258 && n >= 10)
   4182       {
   4183         UPDATE
   4184         r = inflate_fast(c->lbits, c->dbits, c->ltree, c->dtree, s, z);
   4185         LOAD
   4186         if (r != Z_OK)
   4187         {
   4188           c->mode = r == Z_STREAM_END ? WASH : BADCODE;
   4189           break;
   4190         }
   4191       }
   4192 #endif /* !SLOW */
   4193       c->sub.code.need = c->lbits;
   4194       c->sub.code.tree = c->ltree;
   4195       c->mode = LEN;
   4196     case LEN:           /* i: get length/literal/eob next */
   4197       j = c->sub.code.need;
   4198       NEEDBITS(j)
   4199       t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
   4200       DUMPBITS(t->bits)
   4201       e = (uInt)(t->exop);
   4202       if (e == 0)               /* literal */
   4203       {
   4204         c->sub.lit = t->base;
   4205         Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
   4206                  "inflate:         literal '%c'\n" :
   4207                  "inflate:         literal 0x%02x\n", t->base));
   4208         c->mode = LIT;
   4209         break;
   4210       }
   4211       if (e & 16)               /* length */
   4212       {
   4213         c->sub.copy.get = e & 15;
   4214         c->len = t->base;
   4215         c->mode = LENEXT;
   4216         break;
   4217       }
   4218       if ((e & 64) == 0)        /* next table */
   4219       {
   4220         c->sub.code.need = e;
   4221         c->sub.code.tree = t->next;
   4222         break;
   4223       }
   4224       if (e & 32)               /* end of block */
   4225       {
   4226         Tracevv((stderr, "inflate:         end of block\n"));
   4227         c->mode = WASH;
   4228         break;
   4229       }
   4230       c->mode = BADCODE;        /* invalid code */
   4231       z->msg = "invalid literal/length code";
   4232       r = Z_DATA_ERROR;
   4233       LEAVE
   4234     case LENEXT:        /* i: getting length extra (have base) */
   4235       j = c->sub.copy.get;
   4236       NEEDBITS(j)
   4237       c->len += (uInt)b & inflate_mask[j];
   4238       DUMPBITS(j)
   4239       c->sub.code.need = c->dbits;
   4240       c->sub.code.tree = c->dtree;
   4241       Tracevv((stderr, "inflate:         length %u\n", c->len));
   4242       c->mode = DIST;
   4243     case DIST:          /* i: get distance next */
   4244       j = c->sub.code.need;
   4245       NEEDBITS(j)
   4246       t = c->sub.code.tree + ((uInt)b & inflate_mask[j]);
   4247       DUMPBITS(t->bits)
   4248       e = (uInt)(t->exop);
   4249       if (e & 16)               /* distance */
   4250       {
   4251         c->sub.copy.get = e & 15;
   4252         c->sub.copy.dist = t->base;
   4253         c->mode = DISTEXT;
   4254         break;
   4255       }
   4256       if ((e & 64) == 0)        /* next table */
   4257       {
   4258         c->sub.code.need = e;
   4259         c->sub.code.tree = t->next;
   4260         break;
   4261       }
   4262       c->mode = BADCODE;        /* invalid code */
   4263       z->msg = "invalid distance code";
   4264       r = Z_DATA_ERROR;
   4265       LEAVE
   4266     case DISTEXT:       /* i: getting distance extra */
   4267       j = c->sub.copy.get;
   4268       NEEDBITS(j)
   4269       c->sub.copy.dist += (uInt)b & inflate_mask[j];
   4270       DUMPBITS(j)
   4271       Tracevv((stderr, "inflate:         distance %u\n", c->sub.copy.dist));
   4272       c->mode = COPY;
   4273     case COPY:          /* o: copying bytes in window, waiting for space */
   4274 #ifndef __TURBOC__ /* Turbo C bug for following expression */
   4275       f = (uInt)(q - s->window) < c->sub.copy.dist ?
   4276           s->end - (c->sub.copy.dist - (q - s->window)) :
   4277           q - c->sub.copy.dist;
   4278 #else
   4279       f = q - c->sub.copy.dist;
   4280       if ((uInt)(q - s->window) < c->sub.copy.dist)
   4281         f = s->end - (c->sub.copy.dist - (q - s->window));
   4282 #endif
   4283       while (c->len)
   4284       {
   4285         NEEDOUT
   4286         OUTBYTE(*f++)
   4287         if (f == s->end)
   4288           f = s->window;
   4289         c->len--;
   4290       }
   4291       c->mode = START;
   4292       break;
   4293     case LIT:           /* o: got literal, waiting for output space */
   4294       NEEDOUT
   4295       OUTBYTE(c->sub.lit)
   4296       c->mode = START;
   4297       break;
   4298     case WASH:          /* o: got eob, possibly more output */
   4299       FLUSH
   4300       if (s->read != s->write)
   4301         LEAVE
   4302       c->mode = END;
   4303     case END:
   4304       r = Z_STREAM_END;
   4305       LEAVE
   4306     case BADCODE:       /* x: got error */
   4307       r = Z_DATA_ERROR;
   4308       LEAVE
   4309     default:
   4310       r = Z_STREAM_ERROR;
   4311       LEAVE
   4312   }
   4313 }
   4314 
   4315 
   4316 local void inflate_codes_free(c, z)
   4317 inflate_codes_statef *c;
   4318 z_stream *z;
   4319 {
   4320   ZFREE(z, c, sizeof(struct inflate_codes_state));
   4321   Tracev((stderr, "inflate:       codes free\n"));
   4322 }
   4323 
   4324 /*+++++*/
   4325 /* inflate_util.c -- data and routines common to blocks and codes
   4326  * Copyright (C) 1995 Mark Adler
   4327  * For conditions of distribution and use, see copyright notice in zlib.h
   4328  */
   4329 
   4330 /* copy as much as possible from the sliding window to the output area */
   4331 local int inflate_flush(s, z, r)
   4332 inflate_blocks_statef *s;
   4333 z_stream *z;
   4334 int r;
   4335 {
   4336   uInt n;
   4337   Bytef *p, *q;
   4338 
   4339   /* local copies of source and destination pointers */
   4340   p = z->next_out;
   4341   q = s->read;
   4342 
   4343   /* compute number of bytes to copy as far as end of window */
   4344   n = (uInt)((q <= s->write ? s->write : s->end) - q);
   4345   if (n > z->avail_out) n = z->avail_out;
   4346   if (n && r == Z_BUF_ERROR) r = Z_OK;
   4347 
   4348   /* update counters */
   4349   z->avail_out -= n;
   4350   z->total_out += n;
   4351 
   4352   /* update check information */
   4353   if (s->checkfn != Z_NULL)
   4354     s->check = (*s->checkfn)(s->check, q, n);
   4355 
   4356   /* copy as far as end of window */
   4357   if (p != NULL) {
   4358     zmemcpy(p, q, n);
   4359     p += n;
   4360   }
   4361   q += n;
   4362 
   4363   /* see if more to copy at beginning of window */
   4364   if (q == s->end)
   4365   {
   4366     /* wrap pointers */
   4367     q = s->window;
   4368     if (s->write == s->end)
   4369       s->write = s->window;
   4370 
   4371     /* compute bytes to copy */
   4372     n = (uInt)(s->write - q);
   4373     if (n > z->avail_out) n = z->avail_out;
   4374     if (n && r == Z_BUF_ERROR) r = Z_OK;
   4375 
   4376     /* update counters */
   4377     z->avail_out -= n;
   4378     z->total_out += n;
   4379 
   4380     /* update check information */
   4381     if (s->checkfn != Z_NULL)
   4382       s->check = (*s->checkfn)(s->check, q, n);
   4383 
   4384     /* copy */
   4385     if (p != NULL) {
   4386       zmemcpy(p, q, n);
   4387       p += n;
   4388     }
   4389     q += n;
   4390   }
   4391 
   4392   /* update pointers */
   4393   z->next_out = p;
   4394   s->read = q;
   4395 
   4396   /* done */
   4397   return r;
   4398 }
   4399 
   4400 
   4401 /*+++++*/
   4402 /* inffast.c -- process literals and length/distance pairs fast
   4403  * Copyright (C) 1995 Mark Adler
   4404  * For conditions of distribution and use, see copyright notice in zlib.h
   4405  */
   4406 
   4407 /* simplify the use of the inflate_huft type with some defines */
   4408 #define base more.Base
   4409 #define next more.Next
   4410 #define exop word.what.Exop
   4411 #define bits word.what.Bits
   4412 
   4413 /* macros for bit input with no checking and for returning unused bytes */
   4414 #define GRABBITS(j) {while(k<(j)){b|=((uLong)NEXTBYTE)<<k;k+=8;}}
   4415 #define UNGRAB {n+=(c=k>>3);p-=c;k&=7;}
   4416 
   4417 /* Called with number of bytes left to write in window at least 258
   4418    (the maximum string length) and number of input bytes available
   4419    at least ten.  The ten bytes are six bytes for the longest length/
   4420    distance pair plus four bytes for overloading the bit buffer. */
   4421 
   4422 local int inflate_fast(bl, bd, tl, td, s, z)
   4423 uInt bl, bd;
   4424 inflate_huft *tl, *td;
   4425 inflate_blocks_statef *s;
   4426 z_stream *z;
   4427 {
   4428   inflate_huft *t;      /* temporary pointer */
   4429   uInt e;               /* extra bits or operation */
   4430   uLong b;              /* bit buffer */
   4431   uInt k;               /* bits in bit buffer */
   4432   Bytef *p;             /* input data pointer */
   4433   uInt n;               /* bytes available there */
   4434   Bytef *q;             /* output window write pointer */
   4435   uInt m;               /* bytes to end of window or read pointer */
   4436   uInt ml;              /* mask for literal/length tree */
   4437   uInt md;              /* mask for distance tree */
   4438   uInt c;               /* bytes to copy */
   4439   uInt d;               /* distance back to copy from */
   4440   Bytef *r;             /* copy source pointer */
   4441 
   4442   /* load input, output, bit values */
   4443   LOAD
   4444 
   4445   /* initialize masks */
   4446   ml = inflate_mask[bl];
   4447   md = inflate_mask[bd];
   4448 
   4449   /* do until not enough input or output space for fast loop */
   4450   do {                          /* assume called with m >= 258 && n >= 10 */
   4451     /* get literal/length code */
   4452     GRABBITS(20)                /* max bits for literal/length code */
   4453     if ((e = (t = tl + ((uInt)b & ml))->exop) == 0)
   4454     {
   4455       DUMPBITS(t->bits)
   4456       Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
   4457                 "inflate:         * literal '%c'\n" :
   4458                 "inflate:         * literal 0x%02x\n", t->base));
   4459       *q++ = (Byte)t->base;
   4460       m--;
   4461       continue;
   4462     }
   4463     do {
   4464       DUMPBITS(t->bits)
   4465       if (e & 16)
   4466       {
   4467         /* get extra bits for length */
   4468         e &= 15;
   4469         c = t->base + ((uInt)b & inflate_mask[e]);
   4470         DUMPBITS(e)
   4471         Tracevv((stderr, "inflate:         * length %u\n", c));
   4472 
   4473         /* decode distance base of block to copy */
   4474         GRABBITS(15);           /* max bits for distance code */
   4475         e = (t = td + ((uInt)b & md))->exop;
   4476         do {
   4477           DUMPBITS(t->bits)
   4478           if (e & 16)
   4479           {
   4480             /* get extra bits to add to distance base */
   4481             e &= 15;
   4482             GRABBITS(e)         /* get extra bits (up to 13) */
   4483             d = t->base + ((uInt)b & inflate_mask[e]);
   4484             DUMPBITS(e)
   4485             Tracevv((stderr, "inflate:         * distance %u\n", d));
   4486 
   4487             /* do the copy */
   4488             m -= c;
   4489             if ((uInt)(q - s->window) >= d)     /* offset before dest */
   4490             {                                   /*  just copy */
   4491               r = q - d;
   4492               *q++ = *r++;  c--;        /* minimum count is three, */
   4493               *q++ = *r++;  c--;        /*  so unroll loop a little */
   4494             }
   4495             else                        /* else offset after destination */
   4496             {
   4497               e = d - (q - s->window);  /* bytes from offset to end */
   4498               r = s->end - e;           /* pointer to offset */
   4499               if (c > e)                /* if source crosses, */
   4500               {
   4501                 c -= e;                 /* copy to end of window */
   4502                 do {
   4503                   *q++ = *r++;
   4504                 } while (--e);
   4505                 r = s->window;          /* copy rest from start of window */
   4506               }
   4507             }
   4508             do {                        /* copy all or what's left */
   4509               *q++ = *r++;
   4510             } while (--c);
   4511             break;
   4512           }
   4513           else if ((e & 64) == 0)
   4514             e = (t = t->next + ((uInt)b & inflate_mask[e]))->exop;
   4515           else
   4516           {
   4517             z->msg = "invalid distance code";
   4518             UNGRAB
   4519             UPDATE
   4520             return Z_DATA_ERROR;
   4521           }
   4522         } while (1);
   4523         break;
   4524       }
   4525       if ((e & 64) == 0)
   4526       {
   4527         if ((e = (t = t->next + ((uInt)b & inflate_mask[e]))->exop) == 0)
   4528         {
   4529           DUMPBITS(t->bits)
   4530           Tracevv((stderr, t->base >= 0x20 && t->base < 0x7f ?
   4531                     "inflate:         * literal '%c'\n" :
   4532                     "inflate:         * literal 0x%02x\n", t->base));
   4533           *q++ = (Byte)t->base;
   4534           m--;
   4535           break;
   4536         }
   4537       }
   4538       else if (e & 32)
   4539       {
   4540         Tracevv((stderr, "inflate:         * end of block\n"));
   4541         UNGRAB
   4542         UPDATE
   4543         return Z_STREAM_END;
   4544       }
   4545       else
   4546       {
   4547         z->msg = "invalid literal/length code";
   4548         UNGRAB
   4549         UPDATE
   4550         return Z_DATA_ERROR;
   4551       }
   4552     } while (1);
   4553   } while (m >= 258 && n >= 10);
   4554 
   4555   /* not enough input or output--restore pointers and return */
   4556   UNGRAB
   4557   UPDATE
   4558   return Z_OK;
   4559 }
   4560 
   4561 
   4562 /*+++++*/
   4563 /* zutil.c -- target dependent utility functions for the compression library
   4564  * Copyright (C) 1995 Jean-loup Gailly.
   4565  * For conditions of distribution and use, see copyright notice in zlib.h
   4566  */
   4567 
   4568 /* From: zutil.c,v 1.8 1995/05/03 17:27:12 jloup Exp */
   4569 
   4570 char *zlib_version = ZLIB_VERSION;
   4571 
   4572 char *z_errmsg[] = {
   4573 "stream end",          /* Z_STREAM_END    1 */
   4574 "",                    /* Z_OK            0 */
   4575 "file error",          /* Z_ERRNO        (-1) */
   4576 "stream error",        /* Z_STREAM_ERROR (-2) */
   4577 "data error",          /* Z_DATA_ERROR   (-3) */
   4578 "insufficient memory", /* Z_MEM_ERROR    (-4) */
   4579 "buffer error",        /* Z_BUF_ERROR    (-5) */
   4580 ""};
   4581 
   4582 
   4583 /*+++++*/
   4584 /* adler32.c -- compute the Adler-32 checksum of a data stream
   4585  * Copyright (C) 1995 Mark Adler
   4586  * For conditions of distribution and use, see copyright notice in zlib.h
   4587  */
   4588 
   4589 /* From: adler32.c,v 1.6 1995/05/03 17:27:08 jloup Exp */
   4590 
   4591 #define BASE 65521L /* largest prime smaller than 65536 */
   4592 #define NMAX 5552
   4593 /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
   4594 
   4595 #define DO1(buf)  {s1 += *buf++; s2 += s1;}
   4596 #define DO2(buf)  DO1(buf); DO1(buf);
   4597 #define DO4(buf)  DO2(buf); DO2(buf);
   4598 #define DO8(buf)  DO4(buf); DO4(buf);
   4599 #define DO16(buf) DO8(buf); DO8(buf);
   4600 
   4601 /* ========================================================================= */
   4602 uLong adler32(adler, buf, len)
   4603     uLong adler;
   4604     Bytef *buf;
   4605     uInt len;
   4606 {
   4607     unsigned long s1 = adler & 0xffff;
   4608     unsigned long s2 = (adler >> 16) & 0xffff;
   4609     int k;
   4610 
   4611     if (buf == Z_NULL) return 1L;
   4612 
   4613     while (len > 0) {
   4614         k = len < NMAX ? len : NMAX;
   4615         len -= k;
   4616         while (k >= 16) {
   4617             DO16(buf);
   4618             k -= 16;
   4619         }
   4620         if (k != 0) do {
   4621             DO1(buf);
   4622         } while (--k);
   4623         s1 %= BASE;
   4624         s2 %= BASE;
   4625     }
   4626     return (s2 << 16) | s1;
   4627 }
   4628