1 unit Trees;
2 
3 {$T-}
4 {$define ORG_DEBUG}
5 {
6   trees.c -- output deflated data using Huffman coding
7   Copyright (C) 1995-1998 Jean-loup Gailly
8 
9   Pascal tranlastion
10   Copyright (C) 1998 by Jacques Nomssi Nzali
11   For conditions of distribution and use, see copyright notice in readme.txt
12 }
13 
14 {
15  *  ALGORITHM
16  *
17  *      The "deflation" process uses several Huffman trees. The more
18  *      common source values are represented by shorter bit sequences.
19  *
20  *      Each code tree is stored in a compressed form which is itself
21  * a Huffman encoding of the lengths of all the code strings (in
22  * ascending order by source values).  The actual code strings are
23  * reconstructed from the lengths in the inflate process, as described
24  * in the deflate specification.
25  *
26  *  REFERENCES
27  *
28  *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
29  *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
30  *
31  *      Storer, James A.
32  *          Data Compression:  Methods and Theory, pp. 49-50.
33  *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
34  *
35  *      Sedgewick, R.
36  *          Algorithms, p290.
37  *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
38  }
39 
40 interface
41 
42 {$I zconf.inc}
43 
44 uses
45   {$ifdef ZLIB_DEBUG}
46   sysutils,
47   {$endif}
48   zbase
49   ;
50 
51 { ===========================================================================
52   Internal compression state. }
53 
54 const
55   LENGTH_CODES = 29;
56 { number of length codes, not counting the special END_BLOCK code }
57 
58   LITERALS = 256;
59 { number of literal bytes 0..255 }
60 
61   L_CODES = (LITERALS+1+LENGTH_CODES);
62 { number of Literal or Length codes, including the END_BLOCK code }
63 
64   D_CODES = 30;
65 { number of distance codes }
66 
67   BL_CODES = 19;
68 { number of codes used to transfer the bit lengths }
69 
70   HEAP_SIZE = (2*L_CODES+1);
71 { maximum heap size }
72 
73   MAX_BITS = 15;
74 { All codes must not exceed MAX_BITS bits }
75 
76 const
77   INIT_STATE =  42;
78   BUSY_STATE =  113;
79   FINISH_STATE = 666;
80 { Stream status }
81 
82 
83 { Data structure describing a single value and its code string. }
84 type
85   ct_data_ptr = ^ct_data;
86   ct_data = record
87     fc : record
88       case byte of
89       0:(freq : word);       { frequency count }
90       1:(code : word);       { bit string }
91     end;
92     dl : record
93       case byte of
94       0:(dad : word);        { father node in Huffman tree }
95       1:(len : word);        { length of bit string }
96     end;
97   end;
98 
99 { Freq = fc.freq
100  Code = fc.code
101  Dad = dl.dad
102  Len = dl.len }
103 
104 type
105   ltree_type = array[0..HEAP_SIZE-1] of ct_data;    { literal and length tree }
106   dtree_type = array[0..2*D_CODES+1-1] of ct_data;  { distance tree }
107   htree_type = array[0..2*BL_CODES+1-1] of ct_data;  { Huffman tree for bit lengths }
108   { generic tree type }
109   tree_type = array[0..(maxzbaseint div SizeOf(ct_data))-1] of ct_data;
110 
111   tree_ptr = ^ct_data;
112   ltree_ptr = ^ltree_type;
113   dtree_ptr = ^dtree_type;
114   htree_ptr = ^htree_type;
115 
116 
117 type
118   static_tree_desc_ptr = ^static_tree_desc;
119   static_tree_desc =
120          record
121     {const} static_tree : tree_ptr;     { static tree or NIL }
122     {const} extra_bits : pinteger;   { extra bits for each code or NIL }
123             extra_base : integer;           { base index for extra_bits }
124             elems : integer;                { max number of elements in the tree }
125             max_length : integer;           { max bit length for the codes }
126           end;
127 
128   tree_desc_ptr = ^tree_desc;
129   tree_desc = record
130     dyn_tree : tree_ptr;    { the dynamic tree }
131     max_code : integer;            { largest code with non zero frequency }
132     stat_desc : static_tree_desc_ptr; { the corresponding static tree }
133   end;
134 
135 type
136   Pos = word;
137   Posf = Pos; {FAR}
138   IPos = cardinal;
139 
140   pPosf = ^Posf;
141 
142   zPosfArray = array[0..(maxzbaseint div SizeOf(Posf))-1] of Posf;
143   pzPosfArray = ^zPosfArray;
144 
145 { A Pos is an index in the character window. We use short instead of integer to
146   save space in the various tables. IPos is used only for parameter passing.}
147 
148 type
149   deflate_state_ptr = ^deflate_state;
150   deflate_state = record
151     strm : z_streamp;          { pointer back to this zlib stream }
152     status : integer;              { as the name implies }
153     pending_buf : Pbytearray; { output still pending }
154     pending_buf_size : longint;    { size of pending_buf }
155     pending_out : Pbyte;      { next pending byte to output to the stream }
156     pending : longint;             { nb of bytes in the pending buffer }
157     noheader : integer;            { suppress zlib header and adler32 }
158     data_type : Byte;          { UNKNOWN, BINARY or ASCII }
159     method : Byte;             { STORED (for zip only) or DEFLATED }
160     last_flush : integer;          { value of flush param for previous deflate call }
161 
162                 { used by deflate.pas: }
163 
164     w_size : cardinal;             { LZ77 window size (32K by default) }
165     w_bits : cardinal;             { log2(w_size)  (8..16) }
166     w_mask : cardinal;             { w_size - 1 }
167 
168     window : Pbytearray;
169     { Sliding window. Input bytes are read into the second half of the window,
170       and move to the first half later to keep a dictionary of at least wSize
171       bytes. With this organization, matches are limited to a distance of
172       wSize-MAX_MATCH bytes, but this ensures that IO is always
173       performed with a length multiple of the block size. Also, it limits
174       the window size to 64K, which is quite useful on MSDOS.
175       To do: use the user input buffer as sliding window. }
176 
177     window_size : longint;
178     { Actual size of window: 2*wSize, except when the user input buffer
179       is directly used as sliding window. }
180 
181     prev : pzPosfArray;
182     { Link to older string with same hash index. To limit the size of this
183       array to 64K, this link is maintained only for the last 32K strings.
184       An index in this array is thus a window index modulo 32K. }
185 
186     head : pzPosfArray;    { Heads of the hash chains or NIL. }
187 
188     ins_h : cardinal;          { hash index of string to be inserted }
189     hash_size : cardinal;      { number of elements in hash table }
190     hash_bits : cardinal;      { log2(hash_size) }
191     hash_mask : cardinal;      { hash_size-1 }
192 
193     hash_shift : cardinal;
194     { Number of bits by which ins_h must be shifted at each input
195       step. It must be such that after MIN_MATCH steps, the oldest
196       byte no longer takes part in the hash key, that is:
197         hash_shift * MIN_MATCH >= hash_bits     }
198 
199     block_start : longint;
200     { Window position at the beginning of the current output block. Gets
201       negative when the window is moved backwards. }
202 
203     match_length : cardinal;           { length of best match }
204     prev_match : IPos;             { previous match }
205     match_available : boolean;     { set if previous match exists }
206     strstart : cardinal;               { start of string to insert }
207     match_start : cardinal;            { start of matching string }
208     lookahead : cardinal;              { number of valid bytes ahead in window }
209 
210     prev_length : cardinal;
211     { Length of the best match at previous step. Matches not greater than this
212       are discarded. This is used in the lazy match evaluation. }
213 
214     max_chain_length : cardinal;
215     { To speed up deflation, hash chains are never searched beyond this
216       length.  A higher limit improves compression ratio but degrades the
217       speed. }
218 
219     { moved to the end because Borland Pascal won't accept the following:
220     max_lazy_match : cardinal;
221     max_insert_length : cardinal absolute max_lazy_match;
222     }
223 
224     level : integer;    { compression level (1..9) }
225     strategy : integer; { favor or force Huffman coding}
226 
227     good_match : cardinal;
228     { Use a faster search when the previous match is longer than this }
229 
230     nice_match : integer; { Stop searching when current match exceeds this }
231 
232                 { used by trees.pas: }
233     { Didn't use ct_data typedef below to supress compiler warning }
234     dyn_ltree : ltree_type;    { literal and length tree }
235     dyn_dtree : dtree_type;  { distance tree }
236     bl_tree : htree_type;   { Huffman tree for bit lengths }
237 
238     l_desc : tree_desc;                { desc. for literal tree }
239     d_desc : tree_desc;                { desc. for distance tree }
240     bl_desc : tree_desc;               { desc. for bit length tree }
241 
242     bl_count : array[0..MAX_BITS+1-1] of word;
243     { number of codes at each bit length for an optimal tree }
244 
245     heap : array[0..2*L_CODES+1-1] of integer; { heap used to build the Huffman trees }
246     heap_len : integer;                   { number of elements in the heap }
247     heap_max : integer;                   { element of largest frequency }
248     { The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
249       The same heap array is used to build all trees. }
250 
251     depth : array[0..2*L_CODES+1-1] of byte;
252     { Depth of each subtree used as tie breaker for trees of equal frequency }
253 
254 
255     l_buf : Pbytearray;       { buffer for literals or lengths }
256 
257     lit_bufsize : cardinal;
258     { Size of match buffer for literals/lengths.  There are 4 reasons for
259       limiting lit_bufsize to 64K:
260         - frequencies can be kept in 16 bit counters
261         - if compression is not successful for the first block, all input
262           data is still in the window so we can still emit a stored block even
263           when input comes from standard input.  (This can also be done for
264           all blocks if lit_bufsize is not greater than 32K.)
265         - if compression is not successful for a file smaller than 64K, we can
266           even emit a stored file instead of a stored block (saving 5 bytes).
267           This is applicable only for zip (not gzip or zlib).
268         - creating new Huffman trees less frequently may not provide fast
269           adaptation to changes in the input data statistics. (Take for
270           example a binary file with poorly compressible code followed by
271           a highly compressible string table.) Smaller buffer sizes give
272           fast adaptation but have of course the overhead of transmitting
273           trees more frequently.
274         - I can't count above 4 }
275 
276 
277     last_lit : cardinal;      { running index in l_buf }
278 
279     d_buf : Pwordarray;
280     { Buffer for distances. To simplify the code, d_buf and l_buf have
281       the same number of elements. To use different lengths, an extra flag
282       array would be necessary. }
283 
284     opt_len : longint;        { bit length of current block with optimal trees }
285     static_len : longint;     { bit length of current block with static trees }
286     compressed_len : longint; { total bit length of compressed file }
287     matches : cardinal;       { number of string matches in current block }
288     last_eob_len : integer;   { bit length of EOB code for last block }
289 
290 {$ifdef ZLIB_DEBUG}
291     bits_sent : longint;    { bit length of the compressed data }
292 {$endif}
293 
294     bi_buf : word;
295     { Output buffer. bits are inserted starting at the bottom (least
296       significant bits). }
297 
298     bi_valid : integer;
299     { Number of valid bits in bi_buf.  All bits above the last valid bit
300       are always zero. }
301 
302     case byte of
303     0:(max_lazy_match : cardinal);
304     { Attempt to find a better match only when the current match is strictly
305       smaller than this value. This mechanism is used only for compression
306       levels >= 4. }
307 
308     1:(max_insert_length : cardinal);
309     { Insert new strings in the hash table only if the match length is not
310       greater than this length. This saves time but degrades compression.
311       max_insert_length is used only for compression levels <= 3. }
312   end;
313 
314 procedure _tr_init (var s : deflate_state);
315 
_tr_tallynull316 function _tr_tally (var s : deflate_state;
317                     dist : cardinal;
318                     lc : cardinal) : boolean;
319 
_tr_flush_blocknull320 function _tr_flush_block (var s : deflate_state;
321                           buf : Pbyte;
322                           stored_len : longint;
323 			  eof : boolean) : longint;
324 
325 procedure _tr_align(var s : deflate_state);
326 
327 procedure _tr_stored_block(var s : deflate_state;
328                            buf : Pbyte;
329                            stored_len : longint;
330                            eof : boolean);
331 
332 implementation
333 
334 { #define GEN_TREES_H }
335 
336 {$ifndef GEN_TREES_H}
337 { header created automatically with -DGEN_TREES_H }
338 
339 const
340   DIST_CODE_LEN = 512; { see definition of array dist_code below }
341 
342 { The static literal tree. Since the bit lengths are imposed, there is no
343   need for the L_CODES extra codes used during heap construction. However
344   The codes 286 and 287 are needed to build a canonical tree (see _tr_init
345   below). }
346 const
347   static_ltree : array[0..L_CODES+2-1] of ct_data = (
348 { fc:(freq, code) dl:(dad,len) }
349 (fc:(freq: 12);dl:(len: 8)), (fc:(freq:140);dl:(len: 8)), (fc:(freq: 76);dl:(len: 8)),
350 (fc:(freq:204);dl:(len: 8)), (fc:(freq: 44);dl:(len: 8)), (fc:(freq:172);dl:(len: 8)),
351 (fc:(freq:108);dl:(len: 8)), (fc:(freq:236);dl:(len: 8)), (fc:(freq: 28);dl:(len: 8)),
352 (fc:(freq:156);dl:(len: 8)), (fc:(freq: 92);dl:(len: 8)), (fc:(freq:220);dl:(len: 8)),
353 (fc:(freq: 60);dl:(len: 8)), (fc:(freq:188);dl:(len: 8)), (fc:(freq:124);dl:(len: 8)),
354 (fc:(freq:252);dl:(len: 8)), (fc:(freq:  2);dl:(len: 8)), (fc:(freq:130);dl:(len: 8)),
355 (fc:(freq: 66);dl:(len: 8)), (fc:(freq:194);dl:(len: 8)), (fc:(freq: 34);dl:(len: 8)),
356 (fc:(freq:162);dl:(len: 8)), (fc:(freq: 98);dl:(len: 8)), (fc:(freq:226);dl:(len: 8)),
357 (fc:(freq: 18);dl:(len: 8)), (fc:(freq:146);dl:(len: 8)), (fc:(freq: 82);dl:(len: 8)),
358 (fc:(freq:210);dl:(len: 8)), (fc:(freq: 50);dl:(len: 8)), (fc:(freq:178);dl:(len: 8)),
359 (fc:(freq:114);dl:(len: 8)), (fc:(freq:242);dl:(len: 8)), (fc:(freq: 10);dl:(len: 8)),
360 (fc:(freq:138);dl:(len: 8)), (fc:(freq: 74);dl:(len: 8)), (fc:(freq:202);dl:(len: 8)),
361 (fc:(freq: 42);dl:(len: 8)), (fc:(freq:170);dl:(len: 8)), (fc:(freq:106);dl:(len: 8)),
362 (fc:(freq:234);dl:(len: 8)), (fc:(freq: 26);dl:(len: 8)), (fc:(freq:154);dl:(len: 8)),
363 (fc:(freq: 90);dl:(len: 8)), (fc:(freq:218);dl:(len: 8)), (fc:(freq: 58);dl:(len: 8)),
364 (fc:(freq:186);dl:(len: 8)), (fc:(freq:122);dl:(len: 8)), (fc:(freq:250);dl:(len: 8)),
365 (fc:(freq:  6);dl:(len: 8)), (fc:(freq:134);dl:(len: 8)), (fc:(freq: 70);dl:(len: 8)),
366 (fc:(freq:198);dl:(len: 8)), (fc:(freq: 38);dl:(len: 8)), (fc:(freq:166);dl:(len: 8)),
367 (fc:(freq:102);dl:(len: 8)), (fc:(freq:230);dl:(len: 8)), (fc:(freq: 22);dl:(len: 8)),
368 (fc:(freq:150);dl:(len: 8)), (fc:(freq: 86);dl:(len: 8)), (fc:(freq:214);dl:(len: 8)),
369 (fc:(freq: 54);dl:(len: 8)), (fc:(freq:182);dl:(len: 8)), (fc:(freq:118);dl:(len: 8)),
370 (fc:(freq:246);dl:(len: 8)), (fc:(freq: 14);dl:(len: 8)), (fc:(freq:142);dl:(len: 8)),
371 (fc:(freq: 78);dl:(len: 8)), (fc:(freq:206);dl:(len: 8)), (fc:(freq: 46);dl:(len: 8)),
372 (fc:(freq:174);dl:(len: 8)), (fc:(freq:110);dl:(len: 8)), (fc:(freq:238);dl:(len: 8)),
373 (fc:(freq: 30);dl:(len: 8)), (fc:(freq:158);dl:(len: 8)), (fc:(freq: 94);dl:(len: 8)),
374 (fc:(freq:222);dl:(len: 8)), (fc:(freq: 62);dl:(len: 8)), (fc:(freq:190);dl:(len: 8)),
375 (fc:(freq:126);dl:(len: 8)), (fc:(freq:254);dl:(len: 8)), (fc:(freq:  1);dl:(len: 8)),
376 (fc:(freq:129);dl:(len: 8)), (fc:(freq: 65);dl:(len: 8)), (fc:(freq:193);dl:(len: 8)),
377 (fc:(freq: 33);dl:(len: 8)), (fc:(freq:161);dl:(len: 8)), (fc:(freq: 97);dl:(len: 8)),
378 (fc:(freq:225);dl:(len: 8)), (fc:(freq: 17);dl:(len: 8)), (fc:(freq:145);dl:(len: 8)),
379 (fc:(freq: 81);dl:(len: 8)), (fc:(freq:209);dl:(len: 8)), (fc:(freq: 49);dl:(len: 8)),
380 (fc:(freq:177);dl:(len: 8)), (fc:(freq:113);dl:(len: 8)), (fc:(freq:241);dl:(len: 8)),
381 (fc:(freq:  9);dl:(len: 8)), (fc:(freq:137);dl:(len: 8)), (fc:(freq: 73);dl:(len: 8)),
382 (fc:(freq:201);dl:(len: 8)), (fc:(freq: 41);dl:(len: 8)), (fc:(freq:169);dl:(len: 8)),
383 (fc:(freq:105);dl:(len: 8)), (fc:(freq:233);dl:(len: 8)), (fc:(freq: 25);dl:(len: 8)),
384 (fc:(freq:153);dl:(len: 8)), (fc:(freq: 89);dl:(len: 8)), (fc:(freq:217);dl:(len: 8)),
385 (fc:(freq: 57);dl:(len: 8)), (fc:(freq:185);dl:(len: 8)), (fc:(freq:121);dl:(len: 8)),
386 (fc:(freq:249);dl:(len: 8)), (fc:(freq:  5);dl:(len: 8)), (fc:(freq:133);dl:(len: 8)),
387 (fc:(freq: 69);dl:(len: 8)), (fc:(freq:197);dl:(len: 8)), (fc:(freq: 37);dl:(len: 8)),
388 (fc:(freq:165);dl:(len: 8)), (fc:(freq:101);dl:(len: 8)), (fc:(freq:229);dl:(len: 8)),
389 (fc:(freq: 21);dl:(len: 8)), (fc:(freq:149);dl:(len: 8)), (fc:(freq: 85);dl:(len: 8)),
390 (fc:(freq:213);dl:(len: 8)), (fc:(freq: 53);dl:(len: 8)), (fc:(freq:181);dl:(len: 8)),
391 (fc:(freq:117);dl:(len: 8)), (fc:(freq:245);dl:(len: 8)), (fc:(freq: 13);dl:(len: 8)),
392 (fc:(freq:141);dl:(len: 8)), (fc:(freq: 77);dl:(len: 8)), (fc:(freq:205);dl:(len: 8)),
393 (fc:(freq: 45);dl:(len: 8)), (fc:(freq:173);dl:(len: 8)), (fc:(freq:109);dl:(len: 8)),
394 (fc:(freq:237);dl:(len: 8)), (fc:(freq: 29);dl:(len: 8)), (fc:(freq:157);dl:(len: 8)),
395 (fc:(freq: 93);dl:(len: 8)), (fc:(freq:221);dl:(len: 8)), (fc:(freq: 61);dl:(len: 8)),
396 (fc:(freq:189);dl:(len: 8)), (fc:(freq:125);dl:(len: 8)), (fc:(freq:253);dl:(len: 8)),
397 (fc:(freq: 19);dl:(len: 9)), (fc:(freq:275);dl:(len: 9)), (fc:(freq:147);dl:(len: 9)),
398 (fc:(freq:403);dl:(len: 9)), (fc:(freq: 83);dl:(len: 9)), (fc:(freq:339);dl:(len: 9)),
399 (fc:(freq:211);dl:(len: 9)), (fc:(freq:467);dl:(len: 9)), (fc:(freq: 51);dl:(len: 9)),
400 (fc:(freq:307);dl:(len: 9)), (fc:(freq:179);dl:(len: 9)), (fc:(freq:435);dl:(len: 9)),
401 (fc:(freq:115);dl:(len: 9)), (fc:(freq:371);dl:(len: 9)), (fc:(freq:243);dl:(len: 9)),
402 (fc:(freq:499);dl:(len: 9)), (fc:(freq: 11);dl:(len: 9)), (fc:(freq:267);dl:(len: 9)),
403 (fc:(freq:139);dl:(len: 9)), (fc:(freq:395);dl:(len: 9)), (fc:(freq: 75);dl:(len: 9)),
404 (fc:(freq:331);dl:(len: 9)), (fc:(freq:203);dl:(len: 9)), (fc:(freq:459);dl:(len: 9)),
405 (fc:(freq: 43);dl:(len: 9)), (fc:(freq:299);dl:(len: 9)), (fc:(freq:171);dl:(len: 9)),
406 (fc:(freq:427);dl:(len: 9)), (fc:(freq:107);dl:(len: 9)), (fc:(freq:363);dl:(len: 9)),
407 (fc:(freq:235);dl:(len: 9)), (fc:(freq:491);dl:(len: 9)), (fc:(freq: 27);dl:(len: 9)),
408 (fc:(freq:283);dl:(len: 9)), (fc:(freq:155);dl:(len: 9)), (fc:(freq:411);dl:(len: 9)),
409 (fc:(freq: 91);dl:(len: 9)), (fc:(freq:347);dl:(len: 9)), (fc:(freq:219);dl:(len: 9)),
410 (fc:(freq:475);dl:(len: 9)), (fc:(freq: 59);dl:(len: 9)), (fc:(freq:315);dl:(len: 9)),
411 (fc:(freq:187);dl:(len: 9)), (fc:(freq:443);dl:(len: 9)), (fc:(freq:123);dl:(len: 9)),
412 (fc:(freq:379);dl:(len: 9)), (fc:(freq:251);dl:(len: 9)), (fc:(freq:507);dl:(len: 9)),
413 (fc:(freq:  7);dl:(len: 9)), (fc:(freq:263);dl:(len: 9)), (fc:(freq:135);dl:(len: 9)),
414 (fc:(freq:391);dl:(len: 9)), (fc:(freq: 71);dl:(len: 9)), (fc:(freq:327);dl:(len: 9)),
415 (fc:(freq:199);dl:(len: 9)), (fc:(freq:455);dl:(len: 9)), (fc:(freq: 39);dl:(len: 9)),
416 (fc:(freq:295);dl:(len: 9)), (fc:(freq:167);dl:(len: 9)), (fc:(freq:423);dl:(len: 9)),
417 (fc:(freq:103);dl:(len: 9)), (fc:(freq:359);dl:(len: 9)), (fc:(freq:231);dl:(len: 9)),
418 (fc:(freq:487);dl:(len: 9)), (fc:(freq: 23);dl:(len: 9)), (fc:(freq:279);dl:(len: 9)),
419 (fc:(freq:151);dl:(len: 9)), (fc:(freq:407);dl:(len: 9)), (fc:(freq: 87);dl:(len: 9)),
420 (fc:(freq:343);dl:(len: 9)), (fc:(freq:215);dl:(len: 9)), (fc:(freq:471);dl:(len: 9)),
421 (fc:(freq: 55);dl:(len: 9)), (fc:(freq:311);dl:(len: 9)), (fc:(freq:183);dl:(len: 9)),
422 (fc:(freq:439);dl:(len: 9)), (fc:(freq:119);dl:(len: 9)), (fc:(freq:375);dl:(len: 9)),
423 (fc:(freq:247);dl:(len: 9)), (fc:(freq:503);dl:(len: 9)), (fc:(freq: 15);dl:(len: 9)),
424 (fc:(freq:271);dl:(len: 9)), (fc:(freq:143);dl:(len: 9)), (fc:(freq:399);dl:(len: 9)),
425 (fc:(freq: 79);dl:(len: 9)), (fc:(freq:335);dl:(len: 9)), (fc:(freq:207);dl:(len: 9)),
426 (fc:(freq:463);dl:(len: 9)), (fc:(freq: 47);dl:(len: 9)), (fc:(freq:303);dl:(len: 9)),
427 (fc:(freq:175);dl:(len: 9)), (fc:(freq:431);dl:(len: 9)), (fc:(freq:111);dl:(len: 9)),
428 (fc:(freq:367);dl:(len: 9)), (fc:(freq:239);dl:(len: 9)), (fc:(freq:495);dl:(len: 9)),
429 (fc:(freq: 31);dl:(len: 9)), (fc:(freq:287);dl:(len: 9)), (fc:(freq:159);dl:(len: 9)),
430 (fc:(freq:415);dl:(len: 9)), (fc:(freq: 95);dl:(len: 9)), (fc:(freq:351);dl:(len: 9)),
431 (fc:(freq:223);dl:(len: 9)), (fc:(freq:479);dl:(len: 9)), (fc:(freq: 63);dl:(len: 9)),
432 (fc:(freq:319);dl:(len: 9)), (fc:(freq:191);dl:(len: 9)), (fc:(freq:447);dl:(len: 9)),
433 (fc:(freq:127);dl:(len: 9)), (fc:(freq:383);dl:(len: 9)), (fc:(freq:255);dl:(len: 9)),
434 (fc:(freq:511);dl:(len: 9)), (fc:(freq:  0);dl:(len: 7)), (fc:(freq: 64);dl:(len: 7)),
435 (fc:(freq: 32);dl:(len: 7)), (fc:(freq: 96);dl:(len: 7)), (fc:(freq: 16);dl:(len: 7)),
436 (fc:(freq: 80);dl:(len: 7)), (fc:(freq: 48);dl:(len: 7)), (fc:(freq:112);dl:(len: 7)),
437 (fc:(freq:  8);dl:(len: 7)), (fc:(freq: 72);dl:(len: 7)), (fc:(freq: 40);dl:(len: 7)),
438 (fc:(freq:104);dl:(len: 7)), (fc:(freq: 24);dl:(len: 7)), (fc:(freq: 88);dl:(len: 7)),
439 (fc:(freq: 56);dl:(len: 7)), (fc:(freq:120);dl:(len: 7)), (fc:(freq:  4);dl:(len: 7)),
440 (fc:(freq: 68);dl:(len: 7)), (fc:(freq: 36);dl:(len: 7)), (fc:(freq:100);dl:(len: 7)),
441 (fc:(freq: 20);dl:(len: 7)), (fc:(freq: 84);dl:(len: 7)), (fc:(freq: 52);dl:(len: 7)),
442 (fc:(freq:116);dl:(len: 7)), (fc:(freq:  3);dl:(len: 8)), (fc:(freq:131);dl:(len: 8)),
443 (fc:(freq: 67);dl:(len: 8)), (fc:(freq:195);dl:(len: 8)), (fc:(freq: 35);dl:(len: 8)),
444 (fc:(freq:163);dl:(len: 8)), (fc:(freq: 99);dl:(len: 8)), (fc:(freq:227);dl:(len: 8))
445 );
446 
447 
448 { The static distance tree. (Actually a trivial tree since all lens use
449   5 bits.) }
450   static_dtree : array[0..D_CODES-1] of ct_data = (
451 (fc:(freq: 0); dl:(len:5)), (fc:(freq:16); dl:(len:5)), (fc:(freq: 8); dl:(len:5)),
452 (fc:(freq:24); dl:(len:5)), (fc:(freq: 4); dl:(len:5)), (fc:(freq:20); dl:(len:5)),
453 (fc:(freq:12); dl:(len:5)), (fc:(freq:28); dl:(len:5)), (fc:(freq: 2); dl:(len:5)),
454 (fc:(freq:18); dl:(len:5)), (fc:(freq:10); dl:(len:5)), (fc:(freq:26); dl:(len:5)),
455 (fc:(freq: 6); dl:(len:5)), (fc:(freq:22); dl:(len:5)), (fc:(freq:14); dl:(len:5)),
456 (fc:(freq:30); dl:(len:5)), (fc:(freq: 1); dl:(len:5)), (fc:(freq:17); dl:(len:5)),
457 (fc:(freq: 9); dl:(len:5)), (fc:(freq:25); dl:(len:5)), (fc:(freq: 5); dl:(len:5)),
458 (fc:(freq:21); dl:(len:5)), (fc:(freq:13); dl:(len:5)), (fc:(freq:29); dl:(len:5)),
459 (fc:(freq: 3); dl:(len:5)), (fc:(freq:19); dl:(len:5)), (fc:(freq:11); dl:(len:5)),
460 (fc:(freq:27); dl:(len:5)), (fc:(freq: 7); dl:(len:5)), (fc:(freq:23); dl:(len:5))
461 );
462 
463 { Distance codes. The first 256 values correspond to the distances
464   3 .. 258, the last 256 values correspond to the top 8 bits of
465   the 15 bit distances. }
466   _dist_code : array[0..DIST_CODE_LEN-1] of byte = (
467  0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
468  8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
469 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
470 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
471 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
472 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
473 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
474 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
475 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
476 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
477 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
478 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
479 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
480 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
481 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
482 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
483 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
484 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
485 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
486 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
487 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
488 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
489 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
490 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
491 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
492 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
493 );
494 
495 { length code for each normalized match length (0 == MIN_MATCH) }
496   _length_code : array[0..MAX_MATCH-MIN_MATCH+1-1] of byte = (
497  0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
498 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
499 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
500 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
501 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
502 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
503 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
504 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
505 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
506 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
507 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
508 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
509 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
510 );
511 
512 
513 { First normalized length for each code (0 = MIN_MATCH) }
514   base_length : array[0..LENGTH_CODES-1] of integer = (
515 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
516 64, 80, 96, 112, 128, 160, 192, 224, 0
517 );
518 
519 
520 { First normalized distance for each code (0 = distance of 1) }
521   base_dist : array[0..D_CODES-1] of integer = (
522     0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
523    32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
524  1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
525 );
526 {$endif}
527 
528 { Output a byte on the stream.
529   IN assertion: there is enough room in pending_buf.
530 macro put_byte(s, c)
531 begin
532   s^.pending_buf^[s^.pending] := (c);
533   inc(s^.pending);
534 end
535 }
536 
537 const
538   MIN_LOOKAHEAD = (MAX_MATCH+MIN_MATCH+1);
539 { Minimum amount of lookahead, except at the end of the input file.
540   See deflate.c for comments about the MIN_MATCH+1. }
541 
542 {macro d_code(dist)
543    if (dist) < 256 then
544      := _dist_code[dist]
545    else
546      := _dist_code[256+((dist) shr 7)]);
547   Mapping from a distance to a distance code. dist is the distance - 1 and
548   must not have side effects. _dist_code[256] and _dist_code[257] are never
549   used. }
550 
551 {$ifndef ORG_DEBUG}
552 { Inline versions of _tr_tally for speed: }
553 
554 #if defined(GEN_TREES_H) || !defined(STDC)
555   extern byte _length_code[];
556   extern byte _dist_code[];
557 #else
558   extern const byte _length_code[];
559   extern const byte _dist_code[];
560 #endif
561 
562 macro _tr_tally_lit(s, c, flush)
563 var
564   cc : byte;
565 begin
566     cc := (c);
567     s^.d_buf[s^.last_lit] := 0;
568     s^.l_buf[s^.last_lit] := cc;
569     inc(s^.last_lit);
570     inc(s^.dyn_ltree[cc].fc.Freq);
571     flush := (s^.last_lit = s^.lit_bufsize-1);
572 end;
573 
574 macro _tr_tally_dist(s, distance, length, flush) \
575 var
576   len : byte;
577   dist : word;
578 begin
579     len := (length);
580     dist := (distance);
581     s^.d_buf[s^.last_lit] := dist;
582     s^.l_buf[s^.last_lit] = len;
583     inc(s^.last_lit);
584     dec(dist);
585     inc(s^.dyn_ltree[_length_code[len]+LITERALS+1].fc.Freq);
586     inc(s^.dyn_dtree[d_code(dist)].Freq);
587     flush := (s^.last_lit = s^.lit_bufsize-1);
588 end;
589 
590 {$endif}
591 
592 { ===========================================================================
593   Constants }
594 
595 const
596   MAX_BL_BITS = 7;
597 { Bit length codes must not exceed MAX_BL_BITS bits }
598 
599 const
600   END_BLOCK = 256;
601 { end of block literal code }
602 
603 const
604   REP_3_6 = 16;
605 { repeat previous bit length 3-6 times (2 bits of repeat count) }
606 
607 const
608   REPZ_3_10 = 17;
609 { repeat a zero length 3-10 times  (3 bits of repeat count) }
610 
611 const
612   REPZ_11_138 = 18;
613 { repeat a zero length 11-138 times  (7 bits of repeat count) }
614 
615 {local}
616 const
617   extra_lbits : array[0..LENGTH_CODES-1] of integer
618     { extra bits for each length code }
619    = (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);
620 
621 {local}
622 const
623   extra_dbits : array[0..D_CODES-1] of integer
624     { extra bits for each distance code }
625    = (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);
626 
627 {local}
628 const
629   extra_blbits : array[0..BL_CODES-1] of integer { extra bits for each bit length code }
630    = (0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7);
631 
632 {local}
633 const
634   bl_order : array[0..BL_CODES-1] of byte
635    = (16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);
636 { The lengths of the bit length codes are sent in order of decreasing
637   probability, to avoid transmitting the lengths for unused bit length codes.
638  }
639 
640 const
641   Buf_size = (8 * 2*sizeof(char));
642 { Number of bits used within bi_buf. (bi_buf might be implemented on
643   more than 16 bits on some systems.) }
644 
645 { ===========================================================================
646   Local data. These are initialized only once. }
647 
648 
649 {$ifdef GEN_TREES_H)}
650 { non ANSI compilers may not accept trees.h }
651 
652 const
653   DIST_CODE_LEN = 512; { see definition of array dist_code below }
654 
655 {local}
656 var
657   static_ltree : array[0..L_CODES+2-1] of ct_data;
658 { The static literal tree. Since the bit lengths are imposed, there is no
659   need for the L_CODES extra codes used during heap construction. However
660   The codes 286 and 287 are needed to build a canonical tree (see _tr_init
661   below). }
662 
663 {local}
664   static_dtree : array[0..D_CODES-1] of ct_data;
665 { The static distance tree. (Actually a trivial tree since all codes use
666   5 bits.) }
667 
668   _dist_code : array[0..DIST_CODE_LEN-1] of byte;
669 { Distance codes. The first 256 values correspond to the distances
670   3 .. 258, the last 256 values correspond to the top 8 bits of
671   the 15 bit distances. }
672 
673   _length_code : array[0..MAX_MATCH-MIN_MATCH+1-1] of byte;
674 { length code for each normalized match length (0 == MIN_MATCH) }
675 
676 {local}
677   base_length : array[0..LENGTH_CODES-1] of integer;
678 { First normalized length for each code (0 = MIN_MATCH) }
679 
680 {local}
681   base_dist : array[0..D_CODES-1] of integer;
682 { First normalized distance for each code (0 = distance of 1) }
683 
684 {$endif} { GEN_TREES_H }
685 
686 {local}
687 const
688   static_l_desc :  static_tree_desc  =
689       (static_tree: {tree_ptr}@static_ltree[0];  { pointer to array of ct_data }
690        extra_bits: {pzIntfArray}@extra_lbits[0]; { pointer to array of integer }
691        extra_base: LITERALS+1;
692        elems: L_CODES;
693        max_length: MAX_BITS);
694 
695 {local}
696 const
697   static_d_desc : static_tree_desc  =
698       (static_tree: {tree_ptr}@static_dtree[0];
699        extra_bits: {pzIntfArray}@extra_dbits[0];
700        extra_base : 0;
701        elems: D_CODES;
702        max_length: MAX_BITS);
703 
704 {local}
705 const
706   static_bl_desc : static_tree_desc =
707       (static_tree: {tree_ptr}(NIL);
708        extra_bits: {pzIntfArray}@extra_blbits[0];
709        extra_base : 0;
710        elems: BL_CODES;
711        max_length: MAX_BL_BITS);
712 
713 {$ifdef GEN_TREES_H}
714 {local}
715 procedure gen_trees_header;
716 {$endif}
717 
718 (*
719 { ===========================================================================
720   Output a short LSB first on the stream.
721   IN assertion: there is enough room in pendingBuf. }
722 
723 macro put_short(s, w)
724 begin
725     {put_byte(s, (byte)((w) & 0xff));}
726     s.pending_buf^[s.pending] := byte((w) and $ff);
727     inc(s.pending);
728 
729     {put_byte(s, (byte)((word)(w) >> 8));}
730     s.pending_buf^[s.pending] := byte(word(w) shr 8);;
731     inc(s.pending);
732 end
733 *)
734 
735 { ===========================================================================
736   Send a value on a given number of bits.
737   IN assertion: length <= 16 and value fits in length bits. }
738 
739 {$ifdef ORG_DEBUG}
740 
741 {local}
742 procedure send_bits(var s : deflate_state;
743                     value : integer;   { value to send }
744                     length : integer); { number of bits }
745 begin
746   {$ifdef ZLIB_DEBUG}
747   Tracevv(' l '+IntToStr(length)+ ' v '+IntToStr(value));
748   Assert((length > 0) and (length <= 15), 'invalid length');
749   inc(s.bits_sent, longint(length));
750   {$ENDIF}
751 
752   { If not enough room in bi_buf, use (valid) bits from bi_buf and
753     (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
754     unused bits in value. }
755   {$PUSH}
756   {$Q-}
757   {$R-}
758   if (s.bi_valid > integer(Buf_size) - length) then
759   begin
760     s.bi_buf := s.bi_buf or integer(value shl s.bi_valid);
761     {put_short(s, s.bi_buf);}
762     s.pending_buf^[s.pending] := byte(s.bi_buf and $ff);
763     inc(s.pending);
764     s.pending_buf^[s.pending] := byte(word(s.bi_buf) shr 8);;
765     inc(s.pending);
766 
767     s.bi_buf := word(value) shr (Buf_size - s.bi_valid);
768     inc(s.bi_valid, length - Buf_size);
769   end
770   else
771   begin
772     s.bi_buf := s.bi_buf or integer(value shl s.bi_valid);
773     inc(s.bi_valid, length);
774   end;
775   {$POP}
776 end;
777 
778 {$else} { !ZLIB_DEBUG }
779 
780 
781 macro send_code(s, c, tree)
782 begin
783   send_bits(s, tree[c].Code, tree[c].Len);
784   { Send a code of the given tree. c and tree must not have side effects }
785 end
786 
787 macro send_bits(s, value, length) \
788 begin integer len := length;\
789   if (s^.bi_valid > (integer)Buf_size - len) begin\
790     integer val := value;\
791     s^.bi_buf |= (val << s^.bi_valid);\
792     {put_short(s, s.bi_buf);}
793     s.pending_buf^[s.pending] := byte(s.bi_buf and $ff);
794     inc(s.pending);
795     s.pending_buf^[s.pending] := byte(word(s.bi_buf) shr 8);;
796     inc(s.pending);
797 
798     s^.bi_buf := (word)val >> (Buf_size - s^.bi_valid);\
799     s^.bi_valid += len - Buf_size;\
800   end else begin\
801     s^.bi_buf |= (value) << s^.bi_valid;\
802     s^.bi_valid += len;\
803   end\
804 end;
805 {$endif} { ZLIB_DEBUG }
806 
807 { ===========================================================================
808   Reverse the first len bits of a code, using straightforward code (a faster
809   method would use a table)
810   IN assertion: 1 <= len <= 15 }
811 
812 {local}
bi_reversenull813 function bi_reverse(code : cardinal;         { the value to invert }
814                     len : integer) : cardinal;   { its bit length }
815 
816 var
817   res : cardinal; {register}
818 begin
819   res := 0;
820   repeat
821     res := res or (code and 1);
822     code := code shr 1;
823     res := res shl 1;
824     dec(len);
825   until (len <= 0);
826   bi_reverse := res shr 1;
827 end;
828 
829 { ===========================================================================
830   Generate the codes for a given tree and bit counts (which need not be
831   optimal).
832   IN assertion: the array bl_count contains the bit length statistics for
833   the given tree and the field len is set for all tree elements.
834   OUT assertion: the field code is set for all tree elements of non
835       zero code length. }
836 
837 {local}
838 procedure gen_codes(tree : tree_ptr;  { the tree to decorate }
839                     max_code : integer;   { largest code with non zero frequency }
840                     var bl_count : array of word);  { number of codes at each bit length }
841 
842 var
843   next_code : array[0..MAX_BITS+1-1] of word; { next code value for each bit length }
844   code : word;              { running code value }
845   bits : integer;                  { bit index }
846   n : integer;                     { code index }
847 var
848   len : integer;
849 begin
850   code := 0;
851 
852   { The distribution counts are first used to generate the code values
853     without bit reversal. }
854 
855   for bits := 1 to MAX_BITS do
856   begin
857     code := ((code + bl_count[bits-1]) shl 1);
858     next_code[bits] := code;
859   end;
860   { Check that the bit counts in bl_count are consistent. The last code
861     must be all ones. }
862 
863   {$IFDEF ZLIB_DEBUG}
864   Assert (code + bl_count[MAX_BITS]-1 = (1 shl MAX_BITS)-1,
865           'inconsistent bit counts');
866   Tracev(#13'gen_codes: max_code '+IntToStr(max_code));
867   {$ENDIF}
868 
869   for n := 0 to max_code do
870   begin
871     len := tree[n].dl.Len;
872     if (len = 0) then
873       continue;
874     { Now reverse the bits }
875     tree[n].fc.Code := bi_reverse(next_code[len], len);
876     inc(next_code[len]);
877     {$ifdef ZLIB_DEBUG}
878     if (n>31) and (n<128) then
879       Tracecv(tree <> tree_ptr(@static_ltree),
880        (^M'n #'+IntToStr(n)+' '+char(n)+' l '+IntToStr(len)+' c '+
881          IntToStr(tree[n].fc.Code)+' ('+IntToStr(next_code[len]-1)+')'))
882     else
883       Tracecv(tree <> tree_ptr(@static_ltree),
884       (^M'n #'+IntToStr(n)+'   l '+IntToStr(len)+' c '+
885          IntToStr(tree[n].fc.Code)+' ('+IntToStr(next_code[len]-1)+')'));
886     {$ENDIF}
887   end;
888 end;
889 
890 { ===========================================================================
891   Genererate the file trees.h describing the static trees. }
892 {$ifdef GEN_TREES_H}
893 
894 macro SEPARATOR(i, last, width)
895   if (i) = (last) then
896     ( ^M');'^M^M
897   else    \
898     if (i) mod (width) = (width)-1 then
899        ','^M
900      else
901        ', '
902 
903 procedure gen_trees_header;
904 var
905   header : system.text;
906   i : integer;
907 begin
908   system.assign(header, 'trees.inc');
909   {$push}{$I-}
910   ReWrite(header);
911   {$pop}
912   Assert (IOresult <> 0, 'Can''t open trees.h');
913   WriteLn(header,
914     '{ header created automatically with -DGEN_TREES_H }'^M);
915 
916   WriteLn(header, 'local const ct_data static_ltree[L_CODES+2] := (');
917   for i := 0 to L_CODES+2-1 do
918   begin
919     WriteLn(header, '((%3u),(%3u))%s', static_ltree[i].Code,
920 		static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
921   end;
922 
923   WriteLn(header, 'local const ct_data static_dtree[D_CODES] := (');
924   for i := 0 to D_CODES-1 do
925   begin
926     WriteLn(header, '((%2u),(%2u))%s', static_dtree[i].Code,
927 		static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
928   end;
929 
930   WriteLn(header, 'const byte _dist_code[DIST_CODE_LEN] := (');
931   for i := 0 to DIST_CODE_LEN-1 do
932   begin
933     WriteLn(header, '%2u%s', _dist_code[i],
934 		SEPARATOR(i, DIST_CODE_LEN-1, 20));
935   end;
936 
937   WriteLn(header, 'const byte _length_code[MAX_MATCH-MIN_MATCH+1]= (');
938   for i := 0 to MAX_MATCH-MIN_MATCH+1-1 do
939   begin
940     WriteLn(header, '%2u%s', _length_code[i],
941 		SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
942   end;
943 
944   WriteLn(header, 'local const integer base_length[LENGTH_CODES] := (');
945   for i := 0 to LENGTH_CODES-1 do
946   begin
947     WriteLn(header, '%1u%s', base_length[i],
948 		SEPARATOR(i, LENGTH_CODES-1, 20));
949   end;
950 
951   WriteLn(header, 'local const integer base_dist[D_CODES] := (');
952   for i := 0 to D_CODES-1 do
953   begin
954     WriteLn(header, '%5u%s', base_dist[i],
955 		SEPARATOR(i, D_CODES-1, 10));
956   end;
957 
958   close(header);
959 end;
960 {$endif} { GEN_TREES_H }
961 
962 
963 { ===========================================================================
964   Initialize the various 'constant' tables. }
965 
966 {local}
967 procedure tr_static_init;
968 
969 {$ifdef GEN_TREES_H}
970 const
971   static_init_done : boolean = FALSE;
972 var
973   n : integer;        { iterates over tree elements }
974   bits : integer;     { bit counter }
975   length : integer;   { length value }
976   code : integer;     { code value }
977   dist : integer;     { distance index }
978   bl_count : array[0..MAX_BITS+1-1] of word;
979     { number of codes at each bit length for an optimal tree }
980 begin
981     if (static_init_done) then
982       exit;
983 
984     { Initialize the mapping length (0..255) -> length code (0..28) }
985     length := 0;
986     for code := 0 to LENGTH_CODES-1-1 do
987     begin
988       base_length[code] := length;
989       for n := 0 to (1 shl extra_lbits[code])-1 do
990       begin
991         _length_code[length] := byte(code);
992         inc(length);
993       end;
994     end;
995     Assert (length = 256, 'tr_static_init: length <> 256');
996     { Note that the length 255 (match length 258) can be represented
997       in two different ways: code 284 + 5 bits or code 285, so we
998       overwrite length_code[255] to use the best encoding: }
999 
1000     _length_code[length-1] := byte(code);
1001 
1002     { Initialize the mapping dist (0..32K) -> dist code (0..29) }
1003     dist := 0;
1004     for code := 0 to 16-1 do
1005     begin
1006       base_dist[code] := dist;
1007       for n := 0 to (1 shl extra_dbits[code])-1 do
1008       begin
1009         _dist_code[dist] := byte(code);
1010         inc(dist);
1011       end;
1012     end;
1013     Assert (dist = 256, 'tr_static_init: dist <> 256');
1014     dist := dist shr 7; { from now on, all distances are divided by 128 }
1015     for code := 16 to D_CODES-1 do
1016     begin
1017       base_dist[code] := dist shl 7;
1018       for n := 0 to (1 shl (extra_dbits[code]-7))-1 do
1019       begin
1020         _dist_code[256 + dist] := byte(code);
1021         inc(dist);
1022       end;
1023     end;
1024     Assert (dist = 256, 'tr_static_init: 256+dist <> 512');
1025 
1026     { Construct the codes of the static literal tree }
1027     for bits := 0 to MAX_BITS do
1028       bl_count[bits] := 0;
1029     n := 0;
1030     while (n <= 143) do
1031     begin
1032       static_ltree[n].dl.Len := 8;
1033       inc(n);
1034       inc(bl_count[8]);
1035     end;
1036     while (n <= 255) do
1037     begin
1038       static_ltree[n].dl.Len := 9;
1039       inc(n);
1040       inc(bl_count[9]);
1041     end;
1042     while (n <= 279) do
1043     begin
1044       static_ltree[n].dl.Len := 7;
1045       inc(n);
1046       inc(bl_count[7]);
1047     end;
1048     while (n <= 287) do
1049     begin
1050       static_ltree[n].dl.Len := 8;
1051       inc(n);
1052       inc(bl_count[8]);
1053     end;
1054 
1055     { Codes 286 and 287 do not exist, but we must include them in the
1056       tree construction to get a canonical Huffman tree (longest code
1057       all ones)  }
1058 
1059     gen_codes(tree_ptr(@static_ltree), L_CODES+1, bl_count);
1060 
1061     { The static distance tree is trivial: }
1062     for n := 0 to D_CODES-1 do
1063     begin
1064       static_dtree[n].dl.Len := 5;
1065       static_dtree[n].fc.Code := bi_reverse(cardinal(n), 5);
1066     end;
1067     static_init_done := TRUE;
1068 
1069     gen_trees_header;  { save to include file }
1070 {$else}
1071 begin
1072 {$endif} { GEN_TREES_H) }
1073 end;
1074 
1075 { ===========================================================================
1076   Initialize a new block. }
1077 {local}
1078 
1079 procedure init_block(var s : deflate_state);
1080 var
1081   n : integer; { iterates over tree elements }
1082 begin
1083   { Initialize the trees. }
1084   for n := 0 to L_CODES-1 do
1085     s.dyn_ltree[n].fc.Freq := 0;
1086   for n := 0 to D_CODES-1 do
1087     s.dyn_dtree[n].fc.Freq := 0;
1088   for n := 0 to BL_CODES-1 do
1089     s.bl_tree[n].fc.Freq := 0;
1090 
1091   s.dyn_ltree[END_BLOCK].fc.Freq := 1;
1092   s.static_len := 0;
1093   s.opt_len := 0;
1094   s.matches := 0;
1095   s.last_lit := 0;
1096 end;
1097 
1098 const
1099   SMALLEST = 1;
1100 { Index within the heap array of least frequent node in the Huffman tree }
1101 
1102 { ===========================================================================
1103   Initialize the tree data structures for a new zlib stream. }
1104 procedure _tr_init(var s : deflate_state);
1105 begin
1106   tr_static_init;
1107 
1108   s.compressed_len := 0;
1109 
1110   s.l_desc.dyn_tree := tree_ptr(@s.dyn_ltree);
1111   s.l_desc.stat_desc := @static_l_desc;
1112 
1113   s.d_desc.dyn_tree := tree_ptr(@s.dyn_dtree);
1114   s.d_desc.stat_desc := @static_d_desc;
1115 
1116   s.bl_desc.dyn_tree := tree_ptr(@s.bl_tree);
1117   s.bl_desc.stat_desc := @static_bl_desc;
1118 
1119   s.bi_buf := 0;
1120   s.bi_valid := 0;
1121   s.last_eob_len := 8; { enough lookahead for inflate }
1122 {$ifdef ZLIB_DEBUG}
1123   s.bits_sent := 0;
1124 {$endif}
1125 
1126   { Initialize the first block of the first file: }
1127   init_block(s);
1128 end;
1129 
1130 { ===========================================================================
1131   Remove the smallest element from the heap and recreate the heap with
1132   one less element. Updates heap and heap_len.
1133 
1134 macro pqremove(s, tree, top)
1135 begin
1136     top := s.heap[SMALLEST];
1137     s.heap[SMALLEST] := s.heap[s.heap_len];
1138     dec(s.heap_len);
1139     pqdownheap(s, tree, SMALLEST);
1140 end
1141 }
1142 
1143 { ===========================================================================
1144   Compares to subtrees, using the tree depth as tie breaker when
1145   the subtrees have equal frequency. This minimizes the worst case length.
1146 
1147 macro smaller(tree, n, m, depth)
1148    ( (tree[n].Freq < tree[m].Freq) or
1149      ((tree[n].Freq = tree[m].Freq) and (depth[n] <= depth[m])) )
1150 }
1151 
1152 { ===========================================================================
1153   Restore the heap property by moving down the tree starting at node k,
1154   exchanging a node with the smallest of its two sons if necessary, stopping
1155   when the heap property is re-established (each father smaller than its
1156   two sons). }
1157 {local}
1158 
1159 procedure pqdownheap(var s : deflate_state;
1160                      tree : tree_ptr;   { the tree to restore }
1161                      k : integer);          { node to move down }
1162 var
1163   v : integer;
1164   j : integer;
1165 begin
1166   v := s.heap[k];
1167   j := k shl 1;  { left son of k }
1168   while (j <= s.heap_len) do
1169   begin
1170     { Set j to the smallest of the two sons: }
1171     if (j < s.heap_len) and
1172        {smaller(tree, s.heap[j+1], s.heap[j], s.depth)}
1173       ( (tree[s.heap[j+1]].fc.Freq < tree[s.heap[j]].fc.Freq) or
1174         ((tree[s.heap[j+1]].fc.Freq = tree[s.heap[j]].fc.Freq) and
1175          (s.depth[s.heap[j+1]] <= s.depth[s.heap[j]])) ) then
1176     begin
1177       inc(j);
1178     end;
1179     { Exit if v is smaller than both sons }
1180     if {(smaller(tree, v, s.heap[j], s.depth))}
1181      ( (tree[v].fc.Freq < tree[s.heap[j]].fc.Freq) or
1182        ((tree[v].fc.Freq = tree[s.heap[j]].fc.Freq) and
1183         (s.depth[v] <= s.depth[s.heap[j]])) ) then
1184       break;
1185     { Exchange v with the smallest son }
1186     s.heap[k] := s.heap[j];
1187     k := j;
1188 
1189     { And continue down the tree, setting j to the left son of k }
1190     j := j shl 1;
1191   end;
1192   s.heap[k] := v;
1193 end;
1194 
1195 { ===========================================================================
1196   Compute the optimal bit lengths for a tree and update the total bit length
1197   for the current block.
1198   IN assertion: the fields freq and dad are set, heap[heap_max] and
1199      above are the tree nodes sorted by increasing frequency.
1200   OUT assertions: the field len is set to the optimal bit length, the
1201       array bl_count contains the frequencies for each bit length.
1202       The length opt_len is updated; static_len is also updated if stree is
1203       not null. }
1204 
1205 {local}
1206 procedure gen_bitlen(var s : deflate_state;
1207                      var desc : tree_desc);   { the tree descriptor }
1208 var
1209   tree : tree_ptr;
1210   max_code : integer;
1211   stree : tree_ptr; {const}
1212   extra : pinteger; {const}
1213   base : integer;
1214   max_length : integer;
1215   h : integer;              { heap index }
1216   n, m : integer;           { iterate over the tree elements }
1217   bits : integer;           { bit length }
1218   xbits : integer;          { extra bits }
1219   f : word;              { frequency }
1220   overflow : integer;   { number of elements with bit length too large }
1221 begin
1222   tree := desc.dyn_tree;
1223   max_code := desc.max_code;
1224   stree := desc.stat_desc^.static_tree;
1225   extra := desc.stat_desc^.extra_bits;
1226   base := desc.stat_desc^.extra_base;
1227   max_length := desc.stat_desc^.max_length;
1228   overflow := 0;
1229 
1230   for bits := 0 to MAX_BITS do
1231     s.bl_count[bits] := 0;
1232 
1233   { In a first pass, compute the optimal bit lengths (which may
1234     overflow in the case of the bit length tree). }
1235 
1236   tree[s.heap[s.heap_max]].dl.Len := 0; { root of the heap }
1237 
1238   for h := s.heap_max+1 to HEAP_SIZE-1 do
1239   begin
1240     n := s.heap[h];
1241     bits := tree[tree[n].dl.Dad].dl.Len + 1;
1242     if (bits > max_length) then
1243     begin
1244       bits := max_length;
1245       inc(overflow);
1246     end;
1247     tree[n].dl.Len := word(bits);
1248     { We overwrite tree[n].dl.Dad which is no longer needed }
1249 
1250     if (n > max_code) then
1251       continue; { not a leaf node }
1252 
1253     inc(s.bl_count[bits]);
1254     xbits := 0;
1255     if (n >= base) then
1256       xbits := extra[n-base];
1257     f := tree[n].fc.Freq;
1258     inc(s.opt_len, longint(f) * (bits + xbits));
1259     if (stree <> NIL) then
1260       inc(s.static_len, longint(f) * (stree[n].dl.Len + xbits));
1261   end;
1262   if (overflow = 0) then
1263     exit;
1264   {$ifdef ZLIB_DEBUG}
1265   Tracev(^M'bit length overflow');
1266   {$endif}
1267   { This happens for example on obj2 and pic of the Calgary corpus }
1268 
1269   { Find the first bit length which could increase: }
1270   repeat
1271     bits := max_length-1;
1272     while (s.bl_count[bits] = 0) do
1273       dec(bits);
1274     dec(s.bl_count[bits]);      { move one leaf down the tree }
1275     inc(s.bl_count[bits+1], 2); { move one overflow item as its brother }
1276     dec(s.bl_count[max_length]);
1277     { The brother of the overflow item also moves one step up,
1278       but this does not affect bl_count[max_length] }
1279 
1280     dec(overflow, 2);
1281   until (overflow <= 0);
1282 
1283   { Now recompute all bit lengths, scanning in increasing frequency.
1284     h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
1285     lengths instead of fixing only the wrong ones. This idea is taken
1286     from 'ar' written by Haruhiko Okumura.) }
1287   h := HEAP_SIZE;  { Delphi3: compiler warning w/o this }
1288   for bits := max_length downto 1 do
1289   begin
1290     n := s.bl_count[bits];
1291     while (n <> 0) do
1292     begin
1293       dec(h);
1294       m := s.heap[h];
1295       if (m > max_code) then
1296         continue;
1297       if (tree[m].dl.Len <> cardinal(bits)) then
1298       begin
1299         {$ifdef ZLIB_DEBUG}
1300         Trace('code '+IntToStr(m)+' bits '+IntToStr(tree[m].dl.Len)
1301               +'.'+IntToStr(bits));
1302         {$ENDIF}
1303         inc(s.opt_len, (cardinal(bits) - cardinal(tree[m].dl.Len))
1304                         * cardinal(tree[m].fc.Freq) );
1305         tree[m].dl.Len := word(bits);
1306       end;
1307       dec(n);
1308     end;
1309   end;
1310 end;
1311 
1312 { ===========================================================================
1313   Construct one Huffman tree and assigns the code bit strings and lengths.
1314   Update the total bit length for the current block.
1315   IN assertion: the field freq is set for all tree elements.
1316   OUT assertions: the fields len and code are set to the optimal bit length
1317       and corresponding code. The length opt_len is updated; static_len is
1318       also updated if stree is not null. The field max_code is set. }
1319 
1320 {local}
1321 procedure build_tree(var s : deflate_state;
1322                      var desc : tree_desc); { the tree descriptor }
1323 
1324 var
1325   tree : tree_ptr;
1326   stree : tree_ptr; {const}
1327   elems : integer;
1328   n, m : integer;          { iterate over heap elements }
1329   max_code : integer;      { largest code with non zero frequency }
1330   node : integer;          { new node being created }
1331 begin
1332   tree := desc.dyn_tree;
1333   stree := desc.stat_desc^.static_tree;
1334   elems := desc.stat_desc^.elems;
1335   max_code := -1;
1336 
1337   { Construct the initial heap, with least frequent element in
1338     heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
1339     heap[0] is not used. }
1340   s.heap_len := 0;
1341   s.heap_max := HEAP_SIZE;
1342 
1343   for n := 0 to elems-1 do
1344   begin
1345     if (tree[n].fc.Freq <> 0) then
1346     begin
1347       max_code := n;
1348       inc(s.heap_len);
1349       s.heap[s.heap_len] := n;
1350       s.depth[n] := 0;
1351     end
1352     else
1353     begin
1354       tree[n].dl.Len := 0;
1355     end;
1356   end;
1357 
1358   { The pkzip format requires that at least one distance code exists,
1359     and that at least one bit should be sent even if there is only one
1360     possible code. So to avoid special checks later on we force at least
1361     two codes of non zero frequency. }
1362 
1363   while (s.heap_len < 2) do
1364   begin
1365     inc(s.heap_len);
1366     if (max_code < 2) then
1367     begin
1368       inc(max_code);
1369       s.heap[s.heap_len] := max_code;
1370       node := max_code;
1371     end
1372     else
1373     begin
1374       s.heap[s.heap_len] := 0;
1375       node := 0;
1376     end;
1377     tree[node].fc.Freq := 1;
1378     s.depth[node] := 0;
1379     dec(s.opt_len);
1380     if (stree <> NIL) then
1381       dec(s.static_len, stree[node].dl.Len);
1382     { node is 0 or 1 so it does not have extra bits }
1383   end;
1384   desc.max_code := max_code;
1385 
1386   { The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
1387     establish sub-heaps of increasing lengths: }
1388 
1389   for n := s.heap_len div 2 downto 1 do
1390     pqdownheap(s, tree, n);
1391 
1392   { Construct the Huffman tree by repeatedly combining the least two
1393     frequent nodes. }
1394 
1395   node := elems;              { next internal node of the tree }
1396   repeat
1397     {pqremove(s, tree, n);}  { n := node of least frequency }
1398     n := s.heap[SMALLEST];
1399     s.heap[SMALLEST] := s.heap[s.heap_len];
1400     dec(s.heap_len);
1401     pqdownheap(s, tree, SMALLEST);
1402 
1403     m := s.heap[SMALLEST]; { m := node of next least frequency }
1404 
1405     dec(s.heap_max);
1406     s.heap[s.heap_max] := n; { keep the nodes sorted by frequency }
1407     dec(s.heap_max);
1408     s.heap[s.heap_max] := m;
1409 
1410     { Create a new node father of n and m }
1411     tree[node].fc.Freq := tree[n].fc.Freq + tree[m].fc.Freq;
1412     { maximum }
1413     if (s.depth[n] >= s.depth[m]) then
1414       s.depth[node] := byte (s.depth[n] + 1)
1415     else
1416       s.depth[node] := byte (s.depth[m] + 1);
1417 
1418     tree[m].dl.Dad := word(node);
1419     tree[n].dl.Dad := word(node);
1420 {$ifdef DUMP_BL_TREE}
1421     if (tree = tree_ptr(@s.bl_tree)) then
1422     begin
1423       WriteLn(#13'node ',node,'(',tree[node].fc.Freq,') sons ',n,
1424               '(',tree[n].fc.Freq,') ', m, '(',tree[m].fc.Freq,')');
1425     end;
1426 {$endif}
1427     { and insert the new node in the heap }
1428     s.heap[SMALLEST] := node;
1429     inc(node);
1430     pqdownheap(s, tree, SMALLEST);
1431 
1432   until (s.heap_len < 2);
1433 
1434   dec(s.heap_max);
1435   s.heap[s.heap_max] := s.heap[SMALLEST];
1436 
1437   { At this point, the fields freq and dad are set. We can now
1438     generate the bit lengths. }
1439 
1440   gen_bitlen(s, desc);
1441 
1442   { The field len is now set, we can generate the bit codes }
1443   gen_codes (tree, max_code, s.bl_count);
1444 end;
1445 
1446 { ===========================================================================
1447   Scan a literal or distance tree to determine the frequencies of the codes
1448   in the bit length tree. }
1449 
1450 {local}
1451 procedure scan_tree(var s : deflate_state;
1452                     var tree : array of ct_data;    { the tree to be scanned }
1453                     max_code : integer);    { and its largest code of non zero frequency }
1454 var
1455   n : integer;                 { iterates over all tree elements }
1456   prevlen : integer;           { last emitted length }
1457   curlen : integer;            { length of current code }
1458   nextlen : integer;           { length of next code }
1459   count : integer;             { repeat count of the current code }
1460   max_count : integer;         { max repeat count }
1461   min_count : integer;         { min repeat count }
1462 begin
1463   prevlen := -1;
1464   nextlen := tree[0].dl.Len;
1465   count := 0;
1466   max_count := 7;
1467   min_count := 4;
1468 
1469   if (nextlen = 0) then
1470   begin
1471     max_count := 138;
1472     min_count := 3;
1473   end;
1474   tree[max_code+1].dl.Len := word($ffff); { guard }
1475 
1476   for n := 0 to max_code do
1477   begin
1478     curlen := nextlen;
1479 {$push}{$R-}
1480     nextlen := tree[n+1].dl.Len;
1481 {$pop}
1482     inc(count);
1483     if (count < max_count) and (curlen = nextlen) then
1484       continue
1485     else
1486       if (count < min_count) then
1487         inc(s.bl_tree[curlen].fc.Freq, count)
1488       else
1489         if (curlen <> 0) then
1490         begin
1491           if (curlen <> prevlen) then
1492             inc(s.bl_tree[curlen].fc.Freq);
1493           inc(s.bl_tree[REP_3_6].fc.Freq);
1494         end
1495         else
1496           if (count <= 10) then
1497             inc(s.bl_tree[REPZ_3_10].fc.Freq)
1498           else
1499             inc(s.bl_tree[REPZ_11_138].fc.Freq);
1500 
1501     count := 0;
1502     prevlen := curlen;
1503     if (nextlen = 0) then
1504     begin
1505       max_count := 138;
1506       min_count := 3;
1507     end
1508     else
1509       if (curlen = nextlen) then
1510       begin
1511         max_count := 6;
1512         min_count := 3;
1513       end
1514       else
1515       begin
1516         max_count := 7;
1517         min_count := 4;
1518       end;
1519   end;
1520 end;
1521 
1522 { ===========================================================================
1523   Send a literal or distance tree in compressed form, using the codes in
1524   bl_tree. }
1525 
1526 {local}
1527 procedure send_tree(var s : deflate_state;
1528                     var tree : array of ct_data;    { the tree to be scanned }
1529                     max_code : integer);    { and its largest code of non zero frequency }
1530 
1531 var
1532   n : integer;                { iterates over all tree elements }
1533   prevlen : integer;          { last emitted length }
1534   curlen : integer;           { length of current code }
1535   nextlen : integer;          { length of next code }
1536   count : integer;            { repeat count of the current code }
1537   max_count : integer;        { max repeat count }
1538   min_count : integer;        { min repeat count }
1539 begin
1540   prevlen := -1;
1541   nextlen := tree[0].dl.Len;
1542   count := 0;
1543   max_count := 7;
1544   min_count := 4;
1545 
1546   { tree[max_code+1].dl.Len := -1; }  { guard already set }
1547   if (nextlen = 0) then
1548   begin
1549     max_count := 138;
1550     min_count := 3;
1551   end;
1552 
1553   for n := 0 to max_code do
1554   begin
1555     curlen := nextlen;
1556     nextlen := tree[n+1].dl.Len;
1557     inc(count);
1558     if (count < max_count) and (curlen = nextlen) then
1559       continue
1560     else
1561       if (count < min_count) then
1562       begin
1563         repeat
1564           {$ifdef ZLIB_DEBUG}
1565           Tracevvv(#13'cd '+IntToStr(curlen));
1566           {$ENDIF}
1567           send_bits(s, s.bl_tree[curlen].fc.Code, s.bl_tree[curlen].dl.Len);
1568           dec(count);
1569         until (count = 0);
1570       end
1571       else
1572         if (curlen <> 0) then
1573         begin
1574           if (curlen <> prevlen) then
1575           begin
1576             {$ifdef ZLIB_DEBUG}
1577             Tracevvv(#13'cd '+IntToStr(curlen));
1578             {$ENDIF}
1579             send_bits(s, s.bl_tree[curlen].fc.Code, s.bl_tree[curlen].dl.Len);
1580             dec(count);
1581           end;
1582           {$IFDEF ZLIB_DEBUG}
1583           Assert((count >= 3) and (count <= 6), ' 3_6?');
1584           {$ENDIF}
1585           {$ifdef ZLIB_DEBUG}
1586           Tracevvv(#13'cd '+IntToStr(REP_3_6));
1587           {$ENDIF}
1588           send_bits(s, s.bl_tree[REP_3_6].fc.Code, s.bl_tree[REP_3_6].dl.Len);
1589           send_bits(s, count-3, 2);
1590         end
1591         else
1592           if (count <= 10) then
1593           begin
1594             {$ifdef ZLIB_DEBUG}
1595             Tracevvv(#13'cd '+IntToStr(REPZ_3_10));
1596             {$ENDIF}
1597             send_bits(s, s.bl_tree[REPZ_3_10].fc.Code, s.bl_tree[REPZ_3_10].dl.Len);
1598             send_bits(s, count-3, 3);
1599           end
1600           else
1601           begin
1602             {$ifdef ZLIB_DEBUG}
1603             Tracevvv(#13'cd '+IntToStr(REPZ_11_138));
1604             {$ENDIF}
1605             send_bits(s, s.bl_tree[REPZ_11_138].fc.Code, s.bl_tree[REPZ_11_138].dl.Len);
1606             send_bits(s, count-11, 7);
1607           end;
1608     count := 0;
1609     prevlen := curlen;
1610     if (nextlen = 0) then
1611     begin
1612       max_count := 138;
1613       min_count := 3;
1614     end
1615     else
1616       if (curlen = nextlen) then
1617       begin
1618         max_count := 6;
1619         min_count := 3;
1620       end
1621       else
1622       begin
1623         max_count := 7;
1624         min_count := 4;
1625       end;
1626   end;
1627 end;
1628 
1629 { ===========================================================================
1630   Construct the Huffman tree for the bit lengths and return the index in
1631   bl_order of the last bit length code to send. }
1632 
1633 {local}
build_bl_treenull1634 function build_bl_tree(var s : deflate_state) : integer;
1635 var
1636   max_blindex : integer;  { index of last bit length code of non zero freq }
1637 begin
1638   { Determine the bit length frequencies for literal and distance trees }
1639   scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
1640   scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
1641 
1642   { Build the bit length tree: }
1643   build_tree(s, s.bl_desc);
1644   { opt_len now includes the length of the tree representations, except
1645     the lengths of the bit lengths codes and the 5+5+4 bits for the counts. }
1646 
1647   { Determine the number of bit length codes to send. The pkzip format
1648     requires that at least 4 bit length codes be sent. (appnote.txt says
1649     3 but the actual value used is 4.) }
1650 
1651   for max_blindex := BL_CODES-1 downto 3 do
1652   begin
1653     if (s.bl_tree[bl_order[max_blindex]].dl.Len <> 0) then
1654       break;
1655   end;
1656   { Update opt_len to include the bit length tree and counts }
1657   inc(s.opt_len, 3*(max_blindex+1) + 5+5+4);
1658   {$ifdef ZLIB_DEBUG}
1659   Tracev(^M'dyn trees: dyn %ld, stat %ld {s.opt_len, s.static_len}');
1660   {$ENDIF}
1661 
1662   build_bl_tree := max_blindex;
1663 end;
1664 
1665 { ===========================================================================
1666   Send the header for a block using dynamic Huffman trees: the counts, the
1667   lengths of the bit length codes, the literal tree and the distance tree.
1668   IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. }
1669 
1670 {local}
1671 procedure send_all_trees(var s : deflate_state;
1672                          lcodes : integer;
1673                          dcodes : integer;
1674                          blcodes : integer); { number of codes for each tree }
1675 var
1676   rank : integer;                    { index in bl_order }
1677 begin
1678   {$IFDEF ZLIB_DEBUG}
1679   Assert ((lcodes >= 257) and (dcodes >= 1) and (blcodes >= 4),
1680           'not enough codes');
1681   Assert ((lcodes <= L_CODES) and (dcodes <= D_CODES)
1682           and (blcodes <= BL_CODES), 'too many codes');
1683   Tracev(^M'bl counts: ');
1684   {$ENDIF}
1685   send_bits(s, lcodes-257, 5); { not +255 as stated in appnote.txt }
1686   send_bits(s, dcodes-1,   5);
1687   send_bits(s, blcodes-4,  4); { not -3 as stated in appnote.txt }
1688   for rank := 0 to blcodes-1 do
1689   begin
1690     {$ifdef ZLIB_DEBUG}
1691     Tracev(^M'bl code '+IntToStr(bl_order[rank]));
1692     {$ENDIF}
1693     send_bits(s, s.bl_tree[bl_order[rank]].dl.Len, 3);
1694   end;
1695   {$ifdef ZLIB_DEBUG}
1696   Tracev(^M'bl tree: sent '+IntToStr(s.bits_sent));
1697   {$ENDIF}
1698 
1699   send_tree(s, s.dyn_ltree, lcodes-1); { literal tree }
1700   {$ifdef ZLIB_DEBUG}
1701   Tracev(^M'lit tree: sent '+IntToStr(s.bits_sent));
1702   {$ENDIF}
1703 
1704   send_tree(s, s.dyn_dtree, dcodes-1); { distance tree }
1705   {$ifdef ZLIB_DEBUG}
1706   Tracev(^M'dist tree: sent '+IntToStr(s.bits_sent));
1707   {$ENDIF}
1708 end;
1709 
1710 { ===========================================================================
1711   Flush the bit buffer and align the output on a byte boundary }
1712 
1713 {local}
1714 procedure bi_windup(var s : deflate_state);
1715 begin
1716   if (s.bi_valid > 8) then
1717   begin
1718     {put_short(s, s.bi_buf);}
1719     s.pending_buf^[s.pending] := byte(s.bi_buf and $ff);
1720     inc(s.pending);
1721     s.pending_buf^[s.pending] := byte(word(s.bi_buf) shr 8);;
1722     inc(s.pending);
1723   end
1724   else
1725     if (s.bi_valid > 0) then
1726     begin
1727       {put_byte(s, (Byte)s^.bi_buf);}
1728       s.pending_buf^[s.pending] := Byte(s.bi_buf);
1729       inc(s.pending);
1730     end;
1731   s.bi_buf := 0;
1732   s.bi_valid := 0;
1733 {$ifdef ZLIB_DEBUG}
1734   s.bits_sent := (s.bits_sent+7) and (not 7);
1735 {$endif}
1736 end;
1737 
1738 { ===========================================================================
1739   Copy a stored block, storing first the length and its
1740   one's complement if requested. }
1741 
1742 {local}
1743 procedure copy_block(var s : deflate_state;
1744                      buf : Pbyte;       { the input data }
1745                      len : word;        { its length }
1746                      header : boolean); { true if block header must be written }
1747 begin
1748   bi_windup(s);        { align on byte boundary }
1749   s.last_eob_len := 8; { enough lookahead for inflate }
1750 
1751   if (header) then
1752   begin
1753     {put_short(s, (word)len);}
1754     s.pending_buf^[s.pending] := byte(len and $ff);
1755     inc(s.pending);
1756     s.pending_buf^[s.pending] := byte(len shr 8);;
1757     inc(s.pending);
1758     {put_short(s, (word)~len);}
1759     s.pending_buf^[s.pending] := byte((not len) and $ff);
1760     inc(s.pending);
1761     s.pending_buf^[s.pending] := byte((not len) shr 8);;
1762     inc(s.pending);
1763 
1764 {$ifdef ZLIB_DEBUG}
1765     inc(s.bits_sent, 2*16);
1766 {$endif}
1767   end;
1768 {$ifdef ZLIB_DEBUG}
1769   inc(s.bits_sent, len shl 3);
1770 {$endif}
1771   move(buf^,s.pending_buf^[s.pending],len);
1772   inc(s.pending,len);
1773 end;
1774 
1775 
1776 { ===========================================================================
1777   Send a stored block }
1778 
1779 procedure _tr_stored_block(var s : deflate_state;
1780                            buf : Pbyte;     { input block }
1781                            stored_len : longint; { length of input block }
1782                            eof : boolean);   { true if this is the last block for a file }
1783 
1784 begin
1785   send_bits(s, (STORED_BLOCK shl 1)+ord(eof), 3);  { send block type }
1786   s.compressed_len := (s.compressed_len + 3 + 7) and longint(not cardinal(7));
1787   inc(s.compressed_len, (stored_len + 4) shl 3);
1788 
1789   copy_block(s, buf, cardinal(stored_len), TRUE); { with header }
1790 end;
1791 
1792 { ===========================================================================
1793   Flush the bit buffer, keeping at most 7 bits in it. }
1794 
1795 {local}
1796 procedure bi_flush(var s : deflate_state);
1797 begin
1798   if (s.bi_valid = 16) then
1799   begin
1800     {put_short(s, s.bi_buf);}
1801     s.pending_buf^[s.pending] := byte(s.bi_buf and $ff);
1802     inc(s.pending);
1803     s.pending_buf^[s.pending] := byte(word(s.bi_buf) shr 8);;
1804     inc(s.pending);
1805 
1806     s.bi_buf := 0;
1807     s.bi_valid := 0;
1808   end
1809   else
1810    if (s.bi_valid >= 8) then
1811    begin
1812      {put_byte(s, (Byte)s^.bi_buf);}
1813      s.pending_buf^[s.pending] := Byte(s.bi_buf);
1814      inc(s.pending);
1815 
1816      s.bi_buf := s.bi_buf shr 8;
1817      dec(s.bi_valid, 8);
1818    end;
1819 end;
1820 
1821 
1822 { ===========================================================================
1823   Send one empty static block to give enough lookahead for inflate.
1824   This takes 10 bits, of which 7 may remain in the bit buffer.
1825   The current inflate code requires 9 bits of lookahead. If the
1826   last two codes for the previous block (real code plus EOB) were coded
1827   on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
1828   the last real code. In this case we send two empty static blocks instead
1829   of one. (There are no problems if the previous block is stored or fixed.)
1830   To simplify the code, we assume the worst case of last real code encoded
1831   on one bit only. }
1832 
1833 procedure _tr_align(var s : deflate_state);
1834 begin
1835   send_bits(s, STATIC_TREES shl 1, 3);
1836   {$ifdef ZLIB_DEBUG}
1837   Tracevvv(#13'cd '+IntToStr(END_BLOCK));
1838   {$ENDIF}
1839   send_bits(s, static_ltree[END_BLOCK].fc.Code, static_ltree[END_BLOCK].dl.Len);
1840   inc(s.compressed_len, cardinal(10)); { 3 for block type, 7 for EOB }
1841   bi_flush(s);
1842   { Of the 10 bits for the empty block, we have already sent
1843     (10 - bi_valid) bits. The lookahead for the last real code (before
1844     the EOB of the previous block) was thus at least one plus the length
1845     of the EOB plus what we have just sent of the empty static block. }
1846   if (1 + s.last_eob_len + 10 - s.bi_valid < 9) then
1847   begin
1848     send_bits(s, STATIC_TREES shl 1, 3);
1849     {$ifdef ZLIB_DEBUG}
1850     Tracevvv(#13'cd '+IntToStr(END_BLOCK));
1851     {$ENDIF}
1852     send_bits(s, static_ltree[END_BLOCK].fc.Code, static_ltree[END_BLOCK].dl.Len);
1853     inc(s.compressed_len, cardinal(10));
1854     bi_flush(s);
1855   end;
1856   s.last_eob_len := 7;
1857 end;
1858 
1859 { ===========================================================================
1860   Set the data type to ASCII or BINARY, using a crude approximation:
1861   binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
1862   IN assertion: the fields freq of dyn_ltree are set and the total of all
1863   frequencies does not exceed 64K (to fit in an integer on 16 bit machines). }
1864 
1865 {local}
1866 procedure set_data_type(var s : deflate_state);
1867 var
1868   n : integer;
1869   ascii_freq : cardinal;
1870   bin_freq : cardinal;
1871 begin
1872   n := 0;
1873   ascii_freq := 0;
1874   bin_freq := 0;
1875 
1876   while (n < 7) do
1877   begin
1878     inc(bin_freq, s.dyn_ltree[n].fc.Freq);
1879     inc(n);
1880   end;
1881   while (n < 128) do
1882   begin
1883     inc(ascii_freq, s.dyn_ltree[n].fc.Freq);
1884     inc(n);
1885   end;
1886   while (n < LITERALS) do
1887   begin
1888     inc(bin_freq, s.dyn_ltree[n].fc.Freq);
1889     inc(n);
1890   end;
1891   if (bin_freq > (ascii_freq shr 2)) then
1892     s.data_type := Byte(Z_BINARY)
1893   else
1894     s.data_type := Byte(Z_ASCII);
1895 end;
1896 
1897 { ===========================================================================
1898   Send the block data compressed using the given Huffman trees }
1899 
1900 {local}
1901 procedure compress_block(var s : deflate_state;
1902                          var ltree : array of ct_data;   { literal tree }
1903                          var dtree : array of ct_data);  { distance tree }
1904 var
1905   dist : cardinal;      { distance of matched string }
1906   lc : integer;             { match length or unmatched char (if dist == 0) }
1907   lx : cardinal;        { running index in l_buf }
1908   code : cardinal;      { the code to send }
1909   extra : integer;          { number of extra bits to send }
1910 begin
1911   lx := 0;
1912   if (s.last_lit <> 0) then
1913   repeat
1914     dist := s.d_buf^[lx];
1915     lc := s.l_buf^[lx];
1916     inc(lx);
1917     if (dist = 0) then
1918     begin
1919       { send a literal byte }
1920       {$ifdef ZLIB_DEBUG}
1921       Tracevvv(#13'cd '+IntToStr(lc));
1922       Tracecv((lc > 31) and (lc < 128), ' '+char(lc)+' ');
1923       {$ENDIF}
1924       send_bits(s, ltree[lc].fc.Code, ltree[lc].dl.Len);
1925     end
1926     else
1927     begin
1928       { Here, lc is the match length - MIN_MATCH }
1929       code := _length_code[lc];
1930       { send the length code }
1931       {$ifdef ZLIB_DEBUG}
1932       Tracevvv(#13'cd '+IntToStr(code+LITERALS+1));
1933       {$ENDIF}
1934       send_bits(s, ltree[code+LITERALS+1].fc.Code, ltree[code+LITERALS+1].dl.Len);
1935       extra := extra_lbits[code];
1936       if (extra <> 0) then
1937       begin
1938         dec(lc, base_length[code]);
1939         send_bits(s, lc, extra);       { send the extra length bits }
1940       end;
1941       dec(dist); { dist is now the match distance - 1 }
1942       {code := d_code(dist);}
1943       if (dist < 256) then
1944         code := _dist_code[dist]
1945       else
1946         code := _dist_code[256+(dist shr 7)];
1947 
1948       {$IFDEF ZLIB_DEBUG}
1949       Assert (code < D_CODES, 'bad d_code');
1950       {$ENDIF}
1951 
1952       { send the distance code }
1953       {$ifdef ZLIB_DEBUG}
1954       Tracevvv(#13'cd '+IntToStr(code));
1955       {$ENDIF}
1956       send_bits(s, dtree[code].fc.Code, dtree[code].dl.Len);
1957       extra := extra_dbits[code];
1958       if (extra <> 0) then
1959       begin
1960         dec(dist, base_dist[code]);
1961         send_bits(s, dist, extra);   { send the extra distance bits }
1962       end;
1963     end; { literal or match pair ? }
1964 
1965     { Check that the overlay between pending_buf and d_buf+l_buf is ok: }
1966     {$IFDEF ZLIB_DEBUG}
1967     Assert(s.pending < s.lit_bufsize + 2*lx, 'pendingBuf overflow');
1968     {$ENDIF}
1969   until (lx >= s.last_lit);
1970 
1971   {$ifdef ZLIB_DEBUG}
1972   Tracevvv(#13'cd '+IntToStr(END_BLOCK));
1973   {$ENDIF}
1974   send_bits(s, ltree[END_BLOCK].fc.Code, ltree[END_BLOCK].dl.Len);
1975   s.last_eob_len := ltree[END_BLOCK].dl.Len;
1976 end;
1977 
1978 
1979 { ===========================================================================
1980   Determine the best encoding for the current block: dynamic trees, static
1981   trees or store, and output the encoded block to the zip file. This function
1982   returns the total compressed length for the file so far. }
1983 
_tr_flush_blocknull1984 function _tr_flush_block (var s : deflate_state;
1985          buf : Pbyte;         { input block, or NULL if too old }
1986          stored_len : longint;     { length of input block }
1987          eof : boolean) : longint; { true if this is the last block for a file }
1988 var
1989   opt_lenb, static_lenb : longint; { opt_len and static_len in bytes }
1990   max_blindex : integer;  { index of last bit length code of non zero freq }
1991 begin
1992   max_blindex := 0;
1993 
1994   { Build the Huffman trees unless a stored block is forced }
1995   if (s.level > 0) then
1996   begin
1997     { Check if the file is ascii or binary }
1998     if (s.data_type = Z_UNKNOWN) then
1999       set_data_type(s);
2000 
2001     { Construct the literal and distance trees }
2002     build_tree(s, s.l_desc);
2003     {$ifdef ZLIB_DEBUG}
2004     Tracev(^M'lit data: dyn %ld, stat %ld {s.opt_len, s.static_len}');
2005     {$ENDIF}
2006 
2007     build_tree(s, s.d_desc);
2008     {$ifdef ZLIB_DEBUG}
2009     Tracev(^M'dist data: dyn %ld, stat %ld {s.opt_len, s.static_len}');
2010     {$ENDIF}
2011     { At this point, opt_len and static_len are the total bit lengths of
2012       the compressed block data, excluding the tree representations. }
2013 
2014     { Build the bit length tree for the above two trees, and get the index
2015       in bl_order of the last bit length code to send. }
2016     max_blindex := build_bl_tree(s);
2017 
2018     { Determine the best encoding. Compute first the block length in bytes}
2019     opt_lenb := (s.opt_len+3+7) shr 3;
2020     static_lenb := (s.static_len+3+7) shr 3;
2021 
2022     {$ifdef ZLIB_DEBUG}
2023     Tracev(^M'opt %lu(%lu) stat %lu(%lu) stored %lu lit %u '+
2024 	    '{opt_lenb, s.opt_len, static_lenb, s.static_len, stored_len,'+
2025 	    's.last_lit}');
2026     {$ENDIF}
2027 
2028     if (static_lenb <= opt_lenb) then
2029       opt_lenb := static_lenb;
2030 
2031   end
2032   else
2033   begin
2034     {$IFDEF ZLIB_DEBUG}
2035     Assert(buf <> nil, 'lost buf');
2036     {$ENDIF}
2037     static_lenb := stored_len + 5;
2038     opt_lenb := static_lenb;        { force a stored block }
2039   end;
2040 
2041   { If compression failed and this is the first and last block,
2042     and if the .zip file can be seeked (to rewrite the local header),
2043     the whole file is transformed into a stored file:  }
2044 
2045 {$ifdef STORED_FILE_OK}
2046 {$ifdef FORCE_STORED_FILE}
2047   if eof and (s.compressed_len = 0) then
2048   begin { force stored file }
2049 {$else}
2050   if (stored_len <= opt_lenb) and eof and (s.compressed_len=cardinal(0))
2051      and seekable()) do
2052   begin
2053 {$endif}
2054     { Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: }
2055     if buf=nil then
2056       error ('block vanished');
2057 
2058     copy_block(buf, cardinal(stored_len), 0); { without header }
2059     s.compressed_len := stored_len shl 3;
2060     s.method := STORED;
2061   end
2062   else
2063 {$endif} { STORED_FILE_OK }
2064 
2065 {$ifdef FORCE_STORED}
2066   if buf<>nil then
2067   begin { force stored block }
2068 {$else}
2069   if (stored_len+4 <= opt_lenb) and (buf <> nil) then
2070   begin
2071                      { 4: two words for the lengths }
2072 {$endif}
2073     { The test buf <> NULL is only necessary if LIT_BUFSIZE > WSIZE.
2074       Otherwise we can't have processed more than WSIZE input bytes since
2075       the last block flush, because compression would have been
2076       successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
2077       transform a block into a stored block. }
2078 
2079     _tr_stored_block(s, buf, stored_len, eof);
2080 
2081 {$ifdef FORCE_STATIC}
2082   end
2083   else
2084     if (static_lenb >= 0) then
2085     begin { force static trees }
2086 {$else}
2087   end
2088   else
2089     if (static_lenb = opt_lenb) then
2090     begin
2091 {$endif}
2092       send_bits(s, (STATIC_TREES shl 1)+ord(eof), 3);
2093       compress_block(s, static_ltree, static_dtree);
2094       inc(s.compressed_len, 3 + s.static_len);
2095     end
2096     else
2097     begin
2098       send_bits(s, (DYN_TREES shl 1)+ord(eof), 3);
2099       send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1,
2100                      max_blindex+1);
2101       compress_block(s, s.dyn_ltree, s.dyn_dtree);
2102       inc(s.compressed_len, 3 + s.opt_len);
2103     end;
2104   {$ifdef ZLIB_DEBUG}
2105   Assert (s.compressed_len = s.bits_sent, 'bad compressed size');
2106   {$ENDIF}
2107   init_block(s);
2108 
2109   if (eof) then
2110   begin
2111     bi_windup(s);
2112     inc(s.compressed_len, 7);  { align on byte boundary }
2113   end;
2114   {$ifdef ZLIB_DEBUG}
2115   Tracev(#13'comprlen %lu(%lu) {s.compressed_len shr 3,'+
2116          's.compressed_len-7*ord(eof)}');
2117   {$ENDIF}
2118 
2119   _tr_flush_block := s.compressed_len shr 3;
2120 end;
2121 
2122 
2123 { ===========================================================================
2124   Save the match info and tally the frequency counts. Return true if
2125   the current block must be flushed. }
2126 
_tr_tallynull2127 function _tr_tally (var s : deflate_state;
2128    dist : cardinal;          { distance of matched string }
2129    lc : cardinal) : boolean; { match length-MIN_MATCH or unmatched char (if dist=0) }
2130 var
2131   {$IFDEF ZLIB_DEBUG}
2132   MAX_DIST : word;
2133   {$ENDIF}
2134   code : word;
2135 {$ifdef TRUNCATE_BLOCK}
2136 var
2137   out_length : longint;
2138   in_length : longint;
2139   dcode : integer;
2140 {$endif}
2141 begin
2142   s.d_buf^[s.last_lit] := word(dist);
2143   s.l_buf^[s.last_lit] := byte(lc);
2144   inc(s.last_lit);
2145   if (dist = 0) then
2146   begin
2147     { lc is the unmatched char }
2148     inc(s.dyn_ltree[lc].fc.Freq);
2149   end
2150   else
2151   begin
2152     inc(s.matches);
2153     { Here, lc is the match length - MIN_MATCH }
2154     dec(dist);             { dist := match distance - 1 }
2155 
2156     {macro d_code(dist)}
2157     if (dist) < 256 then
2158       code := _dist_code[dist]
2159     else
2160       code := _dist_code[256+(dist shr 7)];
2161     {$IFDEF ZLIB_DEBUG}
2162 {macro  MAX_DIST(s) <=> ((s)^.w_size-MIN_LOOKAHEAD)
2163    In order to simplify the code, particularly on 16 bit machines, match
2164    distances are limited to MAX_DIST instead of WSIZE. }
2165     MAX_DIST := word(s.w_size-MIN_LOOKAHEAD);
2166     Assert((dist < word(MAX_DIST)) and
2167            (word(lc) <= word(MAX_MATCH-MIN_MATCH)) and
2168            (word(code) < word(D_CODES)),  '_tr_tally: bad match');
2169     {$ENDIF}
2170     inc(s.dyn_ltree[_length_code[lc]+LITERALS+1].fc.Freq);
2171     {s.dyn_dtree[d_code(dist)].Freq++;}
2172     inc(s.dyn_dtree[code].fc.Freq);
2173   end;
2174 
2175 {$ifdef TRUNCATE_BLOCK}
2176   { Try to guess if it is profitable to stop the current block here }
2177   if (s.last_lit and $1fff = 0) and (s.level > 2) then
2178   begin
2179     { Compute an upper bound for the compressed length }
2180     out_length := longint(s.last_lit)*cardinal(8);
2181     in_length := longint(cardinal(s.strstart) - s.block_start);
2182     for dcode := 0 to D_CODES-1 do
2183     begin
2184       inc(out_length, longint(s.dyn_dtree[dcode].fc.Freq *
2185             (cardinal(5)+extra_dbits[dcode])) );
2186     end;
2187     out_length := out_length shr 3;
2188     {$ifdef ZLIB_DEBUG}
2189     Tracev(^M'last_lit %u, in %ld, out ~%ld(%ld%%) ');
2190           { s.last_lit, in_length, out_length,
2191            cardinal(100) - out_length*100 div in_length)); }
2192     {$ENDIF}
2193     if (s.matches < s.last_lit div 2) and (out_length < in_length div 2) then
2194     begin
2195       _tr_tally := TRUE;
2196       exit;
2197     end;
2198   end;
2199 {$endif}
2200   _tr_tally := (s.last_lit = s.lit_bufsize-1);
2201   { We avoid equality with lit_bufsize because of wraparound at 64K
2202     on 16 bit machines and because stored blocks are restricted to
2203     64K-1 bytes. }
2204 end;
2205 
2206 end.
2207