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