download MZLib.pas
Language: Delphi
License: ZLL
Copyright: (C) 1995-1998 Jean-loup Gailly and Mark Adler (C) 2000 by Dipl. Ing. Mike Lischke (www.delphi-gems.com)
LOC: 3979
Project Info
GLXTreem
Server: Spider_20090120_inc
Type: filesystem
...01‑12.zip\Source\GraphicEx\
   GraphicColor.pas
   GraphicCompression.pas
   GraphicEx.pas
   GraphicStrings.pas
   GraphicStringsDE.pas
   GraphicStringsFR.pas
   GraphicStringsRU.pas
   JPG.pas
   MZLib.pas

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
unit MZLib;

// Original copyright of the creators:
//
// zlib.H -- interface of the 'zlib' general purpose compression library version 1.1.0, Feb 24th, 1998
//
// Copyright (C) 1995-1998 Jean-loup Gailly and Mark Adler
//
// This software is provided 'as-is', without any express or implied warranty.  In no event will the authors be held
// liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter
// it and redistribute it freely, subject to the following restrictions:
// 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software.
//    If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is
//    not required.
// 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// 3. This notice may not be removed or altered from any Source distribution.
//
// Jean-loup Gailly        Mark Adler
// jloup@gzip.org          madler@alumni.caltech.edu
//
// The data format used by the zlib library is described by RFCs (Request for Comments) 1950 to 1952 in the files
// ftp://deststate.internic.net/rfc/rfc1950.txt (zlib format), rfc1951.txt (Deflate format) and rfc1952.txt (gzip format).
//
// patch 112 from the zlib home page is implicitly applied here
//
// Delphi translation: (C) 2000 by Dipl. Ing. Mike Lischke (www.delphi-gems.com)

interface

uses
  Windows;
  
// The 'zlib' compression library provides in-memory compression and decompression functions, including integrity checks
// of the uncompressed data. This version of the library supports only one compression method (deflation) but other
// algorithms will be added later and will have the same stream interface.
//
// Compression can be done in a single step if the buffers are large enough (for example if an input file is mmap'ed),
// or can be done by repeated calls of the compression function. In the latter case, the application must provide more
// input and/or consume the output (providing more output space) before each call.
//
// The library also supports reading and writing files in gzip (.gz) format.
//
// The library does not install any signal handler. The decoder checks
// the consistency of the compressed data, so the library should never
// crash even in case of corrupted input.

//----------------- general library stuff ------------------------------------------------------------------------------

resourcestring
  SNeedDict = 'need dictionary';
  SStreamEnd = 'stream end';
  SFileError = 'file error';
  SStreamError = 'stream error';
  SDataError = 'data error';
  SInsufficientMemory = 'insufficient memory';
  SBufferError = 'buffer error';
  SIncompatibleVersion = 'incompatible version';
  SInvalidDistanceCode = 'invalid distance code';
  SInvalidLengthCode = 'invalid literal/length code';
  SOversubscribedDBLTree = 'oversubscribed dynamic bit lengths tree';
  SIncompleteDBLTree = 'incomplete dynamic bit lengths tree';
  SOversubscribedLLTree = 'oversubscribed literal/length tree';
  SIncompleteLLTree = 'incomplete literal/length tree';
  SEmptyDistanceTree = 'empty distance tree with lengths';
  SInvalidBlockType = 'invalid block type';
  SInvalidStoredBlockLengths = 'invalid stored block lengths';
  STooManyLDSymbols = 'too many length or distance symbols';
  SInvalidBitLengthRepeat = 'invalid bit length repeat';
  SIncorrectDataCheck = 'incorrect data check';
  SUnknownCompression = 'unknown compression method';
  SInvalidWindowSize = 'invalid window size';
  SIncorrectHeaderCheck = 'incorrect header check';
  SNeedDictionary = 'need dictionary';

type
  PWord = ^Word;
  PInteger = ^Integer;
  PCardinal = ^Cardinal;

type
  TByteArray = array[0..(MaxInt div SizeOf(Byte)) - 1] of Byte;
  PByteArray = ^TByteArray;

  TWordArray = array[0..(MaxInt div SizeOf(Word)) - 1] of Word;
  PWordArray = ^TWordArray;

  TIntegerArray = array[0..(MaxInt div SizeOf(Integer)) - 1] of Integer;
  PIntegerArray = ^TIntegerArray;

  TCardinalArray = array[0..(MaxInt div SizeOf(Cardinal)) - 1] of Cardinal;
  PCardinalArray = ^TCardinalArray;

const
  // maximum value for MemLevel in DeflateInit2
  MAX_MEM_LEVEL = 9;
  DEF_MEM_LEVEL = 8;

  // maximum value for WindowBits in DeflateInit2 and InflateInit2
  MAX_WBITS = 15; // 32K LZ77 window

  // default WindowBits for decompression, MAX_WBITS is for compression only
  DEF_WBITS = MAX_WBITS;

type
  PInflateHuft = ^TInflateHuft;
  TInflateHuft = record
    Exop,           // number of extra bits or operation
    Bits: Byte;     // number of bits in this code or subcode
    Base: Cardinal; // literal, Length base, or distance base or table offset
  end;

  THuftField = array[0..(MaxInt div SizeOf(TInflateHuft)) - 1] of TInflateHuft;
  PHuftField = ^THuftField;
  PPInflateHuft = ^PInflateHuft;

  TInflateCodesMode = ( // waiting for "I:"=input, "O:"=output, "X:"=nothing
    icmStart,    // X: set up for Len
    icmLen,      // I: get length/literal/eob next
    icmLenNext,  // I: getting length extra (have base)
    icmDistance, // I: get distance next
    icmDistExt,  // I: getting distance extra
    icmCopy,     // O: copying bytes in window, waiting for space
    icmLit,      // O: got literal, waiting for output space
    icmWash,     // O: got eob, possibly still output waiting
    icmZEnd,     // X: got eob and all data flushed
    icmBadCode   // X: got error
  );

  // inflate codes private state 
  PInflateCodesState = ^TInflateCodesState;
  TInflateCodesState = record
    Mode: TInflateCodesMode;    // current inflate codes mode
    // mode dependent information
    Len: Cardinal;
    Sub: record                 // submode
      case Byte of
        0:
          (Code: record         // if Len or Distance, where in tree
             Tree: PInflateHuft; // pointer into tree
             need: Cardinal;    // bits needed
           end);
        1:
          (lit: Cardinal);      // if icmLit, literal
        2:
          (copy: record         // if EXT or icmCopy, where and how much
             get: Cardinal;     // bits to get for extra
             Distance: Cardinal; // distance back to copy from
           end);
    end;

    // mode independent information
    LiteralTreeBits: Byte;      // LiteralTree bits decoded per branch
    DistanceTreeBits: Byte;     // DistanceTree bits decoder per branch
    LiteralTree: PInflateHuft;  // literal/length/eob tree
    DistanceTree: PInflateHuft; // distance tree
  end;

  TCheckFunction = function(Check: Cardinal; Buffer: PByte; Len: Cardinal): Cardinal;

  TInflateBlockMode = (
    ibmZType,     // get type bits (3, including end bit)
    ibmLens,      // get lengths for stored
    ibmStored,    // processing stored block
    ibmTable,     // get table lengths
    ibmBitTree,   // get bit lengths tree for a dynamic block
    ibmDistTree,  // get length, distance trees for a dynamic block
    ibmCodes,     // processing fixed or dynamic block
    ibmDry,       // output remaining window bytes
    ibmBlockDone, // finished last block, done
    ibmBlockBad   // got a data error -> stuck here
  );

  // inflate blocks semi-private state
  PInflateBlocksState = ^TInflateBlocksState;
  TInflateBlocksState = record
    Mode: TInflateBlockMode;     // current inflate block mode
    // mode dependent information 
    Sub: record                        // submode
      case Byte of
        0:
          (left: Cardinal);            // if ibmStored, bytes left to copy
        1:
          (Trees: record               // if DistanceTree, decoding info for trees
             Table: Cardinal;          // table lengths (14 Bits)
             Index: Cardinal;          // index into blens (or BitOrder)
             blens: PCardinalArray;    // bit lengths of codes
             BB: Cardinal;             // bit length tree depth
             TB: PInflateHuft;         // bit length decoding tree
           end);
        2:
          (decode: record              // if ibmCodes, current state
             TL: PInflateHuft;
             TD: PInflateHuft;         // trees to free
             codes: PInflateCodesState;
           end);
    end;
    Last: Boolean;                     // True if this block is the last block

    // mode independent information
    bitk: Cardinal;                    // bits in bit buffer
    bitb: Cardinal;                    // bit buffer
    hufts: PHuftField;                 // single allocation for tree space
    window: PByte;                     // sliding window
    zend: PByte;                       // one byte after sliding window
    read: PByte;                       // window read pointer
    write: PByte;                      // window write pointer
    CheckFunction: TCheckFunction;     // check function
    Check: Cardinal;                   // check on output
  end;

  TInflateMode = (
    imMethod,   // waiting for imMethod Byte
    imFlag,     // waiting for flag byte
    imDict4,    // four dictionary check bytes to go
    imDict3,    // three dictionary check bytes to go
    imDict2,    // two dictionary check bytes to go
    imDict1,    // one dictionary check byte to go
    imDict0,    // waiting for InflateSetDictionary
    imBlocks,   // decompressing blocks
    imCheck4,   // four check bytes to go
    imCheck3,   // three check bytes to go
    imCheck2,   // two check bytes to go
    imCheck1,   // one check byte to go
    imDone,     // finished check, done
    imBad       // got an error -> stay here
  );

  // inflate private state
  PInternalState = ^TInternalState;
  TInternalState = record
    Mode: TInflateMode;                // current inflate mode
    // mode dependent information
    Sub: record                        // submode
      case Byte of
        0:
          (imMethod: Cardinal);        // if FLAGS, imMethod byte
        1:
          (Check: record               // if check, check values to compare
             was: Cardinal;            // computed check value
             need: Cardinal;           // stream check value
           end);
        2:
         (marker: Cardinal);           // if imBad, InflateSync's marker bytes count
    end;

     // mode independent information
    nowrap: Boolean;                   // flag for no wrapper
    wbits: Cardinal;                   // log2(window Size) (8..15, defaults to 15)
    blocks: PInflateBlocksState;       // current InflateBlocks state
  end;


  // The application must update NextInput and AvailableInput when AvailableInput has dropped to zero. It must update
  // NextOutput and AvailableOutput when AvailableOutput has dropped to zero. All other fields are set by the
  // compression library and must not be updated by the application.
  //
  // The fields TotalInput and TotalOutput can be used for statistics or progress reports. After compression, TotalInput
  // holds the total size of the uncompressed data and may be saved for use in the decompressor
  // (particularly if the decompressor wants to decompress everything in a single step).

  PZState = ^TZState;
  TZState = record
    NextInput: PByte;           // next input byte
    AvailableInput: Cardinal;   // number of bytes available at NextInput
    TotalInput: Cardinal;       // total number of input bytes read so far
    NextOutput: PByte;          // next output byte should be put there
    AvailableOutput: Cardinal;  // remaining free space at NextOutput
    TotalOutput: Cardinal;      // total number of bytes output so far
    Msg: String;                // last error message, '' if no error
    State: PInternalState;      // not visible by applications
    DataType: Integer;          // best guess about the data type: ASCII or binary
    Adler: Cardinal;            // Adler32 value of the uncompressed data
  end;

const
  // allowed flush values, see Deflate below for details
  Z_NO_FLUSH = 0;
  Z_PARTIAL_FLUSH = 1;
  Z_SYNC_FLUSH = 2;
  Z_FULL_FLUSH = 3;
  Z_FINISH = 4;

  // Return codes for the compression/decompression functions. Negative
  // values are errors, positive values are used for special but normal events.
  Z_OK = 0;
  Z_STREAM_END = 1;
  Z_NEED_DICT = 2;
  Z_ERRNO = -1;
  Z_STREAM_ERROR = -2;
  Z_DATA_ERROR = -3;
  Z_MEM_ERROR = -4;
  Z_BUF_ERROR = -5;
  Z_VERSION_ERROR = -6;

  // compression levels
  Z_DEFAULT_COMPRESSION = -1;
  Z_NO_COMPRESSION = 0;
  Z_BEST_SPEED = 1;
  Z_BEST_COMPRESSION = 9;

  // compression strategy, see DeflateInit2 below for details 
  Z_DEFAULT_STRATEGY = 0;
  Z_FILTERED = 1;
  Z_HUFFMAN_ONLY = 2;

  // possible values of the DataType field
  Z_BINARY = 0;
  Z_ASCII = 1;
  Z_UNKNOWN = 2;

  // the Deflate compression imMethod (the only one supported in this Version) 
  Z_DEFLATED = 8;

  // three kinds of block type
  STORED_BLOCK = 0;
  STATIC_TREES = 1;
  DYN_TREES = 2;

  // minimum and maximum match lengths
  MIN_MATCH = 3;
  MAX_MATCH = 258;

  // preset dictionary flag in zlib header
  PRESET_DICT = $20;

  ZLIB_VERSION: String[10] = '1.1.2';

  ERROR_BASE = Z_NEED_DICT;
  ErrorMessages: array[0..9] of String = (
    SNeedDict,            // Z_NEED_DICT       2
    SStreamEnd,           // Z_STREAM_END      1
    '',                   // Z_OK              0
    SFileError,           // Z_ERRNO          -1
    SStreamError,         // Z_STREAM_ERROR   -2
    SDataError,           // Z_DATA_ERROR     -3
    SInsufficientMemory,  // Z_MEM_ERROR      -4
    SBufferError,         // Z_BUF_ERROR      -5
    SIncompatibleVersion, // Z_VERSION_ERROR  -6
    ''
  );

function zError(Error: Integer): String;
function CRC32(CRC: Cardinal; Buffer: PByte; Len: Cardinal): Cardinal;

//----------------- deflation support ----------------------------------------------------------------------------------

function DeflateInit(var ZState: TZState; Level: Integer): Integer;
function DeflateInit_(ZState: PZState; Level: Integer; const Version: String; StreamSize: Integer): Integer;
function Deflate(var ZState: TZState; Flush: Integer): Integer;
function DeflateEnd(var ZState: TZState): Integer;

// The following functions are needed only in some special applications.
function DeflateInit2(var ZState: TZState; Level: Integer; Method: Byte; AWindowBits: Integer; MemLevel: Integer;
  Strategy: Integer): Integer;
function DeflateSetDictionary(var ZState: TZState; Dictionary: PByte; DictLength: Cardinal): Integer;
function DeflateCopy(Dest: PZState; Source: PZState): Integer;
function DeflateReset(var ZState: TZState): Integer;
function DeflateParams(var ZState: TZState; Level: Integer; Strategy: Integer): Integer;

const
  LENGTH_CODES = 29;         // number of length codes, not counting the special END_BLOCK code
  LITERALS = 256;            // number of literal bytes 0..255
  L_CODES = (LITERALS + 1 + LENGTH_CODES);
                             // number of literal or length codes, including the END_BLOCK code
  D_CODES = 30;              // number of distance codes
  BL_CODES = 19;             // number of codes used to transfer the bit lengths
  HEAP_SIZE = (2 * L_CODES + 1); // maximum heap size
  MAX_BITS = 15;             // all codes must not exceed MAX_BITS bits

  // stream status 
  INIT_STATE =  42;
  BUSY_STATE =  113;
  FINISH_STATE = 666;

type
  // data structure describing a single value and its code string 
  PTreeEntry = ^TTreeEntry;
  TTreeEntry = record
    fc: record
      case Byte of
        0:
          (Frequency: Word); // frequency count
        1:
          (Code: Word); // bit string
    end;
    dl: record
      case Byte of
        0:
          (dad: Word);  // father node in Huffman tree
        1:
          (Len: Word);  // length of bit string
    end;
  end;

  TLiteralTree = array[0..HEAP_SIZE - 1] of TTreeEntry; // literal and length tree
  TDistanceTree = array[0..2 * D_CODES] of TTreeEntry; // distance tree
  THuffmanTree = array[0..2 * BL_CODES] of TTreeEntry; // Huffman tree for bit lengths

  PTree = ^TTree;
  TTree = array[0..(MaxInt div SizeOf(TTreeEntry)) - 1] of TTreeEntry; // generic tree type

  PStaticTreeDescriptor = ^TStaticTreeDescriptor;
  TStaticTreeDescriptor = record
    StaticTree: PTree;        // static tree or nil
    ExtraBits: PIntegerArray; // extra bits for each code or nil
    ExtraBase: Integer;       // base index for ExtraBits
    Elements: Integer;        // max number of elements in the tree
    MaxLength: Integer;       // max bit length for the codes
  end;
  
  PTreeDescriptor = ^TTreeDescriptor;
  TTreeDescriptor = record
    DynamicTree: PTree;     
    MaxCode: Integer;                        // largest code with non zero frequency
    StaticDescriptor: PStaticTreeDescriptor; // the corresponding static tree
  end;

  PDeflateState = ^TDeflateState;
  TDeflateState = record
    ZState: PZState;            // pointer back to this zlib stream
    Status: Integer;            // as the name implies
    PendingBuffer: PByteArray;  // output still pending
    PendingBufferSize: Integer;
    PendingOutput: PByte;       // next pending byte to output to the stream
    Pending: Integer;           // nb of bytes in the pending buffer
    NoHeader: Integer;          // suppress zlib header and Adler32
    DataType: Byte;             // UNKNOWN, BINARY or ASCII
    imMethod: Byte;             // ibmStored (for zip only) or DEFLATED
    LastFlush: Integer;         // Value of flush param for previous deflate call
    WindowSize: Cardinal;       // LZ77 window size (32K by default)
    WindowBits: Cardinal;       // log2(WindowSize) (8..16)
    WindowMask: Cardinal;       // WindowSize - 1

    // Sliding window. Input bytes are read into the second half of the window,
    // and move to the first half later to keep a dictionary of at least WSize
    // bytes. With this organization, matches are limited to a distance of
    // WSize - MAX_MATCH bytes, but this ensures that IO is always
    // performed with a length multiple of the block Size. Also, it limits
    // the window Size to 64K, which is quite useful on MSDOS.
    // To do: use the user input buffer as sliding window.
    Window: PByteArray;

    // Actual size of Window: 2 * WSize, except when the user input buffer
    // is directly used as sliding window.
    CurrentWindowSize: Integer;

    // Link to older string with same hash index. to limit the size of this
    // array to 64K, this link is maintained only for the last 32K strings.
    // An index in this array is thus a window index modulo 32K.
    Previous: PWordArray;

    Head: PWordArray;           // heads of the hash chains or nil

    InsertHash: Cardinal;       // hash index of string to be inserted
    HashSize: Cardinal;         // number of elements in hash table
    HashBits: Cardinal;         // log2(HashSize)
    HashMask: Cardinal;         // HashSize - 1

    // Number of bits by which InsertHash must be shifted at each input step.
    // It must be such that after MIN_MATCH steps, the oldest byte no longer
    // takes part in the hash key, that is:
    // HashShift * MIN_MATCH >= HashBits
    HashShift: Cardinal;

    // Window position at the beginning of the current output block. Gets
    // negative when the window is moved backwards. 
    BlockStart: Integer;

    MatchLength: Cardinal;      // length of best match
    PreviousMatch: Cardinal;    // previous match
    MatchAvailable: Boolean;    // set if previous match exists
    StringStart: Cardinal;      // start of string to insert
    MatchStart: Cardinal;       // start of matching string
    Lookahead: Cardinal;        // number of valid bytes ahead in window 

    // Length of the best match at previous step. Matches not greater than this
    // are discarded. This is used in the lazy match evaluation.
    PreviousLength: Cardinal;

    // To speed up deflation hash chains are never searched beyond this
    // Length. A higher limit improves compression ratio but degrades the speed. 
    MaxChainLength: Cardinal;

    Level: Integer;             // compression level (1..9)
    Strategy: Integer;          // favor or force Huffman coding
    GoodMatch: Cardinal;        // use a faster search when the previous match is longer than this
    NiceMatch: Cardinal;        // stop searching when current match exceeds this

    LiteralTree: TLiteralTree;  // literal and length tree
    DistanceTree: TDistanceTree; // distance tree
    BitLengthTree: THuffmanTree; // Huffman tree for bit lengths

    LiteralDescriptor: TTreeDescriptor; // Descriptor for literal tree
    DistanceDescriptor: TTreeDescriptor; // Descriptor for distance tree
    BitLengthDescriptor: TTreeDescriptor; // Descriptor for bit length tree 

    BitLengthCounts: array[0..MAX_BITS] of Word; // number of codes at each bit length for an optimal tree

    Heap: array[0..2 * L_CODES] of Integer; // heap used to build the Huffman trees 
    HeapLength: Integer;        // number of elements in the heap
    HeapMaximum: Integer;       // element of largest frequency
    // The sons of Heap[N] are Heap[2 * N] and Heap[2 * N + 1]. Heap[0] is not used.
    // The same heap array is used to build all trees.

    Depth: array[0..2 * L_CODES] of Byte; // depth of each subtree used as tie breaker for trees of equal frequency

    LiteralBuffer: PByteArray;       // buffer for literals or lengths

    // Size of match buffer for literals/lengths. There are 4 reasons for limiting LiteralBufferSize to 64K:
    //  - frequencies can be kept in 16 bit counters
    //  - If compression is not successful for the first block, all input
    //    data is still in the window so we can still emit a stored block even
    //    when input comes from standard input. This can also be done for
    //    all blocks if LiteralBufferSize is not greater than 32K.
    //  - if compression is not successful for a file smaller than 64K, we can
    //    even emit a stored file instead of a stored block (saving 5 bytes).
    //    This is applicable only for zip (not gzip or zlib).
    //  - creating new Huffman trees less frequently may not provide fast
    //    adaptation to changes in the input data statistics. (Take for
    //    example a binary file with poorly compressible code followed by
    //    a highly compressible string table.) Smaller buffer sizes give
    //    fast adaptation but have of course the overhead of transmitting
    //    trees more frequently.
    //  - I can't count above 4
    LiteralBufferSize: Cardinal;

    LastLiteral: Cardinal;      // running index in LiteralBuffer

    // Buffer for distances. To simplify the code, DistanceBuffer and LiteralBuffer have
    // the same number of elements. To use different lengths, an extra flag array would be necessary.
    DistanceBuffer: PWordArray;

    OptimalLength: Integer;     // bit length of current block with optimal trees
    StaticLength: Integer;      // bit length of current block with static trees
    CompressedLength: Integer;  // total bit length of compressed file
    Matches: Cardinal;          // number of string matches in current block
    LastEOBLength: Integer;     // bit length of EOB code for last block
    BitsBuffer: Word;           // Output buffer. Bits are inserted starting at the bottom (least significant bits).
    ValidBits: Integer;         // Number of valid bits in BitsBuffer. All Bits above the last valid bit are always zero.
    case Byte of
      0:
        // Attempt to find a better match only when the current match is strictly smaller than this value.
        // This mechanism is used only for compression levels >= 4.
        (MaxLazyMatch: Cardinal);
      1:
        // Insert new strings in the hash table only if the match Length is not greater than this length. This saves
        // time but degrades compression. MaxInsertLength is used only for compression levels <= 3. 
        (MaxInsertLength: Cardinal);
  end;

//----------------- inflation support ----------------------------------------------------------------------------------

function InflateInit(var Z: TZState): Integer;
function InflateInit_(var Z: TZState; const Version: String; StreamSize: Integer): Integer;
function InflateInit2_(var Z: TZState; W: Integer; const Version: String; StreamSize: Integer): Integer;
function InflateInit2(var Z: TZState; AWindowBits: Integer): Integer;
function InflateEnd(var Z: TZState): Integer;
function InflateReset(var Z: TZState): Integer;
function Inflate(var Z: TZState; F: Integer): Integer;
function InflateSetDictionary(var Z: TZState; Dictionary: PByte; DictLength: Cardinal): Integer;
function InflateSync(var Z: TZState): Integer;
function IsInflateSyncPoint(var Z: TZState): Integer;

//----------------------------------------------------------------------------------------------------------------------

implementation

uses
  SysUtils;

const
  // Adler checksum
  Base = Cardinal(65521);       // largest prime smaller than 65536 
  NMAX = 3854;                  // Code with signed 32 bit integer
  
type
  LH = record
    L, H: Word;
  end;

//----------------------------------------------------------------------------------------------------------------------

function zError(Error: Integer): String;

begin
  Result := ErrorMessages[Z_NEED_DICT - Error];
end;

//----------------------------------------------------------------------------------------------------------------------

function Adler32(Adler: Cardinal; Buffer: PByte; Len: Cardinal): Cardinal;

var
  s1, s2: Cardinal;
  K: Integer;

begin
  s1 := Adler and $FFFF;
  s2 := (Adler shr 16) and $FFFF;

  if Buffer = nil then Result := 1
                  else
  begin                                             
    while Len > 0 do
    begin
      if Len < NMAX then K := Len
                    else K := NMAX;
      Dec(Len, K);
      while K > 0 do
      begin
        Inc(s1, Buffer^);
        Inc(s2, s1);                      
        Inc(Buffer);
        Dec(K);
      end;
      s1 := s1 mod Base;
      s2 := s2 mod Base;
    end;
    Result := (s2 shl 16) or s1;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

var
  // used to calculate the running CRC of a bunch of bytes,
  // this table is dynamically created in order to save space if never needed
  CRCTable: array of Cardinal;

procedure MakeCRCTable;

// creates the CRC table when it is needed the first time

var
  C: Cardinal;
  N, K : Integer;
  Poly: Cardinal; // polynomial exclusive-or pattern

const
 // terms of polynomial defining this CRC (except x^32)
 P: array [0..13] of Byte = (0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26);

begin
  // make exclusive-or pattern from polynomial ($EDB88320)
  SetLength(CRCTable, 256);
  Poly := 0;
  for N := 0 to SizeOf(P) - 1 do
    Poly := Poly or (1 shl (31 - P[N]));

  for N := 0 to 255 do
  begin
    C := N;
    for K := 0 to 7 do
    begin
      if (C and 1) <> 0 then C := Poly xor (C shr 1)
                        else C := C shr 1;
    end;
    CRCTable[N] := C;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function CRC32(CRC: Cardinal; Buffer: PByte; Len: Cardinal): Cardinal;

// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
//
// Polynomials over GF(2) are represented in binary, one bit per coefficient,
// with the lowest powers in the most significant bit.  Then adding polynomials
// is just exclusive-or, and multiplying a polynomial by x is a right shift by
// one.  If we call the above polynomial p, and represent a byte as the
// polynomial q, also with the lowest power in the most significant bit (so the
// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
// where a mod b means the remainder after dividing a by b.
//
// This calculation is done using the shift-register method of multiplying and
// taking the remainder.  The register is initialized to zero, and for each
// incoming bit, x^32 is added mod p to the register if the bit is a one (where
// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
// x (which is shifting right by one and adding x^32 mod p if the bit shifted
// out is a one).  We start with the highest power (least significant bit) of
// q and repeat for all eight bits of q.
//
// The table is simply the CRC of all possible eight bit values.  This is all
// the information needed to generate CRC's on data a byte at a time for all
// combinations of CRC register values and incoming bytes.

begin
  if Buffer = nil then Result := 0
                  else
  begin
    if CRCTable = nil then MakeCRCTable;

    CRC := CRC xor $FFFFFFFF;
    while Len >= 8 do
    begin
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);
      CRC := CRCTable[Byte(CRC) xor Buffer^] xor (CRC shr 8);
      Inc(Buffer);

      Dec(Len, 8);
    end;

    while Len > 0 do
    begin
      CRC := CRCTable[(CRC xor Buffer^) and $FF] xor (CRC shr 8);
      Inc(Buffer);
      Dec(Len);
    end;
    Result := CRC xor $FFFFFFFF;
  end;
end;

//----------------- Huffmann trees -------------------------------------------------------------------------------------

const
  DIST_CODE_LEN = 512; // see definition of array dist_code below

  // The static literal tree. Since the bit lengths are imposed, there is no need for the L_CODES Extra codes used
  // during heap construction. However the codes 286 and 287 are needed to build a canonical tree (see TreeInit below).
  StaticLiteralTree: array[0..L_CODES + 1] of TTreeEntry = (
    (fc: (Frequency:  12); dl: (Len: 8)), (fc: (Frequency: 140); dl: (Len: 8)), (fc: (Frequency:  76); dl: (Len: 8)),
    (fc: (Frequency: 204); dl: (Len: 8)), (fc: (Frequency:  44); dl: (Len: 8)), (fc: (Frequency: 172); dl: (Len: 8)),
    (fc: (Frequency: 108); dl: (Len: 8)), (fc: (Frequency: 236); dl: (Len: 8)), (fc: (Frequency:  28); dl: (Len: 8)),
    (fc: (Frequency: 156); dl: (Len: 8)), (fc: (Frequency:  92); dl: (Len: 8)), (fc: (Frequency: 220); dl: (Len: 8)),
    (fc: (Frequency:  60); dl: (Len: 8)), (fc: (Frequency: 188); dl: (Len: 8)), (fc: (Frequency: 124); dl: (Len: 8)),
    (fc: (Frequency: 252); dl: (Len: 8)), (fc: (Frequency:   2); dl: (Len: 8)), (fc: (Frequency: 130); dl: (Len: 8)),
    (fc: (Frequency:  66); dl: (Len: 8)), (fc: (Frequency: 194); dl: (Len: 8)), (fc: (Frequency:  34); dl: (Len: 8)),
    (fc: (Frequency: 162); dl: (Len: 8)), (fc: (Frequency:  98); dl: (Len: 8)), (fc: (Frequency: 226); dl: (Len: 8)),
    (fc: (Frequency:  18); dl: (Len: 8)), (fc: (Frequency: 146); dl: (Len: 8)), (fc: (Frequency:  82); dl: (Len: 8)),
    (fc: (Frequency: 210); dl: (Len: 8)), (fc: (Frequency:  50); dl: (Len: 8)), (fc: (Frequency: 178); dl: (Len: 8)),
    (fc: (Frequency: 114); dl: (Len: 8)), (fc: (Frequency: 242); dl: (Len: 8)), (fc: (Frequency:  10); dl: (Len: 8)),
    (fc: (Frequency: 138); dl: (Len: 8)), (fc: (Frequency:  74); dl: (Len: 8)), (fc: (Frequency: 202); dl: (Len: 8)),
    (fc: (Frequency:  42); dl: (Len: 8)), (fc: (Frequency: 170); dl: (Len: 8)), (fc: (Frequency: 106); dl: (Len: 8)),
    (fc: (Frequency: 234); dl: (Len: 8)), (fc: (Frequency:  26); dl: (Len: 8)), (fc: (Frequency: 154); dl: (Len: 8)),
    (fc: (Frequency:  90); dl: (Len: 8)), (fc: (Frequency: 218); dl: (Len: 8)), (fc: (Frequency:  58); dl: (Len: 8)),
    (fc: (Frequency: 186); dl: (Len: 8)), (fc: (Frequency: 122); dl: (Len: 8)), (fc: (Frequency: 250); dl: (Len: 8)),
    (fc: (Frequency:   6); dl: (Len: 8)), (fc: (Frequency: 134); dl: (Len: 8)), (fc: (Frequency:  70); dl: (Len: 8)),
    (fc: (Frequency: 198); dl: (Len: 8)), (fc: (Frequency:  38); dl: (Len: 8)), (fc: (Frequency: 166); dl: (Len: 8)),
    (fc: (Frequency: 102); dl: (Len: 8)), (fc: (Frequency: 230); dl: (Len: 8)), (fc: (Frequency:  22); dl: (Len: 8)),
    (fc: (Frequency: 150); dl: (Len: 8)), (fc: (Frequency:  86); dl: (Len: 8)), (fc: (Frequency: 214); dl: (Len: 8)),
    (fc: (Frequency:  54); dl: (Len: 8)), (fc: (Frequency: 182); dl: (Len: 8)), (fc: (Frequency: 118); dl: (Len: 8)),
    (fc: (Frequency: 246); dl: (Len: 8)), (fc: (Frequency:  14); dl: (Len: 8)), (fc: (Frequency: 142); dl: (Len: 8)),
    (fc: (Frequency:  78); dl: (Len: 8)), (fc: (Frequency: 206); dl: (Len: 8)), (fc: (Frequency:  46); dl: (Len: 8)),
    (fc: (Frequency: 174); dl: (Len: 8)), (fc: (Frequency: 110); dl: (Len: 8)), (fc: (Frequency: 238); dl: (Len: 8)),
    (fc: (Frequency:  30); dl: (Len: 8)), (fc: (Frequency: 158); dl: (Len: 8)), (fc: (Frequency:  94); dl: (Len: 8)),
    (fc: (Frequency: 222); dl: (Len: 8)), (fc: (Frequency:  62); dl: (Len: 8)), (fc: (Frequency: 190); dl: (Len: 8)),
    (fc: (Frequency: 126); dl: (Len: 8)), (fc: (Frequency: 254); dl: (Len: 8)), (fc: (Frequency:   1); dl: (Len: 8)),
    (fc: (Frequency: 129); dl: (Len: 8)), (fc: (Frequency:  65); dl: (Len: 8)), (fc: (Frequency: 193); dl: (Len: 8)),
    (fc: (Frequency:  33); dl: (Len: 8)), (fc: (Frequency: 161); dl: (Len: 8)), (fc: (Frequency:  97); dl: (Len: 8)),
    (fc: (Frequency: 225); dl: (Len: 8)), (fc: (Frequency:  17); dl: (Len: 8)), (fc: (Frequency: 145); dl: (Len: 8)),
    (fc: (Frequency:  81); dl: (Len: 8)), (fc: (Frequency: 209); dl: (Len: 8)), (fc: (Frequency:  49); dl: (Len: 8)),
    (fc: (Frequency: 177); dl: (Len: 8)), (fc: (Frequency: 113); dl: (Len: 8)), (fc: (Frequency: 241); dl: (Len: 8)),
    (fc: (Frequency:   9); dl: (Len: 8)), (fc: (Frequency: 137); dl: (Len: 8)), (fc: (Frequency:  73); dl: (Len: 8)),
    (fc: (Frequency: 201); dl: (Len: 8)), (fc: (Frequency:  41); dl: (Len: 8)), (fc: (Frequency: 169); dl: (Len: 8)),
    (fc: (Frequency: 105); dl: (Len: 8)), (fc: (Frequency: 233); dl: (Len: 8)), (fc: (Frequency:  25); dl: (Len: 8)),
    (fc: (Frequency: 153); dl: (Len: 8)), (fc: (Frequency:  89); dl: (Len: 8)), (fc: (Frequency: 217); dl: (Len: 8)),
    (fc: (Frequency:  57); dl: (Len: 8)), (fc: (Frequency: 185); dl: (Len: 8)), (fc: (Frequency: 121); dl: (Len: 8)),
    (fc: (Frequency: 249); dl: (Len: 8)), (fc: (Frequency:   5); dl: (Len: 8)), (fc: (Frequency: 133); dl: (Len: 8)),
    (fc: (Frequency:  69); dl: (Len: 8)), (fc: (Frequency: 197); dl: (Len: 8)), (fc: (Frequency:  37); dl: (Len: 8)),
    (fc: (Frequency: 165); dl: (Len: 8)), (fc: (Frequency: 101); dl: (Len: 8)), (fc: (Frequency: 229); dl: (Len: 8)),
    (fc: (Frequency:  21); dl: (Len: 8)), (fc: (Frequency: 149); dl: (Len: 8)), (fc: (Frequency:  85); dl: (Len: 8)),
    (fc: (Frequency: 213); dl: (Len: 8)), (fc: (Frequency:  53); dl: (Len: 8)), (fc: (Frequency: 181); dl: (Len: 8)),
    (fc: (Frequency: 117); dl: (Len: 8)), (fc: (Frequency: 245); dl: (Len: 8)), (fc: (Frequency:  13); dl: (Len: 8)),
    (fc: (Frequency: 141); dl: (Len: 8)), (fc: (Frequency:  77); dl: (Len: 8)), (fc: (Frequency: 205); dl: (Len: 8)),
    (fc: (Frequency:  45); dl: (Len: 8)), (fc: (Frequency: 173); dl: (Len: 8)), (fc: (Frequency: 109); dl: (Len: 8)),
    (fc: (Frequency: 237); dl: (Len: 8)), (fc: (Frequency:  29); dl: (Len: 8)), (fc: (Frequency: 157); dl: (Len: 8)),
    (fc: (Frequency:  93); dl: (Len: 8)), (fc: (Frequency: 221); dl: (Len: 8)), (fc: (Frequency:  61); dl: (Len: 8)),
    (fc: (Frequency: 189); dl: (Len: 8)), (fc: (Frequency: 125); dl: (Len: 8)), (fc: (Frequency: 253); dl: (Len: 8)),
    (fc: (Frequency:  19); dl: (Len: 9)), (fc: (Frequency: 275); dl: (Len: 9)), (fc: (Frequency: 147); dl: (Len: 9)),
    (fc: (Frequency: 403); dl: (Len: 9)), (fc: (Frequency:  83); dl: (Len: 9)), (fc: (Frequency: 339); dl: (Len: 9)),
    (fc: (Frequency: 211); dl: (Len: 9)), (fc: (Frequency: 467); dl: (Len: 9)), (fc: (Frequency:  51); dl: (Len: 9)),
    (fc: (Frequency: 307); dl: (Len: 9)), (fc: (Frequency: 179); dl: (Len: 9)), (fc: (Frequency: 435); dl: (Len: 9)),
    (fc: (Frequency: 115); dl: (Len: 9)), (fc: (Frequency: 371); dl: (Len: 9)), (fc: (Frequency: 243); dl: (Len: 9)),
    (fc: (Frequency: 499); dl: (Len: 9)), (fc: (Frequency:  11); dl: (Len: 9)), (fc: (Frequency: 267); dl: (Len: 9)),
    (fc: (Frequency: 139); dl: (Len: 9)), (fc: (Frequency: 395); dl: (Len: 9)), (fc: (Frequency:  75); dl: (Len: 9)),
    (fc: (Frequency: 331); dl: (Len: 9)), (fc: (Frequency: 203); dl: (Len: 9)), (fc: (Frequency: 459); dl: (Len: 9)),
    (fc: (Frequency:  43); dl: (Len: 9)), (fc: (Frequency: 299); dl: (Len: 9)), (fc: (Frequency: 171); dl: (Len: 9)),
    (fc: (Frequency: 427); dl: (Len: 9)), (fc: (Frequency: 107); dl: (Len: 9)), (fc: (Frequency: 363); dl: (Len: 9)),
    (fc: (Frequency: 235); dl: (Len: 9)), (fc: (Frequency: 491); dl: (Len: 9)), (fc: (Frequency:  27); dl: (Len: 9)),
    (fc: (Frequency: 283); dl: (Len: 9)), (fc: (Frequency: 155); dl: (Len: 9)), (fc: (Frequency: 411); dl: (Len: 9)),
    (fc: (Frequency:  91); dl: (Len: 9)), (fc: (Frequency: 347); dl: (Len: 9)), (fc: (Frequency: 219); dl: (Len: 9)),
    (fc: (Frequency: 475); dl: (Len: 9)), (fc: (Frequency:  59); dl: (Len: 9)), (fc: (Frequency: 315); dl: (Len: 9)),
    (fc: (Frequency: 187); dl: (Len: 9)), (fc: (Frequency: 443); dl: (Len: 9)), (fc: (Frequency: 123); dl: (Len: 9)),
    (fc: (Frequency: 379); dl: (Len: 9)), (fc: (Frequency: 251); dl: (Len: 9)), (fc: (Frequency: 507); dl: (Len: 9)),
    (fc: (Frequency:   7); dl: (Len: 9)), (fc: (Frequency: 263); dl: (Len: 9)), (fc: (Frequency: 135); dl: (Len: 9)),
    (fc: (Frequency: 391); dl: (Len: 9)), (fc: (Frequency:  71); dl: (Len: 9)), (fc: (Frequency: 327); dl: (Len: 9)),
    (fc: (Frequency: 199); dl: (Len: 9)), (fc: (Frequency: 455); dl: (Len: 9)), (fc: (Frequency:  39); dl: (Len: 9)),
    (fc: (Frequency: 295); dl: (Len: 9)), (fc: (Frequency: 167); dl: (Len: 9)), (fc: (Frequency: 423); dl: (Len: 9)),
    (fc: (Frequency: 103); dl: (Len: 9)), (fc: (Frequency: 359); dl: (Len: 9)), (fc: (Frequency: 231); dl: (Len: 9)),
    (fc: (Frequency: 487); dl: (Len: 9)), (fc: (Frequency:  23); dl: (Len: 9)), (fc: (Frequency: 279); dl: (Len: 9)),
    (fc: (Frequency: 151); dl: (Len: 9)), (fc: (Frequency: 407); dl: (Len: 9)), (fc: (Frequency:  87); dl: (Len: 9)),
    (fc: (Frequency: 343); dl: (Len: 9)), (fc: (Frequency: 215); dl: (Len: 9)), (fc: (Frequency: 471); dl: (Len: 9)),
    (fc: (Frequency:  55); dl: (Len: 9)), (fc: (Frequency: 311); dl: (Len: 9)), (fc: (Frequency: 183); dl: (Len: 9)),
    (fc: (Frequency: 439); dl: (Len: 9)), (fc: (Frequency: 119); dl: (Len: 9)), (fc: (Frequency: 375); dl: (Len: 9)),
    (fc: (Frequency: 247); dl: (Len: 9)), (fc: (Frequency: 503); dl: (Len: 9)), (fc: (Frequency:  15); dl: (Len: 9)),
    (fc: (Frequency: 271); dl: (Len: 9)), (fc: (Frequency: 143); dl: (Len: 9)), (fc: (Frequency: 399); dl: (Len: 9)),
    (fc: (Frequency:  79); dl: (Len: 9)), (fc: (Frequency: 335); dl: (Len: 9)), (fc: (Frequency: 207); dl: (Len: 9)),
    (fc: (Frequency: 463); dl: (Len: 9)), (fc: (Frequency:  47); dl: (Len: 9)), (fc: (Frequency: 303); dl: (Len: 9)),
    (fc: (Frequency: 175); dl: (Len: 9)), (fc: (Frequency: 431); dl: (Len: 9)), (fc: (Frequency: 111); dl: (Len: 9)),
    (fc: (Frequency: 367); dl: (Len: 9)), (fc: (Frequency: 239); dl: (Len: 9)), (fc: (Frequency: 495); dl: (Len: 9)),
    (fc: (Frequency:  31); dl: (Len: 9)), (fc: (Frequency: 287); dl: (Len: 9)), (fc: (Frequency: 159); dl: (Len: 9)),
    (fc: (Frequency: 415); dl: (Len: 9)), (fc: (Frequency:  95); dl: (Len: 9)), (fc: (Frequency: 351); dl: (Len: 9)),
    (fc: (Frequency: 223); dl: (Len: 9)), (fc: (Frequency: 479); dl: (Len: 9)), (fc: (Frequency:  63); dl: (Len: 9)),
    (fc: (Frequency: 319); dl: (Len: 9)), (fc: (Frequency: 191); dl: (Len: 9)), (fc: (Frequency: 447); dl: (Len: 9)),
    (fc: (Frequency: 127); dl: (Len: 9)), (fc: (Frequency: 383); dl: (Len: 9)), (fc: (Frequency: 255); dl: (Len: 9)),
    (fc: (Frequency: 511); dl: (Len: 9)), (fc: (Frequency:   0); dl: (Len: 7)), (fc: (Frequency:  64); dl: (Len: 7)),
    (fc: (Frequency:  32); dl: (Len: 7)), (fc: (Frequency:  96); dl: (Len: 7)), (fc: (Frequency:  16); dl: (Len: 7)),
    (fc: (Frequency:  80); dl: (Len: 7)), (fc: (Frequency:  48); dl: (Len: 7)), (fc: (Frequency: 112); dl: (Len: 7)),
    (fc: (Frequency:   8); dl: (Len: 7)), (fc: (Frequency:  72); dl: (Len: 7)), (fc: (Frequency:  40); dl: (Len: 7)),
    (fc: (Frequency: 104); dl: (Len: 7)), (fc: (Frequency:  24); dl: (Len: 7)), (fc: (Frequency:  88); dl: (Len: 7)),
    (fc: (Frequency:  56); dl: (Len: 7)), (fc: (Frequency: 120); dl: (Len: 7)), (fc: (Frequency:   4); dl: (Len: 7)),
    (fc: (Frequency:  68); dl: (Len: 7)), (fc: (Frequency:  36); dl: (Len: 7)), (fc: (Frequency: 100); dl: (Len: 7)),
    (fc: (Frequency:  20); dl: (Len: 7)), (fc: (Frequency:  84); dl: (Len: 7)), (fc: (Frequency:  52); dl: (Len: 7)),
    (fc: (Frequency: 116); dl: (Len: 7)), (fc: (Frequency:   3); dl: (Len: 8)), (fc: (Frequency: 131); dl: (Len: 8)),
    (fc: (Frequency:  67); dl: (Len: 8)), (fc: (Frequency: 195); dl: (Len: 8)), (fc: (Frequency:  35); dl: (Len: 8)),
    (fc: (Frequency: 163); dl: (Len: 8)), (fc: (Frequency:  99); dl: (Len: 8)), (fc: (Frequency: 227); dl: (Len: 8))
  );

  // The static distance tree. (Actually a trivial tree since all lens use 5 Bits.)
  StaticDescriptorTree: array[0..D_CODES - 1] of TTreeEntry = (
    (fc: (Frequency:  0); dl: (Len: 5)), (fc: (Frequency: 16); dl: (Len: 5)), (fc: (Frequency:  8); dl: (Len: 5)),
    (fc: (Frequency: 24); dl: (Len: 5)), (fc: (Frequency:  4); dl: (Len: 5)), (fc: (Frequency: 20); dl: (Len: 5)),
    (fc: (Frequency: 12); dl: (Len: 5)), (fc: (Frequency: 28); dl: (Len: 5)), (fc: (Frequency:  2); dl: (Len: 5)),
    (fc: (Frequency: 18); dl: (Len: 5)), (fc: (Frequency: 10); dl: (Len: 5)), (fc: (Frequency: 26); dl: (Len: 5)),
    (fc: (Frequency:  6); dl: (Len: 5)), (fc: (Frequency: 22); dl: (Len: 5)), (fc: (Frequency: 14); dl: (Len: 5)),
    (fc: (Frequency: 30); dl: (Len: 5)), (fc: (Frequency:  1); dl: (Len: 5)), (fc: (Frequency: 17); dl: (Len: 5)),
    (fc: (Frequency:  9); dl: (Len: 5)), (fc: (Frequency: 25); dl: (Len: 5)), (fc: (Frequency:  5); dl: (Len: 5)),
    (fc: (Frequency: 21); dl: (Len: 5)), (fc: (Frequency: 13); dl: (Len: 5)), (fc: (Frequency: 29); dl: (Len: 5)),
    (fc: (Frequency:  3); dl: (Len: 5)), (fc: (Frequency: 19); dl: (Len: 5)), (fc: (Frequency: 11); dl: (Len: 5)),
    (fc: (Frequency: 27); dl: (Len: 5)), (fc: (Frequency:  7); dl: (Len: 5)), (fc: (Frequency: 23); dl: (Len: 5))
  );

  // Distance codes. The first 256 values correspond to the distances 3 .. 258, the last 256 values correspond to the
  // top 8 Bits of the 15 bit distances.
  DistanceCode: array[0..DIST_CODE_LEN - 1] of Byte = (
     0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
     8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
    10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
    11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
    12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
    13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
    13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
    14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
    15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
    18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
    23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
    24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
    26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
    26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
    27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
    27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
    28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
    28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
    28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
    29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
    29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
    29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  );

  // length code for each normalized match length (0 = MIN_MATCH)
  LengthCode: array[0..MAX_MATCH - MIN_MATCH] of Byte = (
     0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
    13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
    17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
    19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
    21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
    22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
    23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
    24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
    25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
    25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
    26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
    26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
    27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  );

  // first normalized length for each code (0 = MIN_MATCH) 
  BaseLength: array[0..LENGTH_CODES - 1] of Integer = (
    0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
    64, 80, 96, 112, 128, 160, 192, 224, 0
  );

  // first normalized distance for each code (0 = distance of 1)
  BaseDistance: array[0..D_CODES - 1] of Integer = (
       0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
      32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
    1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
  );

  MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  MAX_BL_BITS = 7;              // bit length codes must not exceed MAX_BL_BITS bits
  END_BLOCK = 256;              // end of block literal code
  REP_3_6 = 16;                 // repeat previous bit length 3-6 times (2 Bits of repeat count)
  REPZ_3_10 = 17;               // repeat a zero length 3-10 times  (3 Bits of repeat count)
  REPZ_11_138 = 18;             // repeat a zero length 11-138 times  (7 Bits of repeat count)

  // extra bits for each length code 
  ExtraLengthBits: array[0..LENGTH_CODES - 1] of Integer = (
    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
  );

  // extra bits for each distance code 
  ExtraDistanceBits: array[0..D_CODES-1] of Integer = (
    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
  );

  // extra bits for each bit length code
  ExtraBitLengthBits: array[0..BL_CODES - 1] of Integer = (
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7
  );

  // The lengths of the bit length codes are sent in order of decreasing probability,
  // to avoid transmitting the lengths for unused bit length codes.
  BitLengthOrder: array[0..BL_CODES - 1] of Byte = (
    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  );

  // Number of bits used within BitsBuffer. (BitsBuffer might be implemented on more than 16 bits on some systems.)
  BufferSize = 16;

  StaticLiteralDescriptor: TStaticTreeDescriptor = (
    StaticTree: @StaticLiteralTree;  // pointer to array of TTreeEntry
    ExtraBits: @ExtraLengthBits;     // pointer to array of integer
    ExtraBase: LITERALS + 1;
    Elements: L_CODES;
    MaxLength: MAX_BITS
  );

  StaticDistanceDescriptor: TStaticTreeDescriptor = (
    StaticTree: @StaticDescriptorTree;
    ExtraBits: @ExtraDistanceBits;
    ExtraBase: 0;
    Elements: D_CODES;
    MaxLength: MAX_BITS
  );

  StaticBitLengthDescriptor: TStaticTreeDescriptor = (
    StaticTree: nil;
    ExtraBits: @ExtraBitLengthBits;
    ExtraBase: 0;
    Elements: BL_CODES;
    MaxLength: MAX_BL_BITS
  );

  SMALLEST = 1; // index within the heap array of least frequent node in the Huffman tree

//----------------------------------------------------------------------------------------------------------------------

procedure SendBits(var S: TDeflateState; Value: Word; Length: Integer);

// Value contains what is to be sent
// Length is the number of bits to send

begin
  // If there's not enough room in BitsBuffer use (valid) bits from BitsBuffer and
  // (16 - ValidBits) bits from Value, leaving (width - (16 - ValidBits)) unused bits in Value.
  {$ifopt Q+} {$Q-} {$define OverflowCheck} {$endif}
  {$ifopt R+} {$R-} {$define RangeCheck} {$endif}
  if (S.ValidBits > Integer(BufferSize) - Length) then
  begin
    S.BitsBuffer := S.BitsBuffer or (Value shl S.ValidBits);
    S.PendingBuffer[S.Pending] := S.BitsBuffer and $FF;
    Inc(S.Pending);
    S.PendingBuffer[S.Pending] := S.BitsBuffer shr 8;
    Inc(S.Pending);

    S.BitsBuffer := Value shr (BufferSize - S.ValidBits);
    Inc(S.ValidBits, Length - BufferSize);
  end
  else
  begin
    S.BitsBuffer := S.BitsBuffer or (Value shl S.ValidBits);
    Inc(S.ValidBits, Length);
  end;
  {$ifdef OverflowCheck} {$Q+} {$undef OverflowCheck} {$endif}
  {$ifdef RangeCheck} {$R+} {$undef RangeCheck} {$endif}
end;

//----------------------------------------------------------------------------------------------------------------------

function BitReverse(Code: Word; Len: Integer): Word;

// Reverses the first Len bits of Code, using straightforward code (a faster
// imMethod would use a table)

begin
  Result := 0;
  repeat
    Result := Result or (Code and 1);
    Code := Code shr 1;
    Result := Result shl 1;
    Dec(Len);
  until Len <= 0;
  Result := Result shr 1;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure GenerateCodes(Tree: PTree; MaxCode: Integer; const BitLengthCounts: array of Word);

// Generates the codes for a given tree and bit counts (which need not be optimal).
// The array BitLengthCounts contains the bit length statistics for the given tree and the field Len is set for all
// Tree elements. MaxCode is the largest code with non zero frequency and BitLengthCounts are the number of codes at
// each bit length.
// On exit the field code is set for all tree elements of non zero code length.

var
  NextCode: array[0..MAX_BITS] of Word; // next code value for each bit length
  Code: Word;      // running code value
  Bits: Integer;   // bit Index
  N: Integer;      // code Index
  Len: Integer;

begin
  Code := 0;

  // The distribution counts are first used to generate the code values without bit reversal.
  for Bits := 1 to MAX_BITS do
  begin
    Code := (Code + BitLengthCounts[Bits - 1]) shl 1;
    NextCode[Bits] := Code;
  end;

  // Check that the bit counts in BitLengthCounts are consistent. The last code must be all ones.
  for N := 0 to MaxCode do
  begin
    Len := Tree[N].dl.Len;
    if Len = 0 then Continue;
    Tree[N].fc.Code := BitReverse(NextCode[Len], Len);
    Inc(NextCode[Len]);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure InitializeBlock(var S: TDeflateState);

var
  N: Integer;  

begin
  // initialize the trees 
  for N := 0 to L_CODES - 1 do S.LiteralTree[N].fc.Frequency := 0;
  for N := 0 to D_CODES - 1 do S.DistanceTree[N].fc.Frequency := 0;
  for N := 0 to BL_CODES - 1 do S.BitLengthTree[N].fc.Frequency := 0;

  S.LiteralTree[END_BLOCK].fc.Frequency := 1;
  S.StaticLength := 0;
  S.OptimalLength := 0;
  S.Matches := 0;
  S.LastLiteral := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TreeInit(var S: TDeflateState);

// initializes the tree data structures for a new zlib stream

begin
  S.CompressedLength := 0;

  S.LiteralDescriptor.DynamicTree := @S.LiteralTree;
  S.LiteralDescriptor.StaticDescriptor := @StaticLiteralDescriptor;

  S.DistanceDescriptor.DynamicTree := @S.DistanceTree;
  S.DistanceDescriptor.StaticDescriptor := @StaticDistanceDescriptor;

  S.BitLengthDescriptor.DynamicTree := @S.BitLengthTree;
  S.BitLengthDescriptor.StaticDescriptor := @StaticBitLengthDescriptor;

  S.BitsBuffer := 0;
  S.ValidBits := 0;
  S.LastEOBLength := 8; // enough Lookahead for Inflate 
  // initialize the first block of the first file 
  InitializeBlock(S);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure RestoreHeap(var S: TDeflateState; const Tree: TTree; K: Integer);

// Restores the heap property by moving down tree starting at node K,
// exchanging a Node with the smallest of its two sons if necessary, stopping
// when the heap property is re-established (each father smaller than its two sons).

var
  V, J: Integer;

begin
  V := S.Heap[K];
  J := K shl 1;  // left son of K
  while J <= S.HeapLength do
  begin
    // set J to the smallest of the two sons:
    if (J < S.HeapLength) and
       ((Tree[S.Heap[J + 1]].fc.Frequency < Tree[S.Heap[J]].fc.Frequency) or
        ((Tree[S.Heap[J + 1]].fc.Frequency = Tree[S.Heap[J]].fc.Frequency) and
         (S.Depth[S.Heap[J + 1]] <= S.Depth[S.Heap[J]]))) then Inc(J);

    // exit if V is smaller than both sons
    if ((Tree[V].fc.Frequency < Tree[S.Heap[J]].fc.Frequency) or
       ((Tree[V].fc.Frequency = Tree[S.Heap[J]].fc.Frequency) and
        (S.Depth[V] <= S.Depth[S.Heap[J]]))) then Break;

    // exchange V with the smallest son
    S.Heap[K] := S.Heap[J];
    K := J;

    // and xontinue down the tree, setting J to the left son of K
    J := J shl 1;
  end;
  S.Heap[K] := V;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure GenerateBitLengths(var S: TDeflateState; var Descriptor: TTreeDescriptor);

// Computes the optimal bit lengths for a tree and update the total bit length for the current block.
// The fields Frequency and dad are set, Heap[HeapMaximum] and above are the tree nodes sorted by increasing frequency.
//
// Result: The field Len is set to the optimal bit length, the array BitLengthCounts contains the frequencies for each
// bit length. The length OptimalLength is updated. StaticLength is also updated if STree is not nil.

var
  Tree: PTree;
  MaxCode: Integer;
  STree: PTree;
  Extra: PIntegerArray;
  Base: Integer;
  MaxLength: Integer;
  H: Integer;          // heap Index
  N, M: Integer;       // iterate over the tree elements
  Bits: Word;          // bit length
  ExtraBits: Integer;
  F: Word;             // frequency
  Overflow: Integer;   // number of elements with bit length too large 
  
begin
  Tree := Descriptor.DynamicTree;
  MaxCode := Descriptor.MaxCode;
  STree := Descriptor.StaticDescriptor.StaticTree;
  Extra := Descriptor.StaticDescriptor.ExtraBits;
  Base := Descriptor.StaticDescriptor.ExtraBase;
  MaxLength := Descriptor.StaticDescriptor.MaxLength;
  Overflow := 0;

  FillChar(S.BitLengthCounts, SizeOf(S.BitLengthCounts), 0);

  // in a first pass, compute the optimal bit lengths (which may overflow in the case of the bit length tree) 
  Tree[S.Heap[S.HeapMaximum]].dl.Len := 0; // root of the heap 

  for H := S.HeapMaximum + 1 to HEAP_SIZE - 1 do
  begin
    N := S.Heap[H];
    Bits := Tree[Tree[N].dl.Dad].dl.Len + 1;
    if Bits > MaxLength then
    begin
      Bits := MaxLength;
      Inc(Overflow);
    end;
    Tree[N].dl.Len := Bits;

    // overwrite Tree[N].dl.Dad which is no longer needed
    if N > MaxCode then Continue; // not a leaf node 

    Inc(S.BitLengthCounts[Bits]);
    ExtraBits := 0;
    if N >= Base then ExtraBits := Extra[N - Base];
    F := Tree[N].fc.Frequency;
    Inc(S.OptimalLength, Integer(F) * (Bits + ExtraBits));
    if Assigned(STree) then Inc(S.StaticLength, Integer(F) * (STree[N].dl.Len + ExtraBits));
  end;
  // This happens for example on obj2 and pic of the Calgary corpus 
  if Overflow = 0 then Exit;

  // find the first bit length which could increase 
  repeat
    Bits := MaxLength - 1;
    while (S.BitLengthCounts[Bits] = 0) do Dec(Bits);
    // move one leaf down the tree
    Dec(S.BitLengthCounts[Bits]);
    // move one overflow item as its brother
    Inc(S.BitLengthCounts[Bits + 1], 2);
    // The brother of the overflow item also moves one step up,
    // but this does not affect BitLengthCounts[MaxLength]
    Dec(S.BitLengthCounts[MaxLength]);
    Dec(Overflow, 2);
  until (Overflow <= 0);

  // Now recompute all bit lengths, scanning in increasing frequency.
  // H is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  // lengths instead of fixing only the wrong ones. This idea is taken
  // from 'ar' written by Haruhiko Okumura.)
  H := HEAP_SIZE;
  for Bits := MaxLength downto 1 do
  begin
    N := S.BitLengthCounts[Bits];
    while (N <> 0) do
    begin
      Dec(H);
      M := S.Heap[H];
      if M > MaxCode then Continue;
      if Tree[M].dl.Len <> Bits then
      begin
        Inc(S.OptimalLength, (Bits - Tree[M].dl.Len) * Tree[M].fc.Frequency);
        Tree[M].dl.Len := Word(Bits);
      end;
      Dec(N);
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure BuildTree(var S: TDeflateState; var Descriptor: TTreeDescriptor);

// Constructs a Huffman tree and assigns the code bit strings and lengths.
// Updates the total bit length for the current block. The field Frequency must be set for all tree elements on entry.
//
// Result: the fields Len and Code are set to the optimal bit length and corresponding Code. The length OptimalLength
// is updated; StaticLength is also updated if STree is not nil. The field MaxCode is set.

var
  Tree: PTree;
  STree: PTree;
  Elements: Integer;
  N, M: Integer;    // iterate over heap elements
  MaxCode: Integer; // largest code with non zero frequency
  Node: Integer;    // new node being created 

begin
  Tree := Descriptor.DynamicTree;
  STree := Descriptor.StaticDescriptor.StaticTree;
  Elements := Descriptor.StaticDescriptor.Elements;
  MaxCode := -1;

  // Construct the initial Heap, with least frequent element in Heap[SMALLEST].
  // The sons of Heap[N] are Heap[2 * N] and Heap[2 * N + 1]. Heap[0] is not used. 
  S.HeapLength := 0;
  S.HeapMaximum := HEAP_SIZE;

  for N := 0 to Elements - 1 do
  begin
    if Tree[N].fc.Frequency = 0 then Tree[N].dl.Len := 0
                                else
    begin
      MaxCode := N;
      Inc(S.HeapLength);
      S.Heap[S.HeapLength] := N;
      S.Depth[N] := 0;
    end;
  end;

  // The pkzip format requires that at least one distance code exists and that at least one bit
  // should be sent even if there is only one possible code. So to avoid special checks later on we force at least
  // two codes of non zero frequency.
  while S.HeapLength < 2 do
  begin
    Inc(S.HeapLength);
    if MaxCode < 2 then
    begin
      Inc(MaxCode);
      S.Heap[S.HeapLength] := MaxCode;
      Node := MaxCode;
    end
    else
    begin
      S.Heap[S.HeapLength] := 0;
      Node := 0;
    end;
    Tree[Node].fc.Frequency := 1;
    S.Depth[Node] := 0;
    Dec(S.OptimalLength);
    if (STree <> nil) then Dec(S.StaticLength, STree[Node].dl.Len);
    // Node is 0 or 1 so it does not have extra bits 
  end;
  Descriptor.MaxCode := MaxCode;

  // The elements Heap[HeapLength / 2 + 1 .. HeapLength] are leaves of the Tree,
  // establish sub-heaps of increasing lengths.
  for N := S.HeapLength div 2 downto 1 do RestoreHeap(S, Tree^, N);

  // construct the Huffman tree by repeatedly combining the least two frequent nodes
  Node := Elements; // next internal node of the tree
  repeat
    N := S.Heap[SMALLEST];
    S.Heap[SMALLEST] := S.Heap[S.HeapLength];
    Dec(S.HeapLength);
    RestoreHeap(S, Tree^, SMALLEST);

    // M := node of next least frequency
    M := S.Heap[SMALLEST];
    Dec(S.HeapMaximum);
    // keep the nodes sorted by frequency
    S.Heap[S.HeapMaximum] := N;
    Dec(S.HeapMaximum);
    S.Heap[S.HeapMaximum] := M;

    // create a new node father of N and M
    Tree[Node].fc.Frequency := Tree[N].fc.Frequency + Tree[M].fc.Frequency;
    // maximum
    if (S.Depth[N] >= S.Depth[M]) then S.Depth[Node] := Byte (S.Depth[N] + 1)
                                  else S.Depth[Node] := Byte (S.Depth[M] + 1);

    Tree[M].dl.Dad := Word(Node);
    Tree[N].dl.Dad := Word(Node);
    // and insert the new node in the heap
    S.Heap[SMALLEST] := Node;
    Inc(Node);
    RestoreHeap(S, Tree^, SMALLEST);
  until S.HeapLength < 2;

  Dec(S.HeapMaximum);
  S.Heap[S.HeapMaximum] := S.Heap[SMALLEST];

  // At this point the fields Frequency and dad are set. We can now generate the bit lengths.
  GenerateBitLengths(S, Descriptor);

  // The field Len is now set, we can generate the bit codes 
  GenerateCodes(Tree, MaxCode, S.BitLengthCounts);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure ScanTree(var S: TDeflateState; var Tree: array of TTreeEntry; MaxCode: Integer);

// Scans a given tree to determine the frequencies of the codes in the bit length tree.
// MaxCode is the tree's largest code of non zero frequency.

var
  N: Integer;           // iterates over all tree elements
  PreviousLen: Integer; // last emitted length
  CurrentLen: Integer;  // Length of current code
  NextLen: Integer;     // length of next code
  Count: Integer;       // repeat count of the current xode
  MaxCount: Integer;    // max repeat count
  MinCount: Integer;    // min repeat count
   
begin
  PreviousLen := -1;
  NextLen := Tree[0].dl.Len;
  Count := 0;
  MaxCount := 7;
  MinCount := 4;

  if NextLen = 0 then
  begin
    MaxCount := 138;
    MinCount := 3;
  end;
  Tree[MaxCode + 1].dl.Len := Word($FFFF); // guard

  for N := 0 to MaxCode do
  begin
    CurrentLen := NextLen;
    NextLen := Tree[N + 1].dl.Len;
    Inc(Count);
    if (Count < MaxCount) and (CurrentLen = NextLen) then Continue
                                                     else
      if (Count < MinCount) then Inc(S.BitLengthTree[CurrentLen].fc.Frequency, Count)
                            else
        if CurrentLen <> 0 then
        begin
          if (CurrentLen <> PreviousLen) then Inc(S.BitLengthTree[CurrentLen].fc.Frequency);
          Inc(S.BitLengthTree[REP_3_6].fc.Frequency);
        end
        else
          if (Count <= 10) then Inc(S.BitLengthTree[REPZ_3_10].fc.Frequency)
                           else Inc(S.BitLengthTree[REPZ_11_138].fc.Frequency);
    Count := 0;
    PreviousLen := CurrentLen;
    if NextLen = 0 then
    begin
      MaxCount := 138;
      MinCount := 3;
    end
    else
      if CurrentLen = NextLen then
      begin
        MaxCount := 6;
        MinCount := 3;
      end
      else
      begin
        MaxCount := 7;
        MinCount := 4;
      end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure SendTree(var S: TDeflateState; const Tree: array of TTreeEntry; MaxCode: Integer);

// Sends the given tree in compressed form using the codes in BitLengthTree. 
// MaxCode is the tree's largest code of non zero frequency.

var
  N: Integer;           // iterates over all tree elements
  PreviousLen: Integer; // last emitted length
  CurrentLen: Integer;  // length of current code
  NextLen: Integer;     // length of next code
  Count: Integer;       // repeat count of the current code
  MaxCount: Integer;    // max repeat count 
  MinCount: Integer;    // min repeat count

begin
  PreviousLen := -1;
  NextLen := Tree[0].dl.Len;
  Count := 0;
  MaxCount := 7;
  MinCount := 4;

  // guard is already set 
  if NextLen = 0 then
  begin
    MaxCount := 138;
    MinCount := 3;
  end;

  for N := 0 to MaxCode do
  begin
    CurrentLen := NextLen;
    NextLen := Tree[N + 1].dl.Len;
    Inc(Count);
    if (Count < MaxCount) and (CurrentLen = NextLen) then Continue
                                                     else
      if Count < MinCount then
      begin
        repeat
          SendBits(S, S.BitLengthTree[CurrentLen].fc.Code, S.BitLengthTree[CurrentLen].dl.Len);
          Dec(Count);
        until (Count = 0);
      end
      else
        if CurrentLen <> 0 then
        begin
          if CurrentLen <> PreviousLen then
          begin
            SendBits(S, S.BitLengthTree[CurrentLen].fc.Code, S.BitLengthTree[CurrentLen].dl.Len);
            Dec(Count);
          end;
          SendBits(S, S.BitLengthTree[REP_3_6].fc.Code, S.BitLengthTree[REP_3_6].dl.Len);
          SendBits(S, Count - 3, 2);
        end
        else
          if Count <= 10 then
          begin
            SendBits(S, S.BitLengthTree[REPZ_3_10].fc.Code, S.BitLengthTree[REPZ_3_10].dl.Len);
            SendBits(S, Count - 3, 3);
          end
          else
          begin
            SendBits(S, S.BitLengthTree[REPZ_11_138].fc.Code, S.BitLengthTree[REPZ_11_138].dl.Len);
            SendBits(S, Count - 11, 7);
          end;
    Count := 0;
    PreviousLen := CurrentLen;
    if NextLen = 0 then
    begin
      MaxCount := 138;
      MinCount := 3;
    end
    else
      if CurrentLen = NextLen then
      begin
        MaxCount := 6;
        MinCount := 3;
      end
      else
      begin
        MaxCount := 7;
        MinCount := 4;
      end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function BuildBitLengthTree(var S: TDeflateState): Integer;

// Constructs the Huffman tree for the bit lengths and returns the Index in BitLengthOrder
// of the last bit length code to send.

begin
  // determine the bit length frequencies for literal and distance trees
  ScanTree(S, S.LiteralTree, S.LiteralDescriptor.MaxCode);
  ScanTree(S, S.DistanceTree, S.DistanceDescriptor.MaxCode);

  // build the bit length tree
  BuildTree(S, S.BitLengthDescriptor);
  // OptimalLength now includes the length of the tree representations, except
  // the lengths of the bit lengths codes and the 5 + 5 + 4 (= 14) bits for the counts.

  // Determine the number of bit length codes to send. The pkzip format requires that at least 4 bit length codes
  // be sent. (appnote.txt says 3 but the actual value used is 4.)
  for Result := BL_CODES - 1 downto 3 do
    if S.BitLengthTree[BitLengthOrder[Result]].dl.Len <> 0 then Break;

  // update OptimalLength to include the bit length tree and counts 
  Inc(S.OptimalLength, 3 * (Result + 1) + 14);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure SendAllTrees(var S: TDeflateState; lcodes, dcodes, blcodes: Integer);

// Sends the header for a block using dynamic Huffman trees: the counts, the
// lengths of the bit length codes, the literal tree and the distance tree.
// lcodes must be >= 257, dcodes >= 1 and blcodes >= 4

var
  Rank: Integer;          

begin
  SendBits(S, lcodes - 257, 5); // not +255 as stated in appnote.txt
  SendBits(S, dcodes - 1,   5);
  SendBits(S, blcodes - 4,  4); // not -3 as stated in appnote.txt

  for Rank := 0 to blcodes - 1 do SendBits(S, S.BitLengthTree[BitLengthOrder[Rank]].dl.Len, 3);
  SendTree(S, S.LiteralTree, lcodes-1);
  SendTree(S, S.DistanceTree, dcodes-1);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure BitsWindup(var S: TDeflateState);

// flushs the bit buffer and aligns the output on a byte boundary

begin
  if S.ValidBits > 8 then
  begin
    S.PendingBuffer[S.Pending] := Byte(S.BitsBuffer and $FF);
    Inc(S.Pending);
    S.PendingBuffer[S.Pending] := Byte(Word(S.BitsBuffer) shr 8);;
    Inc(S.Pending);
  end
  else
    if S.ValidBits > 0 then
    begin
      S.PendingBuffer[S.Pending] := Byte(S.BitsBuffer);
      Inc(S.Pending);
    end;
    
  S.BitsBuffer := 0;
  S.ValidBits := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure CopyBlock(var S: TDeflateState; Buffer: PByte; Len: Cardinal; Header: Boolean);

// copies a stored block, storing first the length and its one's complement if requested
// Buffer contains the input data, Len the buffer length and Header is True if the block Header must be written too.

begin
  BitsWindup(S);        // align on byte boundary
  S.LastEOBLength := 8; // enough lookahead for Inflate

  if Header then
  begin
    S.PendingBuffer[S.Pending] := Byte(Word(Len) and $FF);
    Inc(S.Pending);
    S.PendingBuffer[S.Pending] := Byte(Word(Len) shr 8);
    Inc(S.Pending);
    S.PendingBuffer[S.Pending] := Byte(Word(not Len) and $FF);
    Inc(S.Pending);
    S.PendingBuffer[S.Pending] := Byte(Word(not Len) shr 8);
    Inc(S.Pending);
  end;

  while Len > 0 do
  begin
    Dec(Len);
    S.PendingBuffer[S.Pending] := Buffer^;
    Inc(Buffer);
    Inc(S.Pending);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TreeStroredBlock(var S: TDeflateState; Buffer: PByte; StoredLength: Integer; EOF: Boolean);

// sends a stored block
// Buffer contains the input data, Len the buffer length and EOF is True if this is the last block for a file.

begin
  SendBits(S, (STORED_BLOCK shl 1) + Ord(EOF), 3);  // send block type 
  S.CompressedLength := (S.CompressedLength + 10) and Integer(not 7);
  Inc(S.CompressedLength, (StoredLength + 4) shl 3);

  // copy with header
  CopyBlock(S, Buffer, Cardinal(StoredLength), True);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure BitsFlush(var S: TDeflateState);

// flushs the bit buffer, keeping at most 7 bits in it

begin
  if S.ValidBits = 16 then
  begin
    S.PendingBuffer[S.Pending] := Byte(S.BitsBuffer and $FFf);
    Inc(S.Pending);
    S.PendingBuffer[S.Pending] := Byte(Word(S.BitsBuffer) shr 8);
    Inc(S.Pending);

    S.BitsBuffer := 0;
    S.ValidBits := 0;
  end
  else
   if S.ValidBits >= 8 then
   begin
     S.PendingBuffer[S.Pending] := Byte(S.BitsBuffer);
     Inc(S.Pending);

     S.BitsBuffer := S.BitsBuffer shr 8;
     Dec(S.ValidBits, 8);
   end;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure TreeAlign(var S: TDeflateState);

// Sends one empty static block to give enough lookahead for Inflate. This takes 10 Bits, of which 7 may remain
// in the bit buffer. The current Inflate code requires 9 Bits of lookahead. if the last two codes for the previous
// block (real code plus EOB) were coded on 5 Bits or less, Inflate may have only 5 + 3 Bits of lookahead to decode the 
// last real code. In this case we send two empty static blocks instead of one. (There are no problems if the previous
// block is stored or fixed.) To simplify the code, we assume the worst case of last real code encoded on one bit only.

begin
  SendBits(S, STATIC_TREES shl 1, 3);
  SendBits(S, StaticLiteralTree[END_BLOCK].fc.Code, StaticLiteralTree[END_BLOCK].dl.Len);
  Inc(S.CompressedLength, 10); // 3 for block type, 7 for EOB 
  BitsFlush(S);
  // Of the 10 Bits for the empty block, we have already sent
  // (10 - ValidBits) bits. The lookahead for the last real code (before
  // the EOB of the previous block) was thus at least one plus the length
  // of the EOB plus what we have just sent of the empty static block.
  if (1 + S.LastEOBLength + 10 - S.ValidBits) < 9 then
  begin
    SendBits(S, STATIC_TREES shl 1, 3);
    SendBits(S, StaticLiteralTree[END_BLOCK].fc.Code, StaticLiteralTree[END_BLOCK].dl.Len);
    Inc(S.CompressedLength, 10);
    BitsFlush(S);
  end;
  S.LastEOBLength := 7;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure SetDataType(var S: TDeflateState);

// Sets the data type to ASCII or BINARY, using a crude approximation. Binary if more than 20% of the bytes are
// <= 6 or >= 128, ASCII otherwise. The fields Frequency of LiteralTree are set and the total of all frequencies does
// not exceed 64K.

var
  N: Integer;
  ASCIIFrequency: Cardinal;
  BinaryFrequency: Cardinal;

begin
  N := 0;
  ASCIIFrequency := 0;
  BinaryFrequency := 0;

  while N < 7 do
  begin
    Inc(BinaryFrequency, S.LiteralTree[N].fc.Frequency);
    Inc(N);
  end;
  while N < 128 do
  begin
    Inc(ASCIIFrequency, S.LiteralTree[N].fc.Frequency);
    Inc(N);
  end;
  while N < LITERALS do
  begin
    Inc(BinaryFrequency, S.LiteralTree[N].fc.Frequency);
    Inc(N);
  end;

  if BinaryFrequency > (ASCIIFrequency shr 2) then S.DataType := Z_BINARY
                                              else S.DataType := Z_ASCII;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure CompressBlock(var S: TDeflateState; const LiteralTree, DistanceTree: array of TTreeEntry);

// sends the block data compressed using the given Huffman trees

var
  Distance: Cardinal; // distance of matched string
  lc: Integer;        // match length or unmatched char (if Distance = 0)
  I: Cardinal;
  Code: Cardinal;     // the code to send
  Extra: Integer;     // number of extra bits to send 

begin
  I := 0;
  if S.LastLiteral <> 0 then
  repeat
    Distance := S.DistanceBuffer[I];
    lc := S.LiteralBuffer[I];
    Inc(I);
    if Distance = 0 then
    begin
      // send a literal byte
      SendBits(S, LiteralTree[lc].fc.Code, LiteralTree[lc].dl.Len);
    end
    else
    begin
      // Here, lc is the match length - MIN_MATCH
      Code := LengthCode[lc];
      // send the length code 
      SendBits(S, LiteralTree[Code + LITERALS + 1].fc.Code, LiteralTree[Code + LITERALS + 1].dl.Len);
      Extra := ExtraLengthBits[Code];
      if Extra <> 0 then
      begin
        Dec(lc, BaseLength[Code]);
        // send the extra length bits
        SendBits(S, lc, Extra);
      end;
      Dec(Distance); // Distance is now the match distance - 1
      if Distance < 256 then Code := DistanceCode[Distance]
                        else Code := DistanceCode[256 + (Distance shr 7)];

      // send the distance code
      SendBits(S, DistanceTree[Code].fc.Code, DistanceTree[Code].dl.Len);
      Extra := ExtraDistanceBits[Code];
      if Extra <> 0 then
      begin
        Dec(Distance, BaseDistance[Code]);
        SendBits(S, Distance, Extra);   // send the extra distance bits
      end;
    end; // literal or match pair? 

    // Check that the overlay between PendingBuffer and DistanceBuffer + LiteralBuffer is ok
  until I >= S.LastLiteral;

  SendBits(S, LiteralTree[END_BLOCK].fc.Code, LiteralTree[END_BLOCK].dl.Len);
  S.LastEOBLength := LiteralTree[END_BLOCK].dl.Len;
end;

//----------------------------------------------------------------------------------------------------------------------

function TreeFlushBlock(var S: TDeflateState; Buffer: PByte; StoredLength: Integer; EOF: Boolean): Integer;

// Determines the best encoding for the current block: dynamic trees, static trees or store, and outputs the encoded
// block. Buffer contains the input block (or nil if too old), StoredLength the length of this block and EOF if this
// is the last block.
// Returns the total compressed length so far.

var
  OptimalByteLength,
  StaticByteLength: Integer; // OptimalLength and StaticLength in bytes
  MacBLIndex: Integer;  // index of last bit length code of non zero frequency 

begin
  MacBLIndex := 0;

  // build the Huffman trees unless a stored block is forced
  if S.Level > 0 then
  begin
    // check if the file is ASCII or binary
    if S.DataType = Z_UNKNOWN then SetDataType(S);

    // construct the literal and distance trees
    // After this, OptimalLength and StaticLength are the total bit lengths of
    // the compressed block data, excluding the tree representations.
    BuildTree(S, S.LiteralDescriptor);
    BuildTree(S, S.DistanceDescriptor);

    // Build the bit length tree for the above two trees and get the index
    // in BitLengthOrder of the last bit length code to send.
    MacBLIndex := BuildBitLengthTree(S);

    // determine the best encoding, compute first the block length in bytes
    OptimalByteLength := (S.OptimalLength + 10) shr 3;
    StaticByteLength := (S.StaticLength + 10) shr 3;
    if StaticByteLength <= OptimalByteLength then OptimalByteLength := StaticByteLength;
  end
  else
  begin
    StaticByteLength := StoredLength + 5;
    OptimalByteLength := StaticByteLength; // force a stored block 
  end;

  // if Iompression failed and this is the first and last block,
  // and if the .zip file can be seeked (to rewrite the local header),
  // the whole file is transformed into a stored file.  
  // (4 are the two words for the lengths) 
  if (StoredLength + 4 <= OptimalByteLength) and Assigned(Buffer) then
  begin
    // The test Buffer <> nil is only necessary if LiteralBufferSize > WSize.
    // Otherwise we can't have processed more than WSize input bytes since
    // the last block dlush, because compression would have been successful.
    // if LiteralBufferSize <= WSize, it is never too late to transform a block into a stored block. 
    TreeStroredBlock(S, Buffer, StoredLength, EOF);
  end
  else
    if StaticByteLength >= 0 then
    begin
      // force static trees 
      SendBits(S, (STATIC_TREES shl 1) + Ord(EOF), 3);
      CompressBlock(S, StaticLiteralTree, StaticDescriptorTree);
      Inc(S.CompressedLength, 3 + S.StaticLength);
    end
    else
    begin
      SendBits(S, (DYN_TREES shl 1) + Ord(EOF), 3);
      SendAllTrees(S, S.LiteralDescriptor.MaxCode + 1, S.DistanceDescriptor.MaxCode + 1, MacBLIndex + 1);
      CompressBlock(S, S.LiteralTree, S.DistanceTree);
      Inc(S.CompressedLength, 3 + S.OptimalLength);
    end;
  InitializeBlock(S);

  if EOF then
  begin
    BitsWindup(S);
    // align on byte boundary
    Inc(S.CompressedLength, 7);
  end;

  Result := S.CompressedLength shr 3;
end;

//----------------------------------------------------------------------------------------------------------------------

function TreeTally(var S: TDeflateState; Distance: Cardinal; lc: Cardinal): Boolean;

// Saves the match info and tallies the frequency counts. Returns True if the current block must be flushed.
// Distance is the distance of the matched string and lc either match length minus MIN_MATCH or the unmatch character
// (if Distance = 0).

var
  Code: Word;

begin
  S.DistanceBuffer[S.LastLiteral] := Word(Distance);
  S.LiteralBuffer[S.LastLiteral] := Byte(lc);
  Inc(S.LastLiteral);
  if (Distance = 0) then
  begin
    // lc is the unmatched char
    Inc(S.LiteralTree[lc].fc.Frequency);
  end
  else
  begin
    Inc(S.Matches);
    // here, lc is the match length - MIN_MATCH
    Dec(Distance);              
    if Distance < 256 then Code := DistanceCode[Distance]
                      else Code := DistanceCode[256 + (Distance shr 7)];
    Inc(S.LiteralTree[LengthCode[lc] + LITERALS + 1].fc.Frequency);
    Inc(S.DistanceTree[Code].fc.Frequency);
  end;

  Result := (S.LastLiteral = S.LiteralBufferSize - 1);
  // We avoid equality with LiteralBufferSize because stored blocks are restricted to 64K - 1 bytes. 
end;

//----------------- deflation support ----------------------------------------------------------------------------------

type
  TBlockState = (
    bsNeedMore,      // block not completed, need more input or more output
    bsBlockDone,     // block flush performed
    bsFinishStarted, // finish started, need only more output at next Deflate
    bsFinishDone     // finish done, accept no more input or output
  );

type // compression function, returns the block state after the call
  TCompressFunction = function(var S: TDeflateState; Flush: Integer): TBlockState;

function DeflateStored(var S: TDeflateState; Flush: Integer): TBlockState; forward;
function DeflateFast(var S: TDeflateState; Flush: Integer): TBlockState; forward;
function DeflateSlow(var S: TDeflateState; Flush: Integer): TBlockState; forward;

const
  ZNIL = 0;                     // Tail of hash chains
  TOO_FAR = 4096;               // matches of length 3 are discarded if their distance exceeds TOO_FAR 

type
  TConfig = record
   GoodLength: Word;            // reduce lazy search above this match length
   MaxLazy: Word;               // do not perform lazy search above this match length
   NiceLength: Word;            // quit search above this match length
   MaxChain: Word;
   Func: TCompressFunction;
  end;

const
  // Values for MaxLazyMatch, GoodMatch and MaxChainLength, depending on the desired pack Level (0..9).
  // The values given below have been tuned to exclude worst case performance for pathological files.
  // Better values may be found for specific files.
  ConfigurationTable: array[0..9] of TConfig = (
    (GoodLength: 0;  MaxLazy: 0;   NiceLength: 0;   MaxChain: 0;    Func: DeflateStored),  // store only
    (GoodLength: 4;  MaxLazy: 4;   NiceLength: 8;   MaxChain: 4;    Func: DeflateFast), // maximum speed
    (GoodLength: 4;  MaxLazy: 5;   NiceLength: 16;  MaxChain: 8;    Func: DeflateFast),
    (GoodLength: 4;  MaxLazy: 6;   NiceLength: 32;  MaxChain: 32;   Func: DeflateFast),
    (GoodLength: 4;  MaxLazy: 4;   NiceLength: 16;  MaxChain: 16;   Func: DeflateSlow),
    (GoodLength: 8;  MaxLazy: 16;  NiceLength: 32;  MaxChain: 32;   Func: DeflateSlow),
    (GoodLength: 8;  MaxLazy: 16;  NiceLength: 128; MaxChain: 128;  Func: DeflateSlow),
    (GoodLength: 8;  MaxLazy: 32;  NiceLength: 128; MaxChain: 256;  Func: DeflateSlow),
    (GoodLength: 32; MaxLazy: 128; NiceLength: 258; MaxChain: 1024; Func: DeflateSlow),
    (GoodLength: 32; MaxLazy: 258; NiceLength: 258; MaxChain: 4096; Func: DeflateSlow)  // maximum compression
  );

// Note: The deflate code requires MaxLazy >= MIN_MATCH and MaxChain >= 4.
//       For DeflateFast (levels <= 3) good is ignored and lazy has a different meaning.

//----------------------------------------------------------------------------------------------------------------------

procedure InsertString(var S: TDeflateState; Str: Cardinal; var MatchHead: Cardinal);

// Inserts Str into the dictionary and sets MatchHead to the previous head of the hash chain (the most recent string
// with same hash key). All calls to to InsertString are made with consecutive input characters and the first MIN_MATCH
// bytes of Str are valid (except for the last MIN_MATCH - 1 bytes of the input file).
// Returns the previous length of the hash chain.

begin
  S.InsertHash := ((S.InsertHash shl S.HashShift) xor (S.Window[(Str) + (MIN_MATCH - 1)])) and S.HashMask;

  MatchHead := S.Head[S.InsertHash];
  S.Previous[(Str) and S.WindowMask] := MatchHead;
  S.Head[S.InsertHash] := Word(Str);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure LongestMatchInit(var S: TDeflateState);

// initializes the "longest match" routines for a new zlib stream 

begin
  S.CurrentWindowSize := 2 * S.WindowSize;

  S.Head[S.HashSize - 1] := ZNIL;
  FillChar(S.Head^, (S.HashSize - 1) * SizeOf(S.Head[0]), 0);

  // set the default configuration parameters 
  S.MaxLazyMatch := ConfigurationTable[S.Level].MaxLazy;
  S.GoodMatch := ConfigurationTable[S.Level].GoodLength;
  S.NiceMatch := ConfigurationTable[S.Level].NiceLength;
  S.MaxChainLength := ConfigurationTable[S.Level].MaxChain;

  S.StringStart := 0;
  S.BlockStart := 0;
  S.Lookahead := 0;
  S.PreviousLength := MIN_MATCH - 1;
  S.MatchLength := MIN_MATCH - 1;
  S.MatchAvailable := False;
  S.InsertHash := 0;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateInit2_(var ZState: TZState; Level: Integer; imMethod: Byte; AWindowBits: Integer; MemLevel:
  Integer; Strategy: Integer; const Version: String; StreamSize: Integer): Integer;

// initializes the hash table (Previous[] will be initialized on the fly)

var
  S: PDeflateState;
  NoHeader: Integer;
  Overlay: PWordArray;
  // We overlay PendingBuffer and DistanceBuffer + LiteralBuffer. This works since the average
  // output size for (length, distance) codes is <= 24 Bits.

begin
  NoHeader := 0;
  if (Version  =  '') or (Version[1] <> ZLIB_VERSION[1]) or (StreamSize <> SizeOf(TZState)) then
  begin
    Result := Z_VERSION_ERROR;
    Exit;
  end;

  ZState.Msg := '';
  if Level  =  Z_DEFAULT_COMPRESSION then Level := 6;

  if AWindowBits < 0 then
  begin
    // undocumented feature: suppress zlib header
    NoHeader := 1;
    AWindowBits := -AWindowBits;
  end;
  
  if (MemLevel < 1) or
     (MemLevel > MAX_MEM_LEVEL) or
     (imMethod <> Z_DEFLATED) or
     (AWindowBits < 8) or
     (AWindowBits > 15) or
     (Level < 0) or
     (Level > 9) or
     (Strategy < 0) or
     (Strategy > Z_HUFFMAN_ONLY) then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  try
    S := AllocMem(SizeOf(TDeflateState));
    ZState.State := PInternalState(S);
    S.ZState := @ZState;

    S.NoHeader := NoHeader;
    S.WindowBits := AWindowBits;
    S.WindowSize := 1 shl S.WindowBits;
    S.WindowMask := S.WindowSize - 1;

    S.HashBits := MemLevel + 7;
    S.HashSize := 1 shl S.HashBits;
    S.HashMask := S.HashSize - 1;
    S.HashShift := (S.HashBits + MIN_MATCH - 1) div MIN_MATCH;

    S.Window := AllocMem(S.WindowSize * 2 * SizeOf(Byte));
    S.Previous := AllocMem(S.WindowSize * SizeOf(Word));
    S.Head := AllocMem(S.HashSize * SizeOf(Word));

    S.LiteralBufferSize := 1 shl (MemLevel + 6); // 16K elements by default 

    Overlay := AllocMem(S.LiteralBufferSize * SizeOf(Word) + 2);
    S.PendingBuffer := PByteArray(Overlay);
    S.PendingBufferSize := S.LiteralBufferSize * (SizeOf(Word) + 2);

    S.DistanceBuffer := @Overlay[S.LiteralBufferSize div SizeOf(Word)];
    S.LiteralBuffer := @S.PendingBuffer[(1 + SizeOf(Word)) * S.LiteralBufferSize];

    S.Level := Level;
    S.Strategy := Strategy;
    S.imMethod := imMethod;

    Result := DeflateReset(ZState);
  except
    ZState.Msg := ErrorMessages[ERROR_BASE - Z_MEM_ERROR];
    // free already allocated data on error
    DeflateEnd(ZState);
    raise;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateInit2(var ZState: TZState; Level: Integer; Method: Byte; AWindowBits: Integer; MemLevel: Integer;
  Strategy: Integer): Integer;

// This is another Version of DeflateInit with more compression options. The field
//  NextInput must be initialized before by the caller.
//
// The Method parameter is the compression method. It must be Z_DEFLATED in
// this Version of the library. (Method 9 will allow a 64K history buffer and
// partial block flushes.)
//
// The AWindowBits parameter is the base two logarithm of the window size
// (the size of the history buffer). It should be in the range 8..15 for this
// version of the library (the value 16 will be allowed for method 9). Larger
// values of this parameter result in better compression at the expense of
// memory usage. The default value is 15 if DeflateInit is used instead.
//
// The MemLevel parameter specifies how much memory should be allocated
// for the internal compression State. MemLevel = 1 uses minimum memory but
// is slow and reduces compression ratio; MemLevel = 9 uses maximum memory
// for optimal speed. The default value is 8. 
//
// The strategy parameter is used to tune the compression algorithm. Use the
// Value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
// filter (or predictor), or Z_HUFFMAN_ONLY to force Huffman encoding only (no
// string match). Filtered data consists mostly of small values with a
// somewhat random distribution. In this case, the compression algorithm is
// tuned to compress them better. The effect of Z_FILTERED is to force more
// Huffman coding and less string matching; it is somewhat intermediate
// between Z_DEFAULT and Z_HUFFMAN_ONLY. The strategy parameter only affects
// the compression ratio but not the correctness of the compressed output even
// if it is not set appropriately.
//
// if NextInput is not nil the library will use this buffer to hold also
// some history information; the buffer must either hold the entire input
// data or have at least 1 shl (WindowBits + 1) bytes and be writable. If NextInput
// is nil the library will allocate its own history buffer (and leave NextInput
// nil). NextOutput need not be provided here but must be provided by the
// application for the next call of Deflate.
//
// if the history buffer is provided by the application, NextInput must
// must never be changed by the application since the compressor maintains
// information inside this buffer from call to call; the application
// must provide more input only by increasing AvailableInput. NextInput is always
// reset by the library in this case.
//
// DeflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was
// not enough memory, Z_STREAM_ERROR if a parameter is invalid (such as
// an invalid method). Msg is set to '' if there is no error message.
// DeflateInit2 does not perform any compression: this will be done by
// Deflate. 

begin
  Result := DeflateInit2_(ZState, Level, Method, AWindowBits, MemLevel, Strategy, ZLIB_VERSION, SizeOf(TZState));
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateInit_(ZState: PZState; Level: Integer; const Version: String; StreamSize: Integer): Integer;

// Initializes the internal stream state for compression. 
//
// The compression level must be Z_DEFAULT_COMPRESSION or between 0 and 9:
// 1 gives best speed, 9 gives best compression, 0 gives no compression at
// all (the input data is simply copied a block at a time).
// Z_DEFAULT_COMPRESSION requests a default compromise between speed and
// compression (currently equivalent to Level 6).
//
// DeflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
// enough memory, Z_STREAM_ERROR if Level is not a valid compression level,
// Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
// with the version assumed by the caller (ZLIB_VERSION).
// Msg is set to '' if there is no error message.  DeflateInit does not
// perform any compression, this will be done by Deflate. 

begin
  if ZState = nil then DeflateInit_ := Z_STREAM_ERROR
                  else DeflateInit_ := DeflateInit2_(ZState^, Level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
                                         Z_DEFAULT_STRATEGY, Version, StreamSize);
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateInit(var ZState: TZState; Level: Integer): Integer;

begin
  DeflateInit := DeflateInit2_(ZState, Level, Z_DEFLATED, MAX_WBITS,
         DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY, ZLIB_VERSION, SizeOf(TZState));
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateSetDictionary(var ZState: TZState; Dictionary: PByte; DictLength: Cardinal): Integer;

// Initializes the compression dictionary (history buffer) from the given
// byte sequence without producing any compressed output. This function must
// be called immediately after DeflateInit or DeflateInit2, before any call
// of Deflate. The compressor and decompressor must use exactly the same
// dictionary (see InflateSetDictionary).
//
// The dictionary should consist of strings (byte sequences) that are likely
// to be encountered later in the data to be compressed, with the most commonly
// used strings preferably put towards the end of the dictionary. Using a
// dictionary is most useful when the data to be compressed is short and
// can be predicted with good accuracy; the data can then be compressed better
// than with the default empty dictionary. In this version of the library,
// only the last 32K bytes of the dictionary are used.
//
// Upon return of this function ZState.Adler is set to the Adler32 value
// of the dictionary. The decompressor may later use this value to determine
// which dictionary has been used by the compressor. (The Adler32 value
// applies to the whole dictionary even if only a subset of the dictionary is
// actually used by the compressor.)
//
// DeflateSetDictionary returns Z_OK if success or Z_STREAM_ERROR if a
// parameter is invalid (such as nil dictionary) or the stream state
// is inconsistent (for example if Deflate has already been called for this
// stream). DeflateSetDictionary does not perform any compression, this will
// be done by Deflate.

var
  S: PDeflateState;
  Length: Cardinal;
  N: Cardinal;
  HashHead: Cardinal;
  MaxDistance: Cardinal;

begin
  Length := DictLength;
  HashHead := 0;

  if (ZState.State  =  nil) or
     (Dictionary  =  nil) or
     (PDeflateState(ZState.State).Status <> INIT_STATE) then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  S := PDeflateState(ZState.State);
  ZState.Adler := Adler32(ZState.Adler, Dictionary, DictLength);

  if Length < MIN_MATCH then
  begin
    Result := Z_OK;
    Exit;
  end;

  MaxDistance := S.WindowSize - MIN_LOOKAHEAD;
  if Length > MaxDistance then
  begin
    Length := MaxDistance;
    // use the tail of the dictionary
    Inc(Dictionary, DictLength - Length);
  end;

  Move( Dictionary^ , S.Window^, Length);
  S.StringStart := Length;
  S.BlockStart := Integer(Length);

  // Insert all strings in the hash table (except for the last two bytes).
  // S.Lookahead stays nil, so S.InsertHash will be recomputed at the next call of FillWindow.
  S.InsertHash := S.Window[0];
  S.InsertHash := ((S.InsertHash shl S.HashShift) xor (S.Window[1])) and S.HashMask;

  for N := 0 to Length - MIN_MATCH do InsertString(S^, N, HashHead);

  Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateReset(var ZState: TZState): Integer;

// This function is equivalent to DeflateEnd followed by DeflateInit,
// but does not free and reallocate all the internal compression state.
// The stream will keep the same compression level and any other attributes
// that may have been set by DeflateInit2.
//
// DeflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
// stream state was inconsistent (such as state being nil).

var
  S: PDeflateState;

begin
  if ZState.State = nil then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  ZState.TotalOutput := 0;
  ZState.TotalInput := 0;
  ZState.Msg := '';       
  ZState.DataType := Z_UNKNOWN;

  S := PDeflateState(ZState.State);
  S.Pending := 0;
  S.PendingOutput := PByte(S.PendingBuffer);

  if S.NoHeader < 0 then
  begin
    // was set to -1 by Deflate(..., Z_FINISH);
    S.NoHeader := 0;
  end;
  
  if S.NoHeader <> 0 then S.Status := BUSY_STATE
                     else S.Status := INIT_STATE;
  ZState.Adler := 1;
  S.LastFlush := Z_NO_FLUSH;

  TreeInit(S^);
  LongestMatchInit(S^);

  Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateParams(var ZState: TZState; Level: Integer; Strategy: Integer): Integer;

// Dynamically update the compression level and compression strategy.
// This can be used to switch between compression and straight copy of
// the input data or to switch to a different kind of input data requiring
// a different strategy. If the compression level is changed the input
// available so far is compressed with the old Level (and may be flushed).
// The new level will take effect only at the next call of Deflate.
//
// Before the call of DeflateParams the stream state must be set as for
// a call of Deflate, since the currently available input may have to
// be compressed and flushed. In particular, ZState.AvailableOutput must be non-zero.
//
// DeflateParams returns Z_OK if successuful, Z_STREAM_ERROR if the source
// stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
// if ZState.AvailableOutput was zero.

var
  S: PDeflateState;
  Func: TCompressFunction;
  Error: Integer;

begin
  Error := Z_OK;
  if ZState.State  = nil then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  S := PDeflateState(ZState.State);

  if Level = Z_DEFAULT_COMPRESSION then Level := 6;
  
  if (Level < 0) or
     (Level > 9) or
     (Strategy < 0) or
     (Strategy > Z_HUFFMAN_ONLY) then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  Func := ConfigurationTable[S.Level].Func;

  if (@Func <> @ConfigurationTable[Level].Func) and (ZState.TotalInput <> 0) then
  begin
    // flush the last buffer
    Error := Deflate(ZState, Z_PARTIAL_FLUSH);
  end;

  if S.Level <> Level then
  begin
    S.Level := Level;
    S.MaxLazyMatch := ConfigurationTable[Level].MaxLazy;
    S.GoodMatch := ConfigurationTable[Level].GoodLength;
    S.NiceMatch := ConfigurationTable[Level].NiceLength;
    S.MaxChainLength := ConfigurationTable[Level].MaxChain;
  end;
  S.Strategy := Strategy;
  Result := Error;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure PutShortMSB(var S: TDeflateState; B: Cardinal);

// Puts a word in the pending buffer. The 16-bit value is put in MSB order.
// The stream state must be correct and there must be enough room in PendingBuffer.

begin
  S.PendingBuffer[S.Pending] := B shr 8;
  Inc(S.Pending);
  S.PendingBuffer[S.Pending] := B and $FF;
  Inc(S.Pending);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure FlushPending(var ZState: TZState);

// Flushs as much pending output as possible. All Deflate output goes through this function so some applications may
// wish to modify it to avoid allocating a large ZState.NextOutput buffer and copying into it
// (see also ReadBuffer). 

var
  Len: Cardinal;
  S: PDeflateState;

begin
  S := PDeflateState(ZState.State);
  Len := S.Pending;

  if Len > ZState.AvailableOutput then Len := ZState.AvailableOutput;
  if Len > 0 then
  begin
    Move(S.PendingOutput^, ZState.NextOutput^, Len);
    Inc(ZState.NextOutput, Len);
    Inc(S.PendingOutput, Len);
    Inc(ZState.TotalOutput, Len);
    Dec(ZState.AvailableOutput, Len);
    Dec(S.Pending, Len);
    if S.Pending = 0 then S.PendingOutput := PByte(S.PendingBuffer);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function Deflate(var ZState: TZState; Flush: Integer): Integer;

// Performs one or both of the following actions:
//
// - Compress more input starting at NextInput and update NextInput and AvailableInput
//  accordingly. If not all input can be processed (because there is not enough room in the output buffer), NextInput
//  and AvailableInput are updated and processing will resume at this point for the next call of Deflate.
//
// - Provide more output starting at NextOutput and update NextOutput and AvailableOutput accordingly. This action is
//   forced if the parameter Flush is non zero. Forcing Flush frequently degrades the compression ratio, so this
//   parameter should be set only when necessary (in interactive applications).
//   Some output may be provided even if Flush is not set.
//
// Before the call of Deflate, the application should ensure that at least one of the actions is possible, by providing
// more input and/or consuming more output, and updating AvailableInput or AvailableOutput accordingly. AvailableOutput
// should never be zero before the call. The application can consume the compressed output when it wants, for example
// when the output buffer is full (AvailableOutput = 0), or after each call of Deflate. if Deflate returns Z_OK and with
// zero AvailableOutput, it must be called again after making room in the output buffer because there might be more output pending.
//
// If the parameter Flush is set to Z_PARTIAL_FLUSH, the current compression block is terminated and flushed to the
// output buffer so that the decompressor can get all input data available so far. For method 9 a future variant on
// method 8, the current block will be flushed but not terminated. Z_SYNC_FLUSH has the same effect as partial flush
// except that the compressed output is byte aligned (the compressor can clear its internal bit buffer) and the current
// block is always terminated. This can be useful if the compressor has to be restarted from scratch after an
// interruption (in which case the internal state of the compressor may be lost). If Flush is set to Z_FULL_FLUSH, the
// compression block is terminated, a special marker is output and the compression dictionary is discarded. This
// is useful to allow the decompressor to synchronize if one compressed block has been damaged (see InflateSync below).
// Flushing degrades compression and so should be used only when necessary.  Using Z_FULL_FLUSH too often can seriously
// degrade the compression. if Deflate returns with AvailableOutput = 0, this function must be called again with the
// same Value of the Flush parameter and more output space (updated AvailableOutput), until the Flush is complete
// (Deflate returns with non-zero AvailableOutput).
//
// If the parameter Flush is set to Z_FINISH, all Pending input is processed, all pending output is flushed and Deflate
// returns with Z_STREAM_END if there was enough output space. If Deflate returns with Z_OK, this function must be
// called again with Z_FINISH and more output space (updated AvailableOutput) but no more input data, until it returns
// with Z_STREAM_END or an error. After Deflate has returned Z_STREAM_END, the only possible operations on the
// stream are DeflateReset or DeflateEnd.
//
// Z_FINISH can be used immediately after DeflateInit if all the compression is to be done in a single step. In this
// case, AvailableOutput must be at least 0.1% larger than AvailableInput plus 12 bytes. If Deflate does not return
// Z_STREAM_END then it must be called again as described above.
//
// Deflate may update DataType if it can make a good guess about the input data type (Z_ASCII or Z_BINARY). In doubt,
// the data is considered binary. This field is only for information purposes and does not affect the compression
// algorithm in any manner.
//
// Deflate returns Z_OK if some progress has been made (mnore input processed or more output produced), Z_STREAM_END if
// all input has been consumed and all output has been produced (only when Flush is set to Z_FINISH), Z_STREAM_ERROR if
// the stream State was inconsistent (for example if NextInput or NextOutput was nil), Z_BUF_ERROR if no progress is possible. 

var
  OldFlush: Integer; // value of Flush param for previous Deflate call
  S: PDeflateState;
  Header: Cardinal;
  LevelFlags: Cardinal;
  BlockState: TBlockState;

begin
  if (ZState.State = nil) or (Flush > Z_FINISH) or (Flush < 0) then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;
  S := PDeflateState(ZState.State);

  if (ZState.NextOutput = nil) or
     ((ZState.NextInput = nil) and (ZState.AvailableInput <> 0)) or
     ((S.Status = FINISH_STATE) and (Flush <> Z_FINISH)) then
  begin
    ZState.Msg := ErrorMessages[ERROR_BASE - Z_STREAM_ERROR];
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  if ZState.AvailableOutput = 0 then
  begin
    ZState.Msg := ErrorMessages[ERROR_BASE - Z_BUF_ERROR];
    Result := Z_BUF_ERROR;
    Exit;
  end;

  // just in case
  S.ZState := @ZState;
  OldFlush := S.LastFlush;
  S.LastFlush := Flush;

  // write the zlib header 
  if S.Status = INIT_STATE then
  begin
    Header := (Z_DEFLATED + ((S.WindowBits - 8) shl 4)) shl 8;
    LevelFlags := (S.Level - 1) shr 1;

    if LevelFlags > 3 then LevelFlags := 3;
    Header := Header or (LevelFlags shl 6);
    if (S.StringStart <> 0) then Header := Header or PRESET_DICT;
    Inc(Header, 31 - (Header mod 31));

    S.Status := BUSY_STATE;
    PutShortMSB(S^, Header);

    // save the Adler32 of the preset dictionary 
    if S.StringStart <> 0 then
    begin
      PutShortMSB(S^, Cardinal(ZState.Adler shr 16));
      PutShortMSB(S^, Cardinal(ZState.Adler and $FFFF));
    end;
    ZState.Adler := 1;
  end;

  // flush as much pending output as possible 
  if S.Pending <> 0 then
  begin
    FlushPending(ZState);
    if ZState.AvailableOutput = 0 then
    begin
      // Since AvailableOutput is 0, Deflate will be called again with
	    // more output space, but possibly with both Pending and
     	// AvailableInput equal to zero. There won't be anything to do,
	    // but this is not an error situation so make sure we
	    // return OK instead of BUF_ERROR at next call of Deflate.
      S.LastFlush := -1;
      Result := Z_OK;
      Exit;
    end;

    // Make sure there is something to do and avoid duplicate consecutive
    // flushes. For repeated and useless calls with Z_FINISH, we keep
    // returning Z_STREAM_END instead of Z_BUFF_ERROR.
  end
  else
    if (ZState.AvailableInput = 0) and
       (Flush <= OldFlush) and
       (Flush <> Z_FINISH) then
    begin
      ZState.Msg := ErrorMessages[ERROR_BASE - Z_BUF_ERROR];
      Result := Z_BUF_ERROR;
      Exit;
    end;

  // user must not provide more input after the first FINISH
  if (S.Status = FINISH_STATE) and (ZState.AvailableInput <> 0) then
  begin
    ZState.Msg := ErrorMessages[ERROR_BASE - Z_BUF_ERROR];
    Result := Z_BUF_ERROR;
    Exit;
  end;

  // start a new block or continue the current one
  if (ZState.AvailableInput <> 0) or
     (S.Lookahead <> 0) or
     ((Flush <> Z_NO_FLUSH) and (S.Status <> FINISH_STATE)) then
  begin
    BlockState := ConfigurationTable[S.Level].Func(S^, Flush);
    if (BlockState = bsFinishStarted) or (BlockState = bsFinishDone) then S.Status := FINISH_STATE;
    if (BlockState = bsNeedMore) or (BlockState = bsFinishStarted) then
    begin
      // avoid BUF_ERROR next call, see above
      if (ZState.AvailableOutput = 0) then S.LastFlush := -1;
      Result := Z_OK;
      Exit;
      
      // If Flush <> Z_NO_FLUSH and AvailableOutput = 0, the next call
	    // of Deflate should use the same Flush parameter to make sure
	    // that the Flush is complete. So we don't have to output an
	    // empty block here, this will be done at next call. This also
	    // ensures that for a very small output buffer we emit at most
	    // one empty block. 
    end;
    if BlockState = bsBlockDone then
    begin
      if Flush = Z_PARTIAL_FLUSH then TreeAlign(S^)
                                 else
      begin
        // FULL_FLUSH or SYNC_FLUSH 
        TreeStroredBlock(S^, nil, 0, False);

        // for a full Flush, this empty block will be recognized as a special marker
        if Flush = Z_FULL_FLUSH then
        begin
          // forget history
          S.Head[S.HashSize - 1] := ZNIL;
          FillChar(S.Head^, (S.HashSize - 1) * SizeOf(S.Head[0]), 0);
        end;
      end;

      FlushPending(ZState);
      if ZState.AvailableOutput = 0 then
      begin
        // avoid BUF_ERROR at next call, see above
        S.LastFlush := -1;
	      Result := Z_OK;
        Exit;
      end;
    end;
  end;

  if Flush <> Z_FINISH then
  begin
    Result := Z_OK;
    Exit;
  end;

  if S.NoHeader <> 0 then
  begin
    Result := Z_STREAM_END;
    Exit;
  end;

  // write the zlib trailer (Adler32)
  PutShortMSB(S^, Cardinal(ZState.Adler shr 16));
  PutShortMSB(S^, Cardinal(ZState.Adler and $FFFF));
  FlushPending(ZState);

  // If AvailableOutput is zero the application will call Deflate again to Flush the rest
  // write the trailer only once!
  S.NoHeader := -1;
  if S.Pending <> 0 then Result := Z_OK
                    else Result := Z_STREAM_END;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateEnd(var ZState: TZState): Integer;

// All dynamically allocated data structures for this stream are freed.
// This function discards any unprocessed input and does not Flush any
// pending output.
//
// DeflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
// stream State was inconsistent, Z_DATA_ERROR if the stream was freed
// prematurely (some input or output was discarded). 

var
  Status: Integer;
  S: PDeflateState;

begin
  if ZState.State = nil then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  S := PDeflateState(ZState.State);
  Status := S.Status;
  if (Status <> INIT_STATE) and
     (Status <> BUSY_STATE) and
     (Status <> FINISH_STATE) then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  FreeMem(S.PendingBuffer);
  FreeMem(S.Head);
  FreeMem(S.Previous);
  FreeMem(S.Window);
  FreeMem(S);
  ZState.State := nil;

  if Status = BUSY_STATE then Result := Z_DATA_ERROR
                         else Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateCopy(Dest, Source: PZState): Integer;

// Copies the source state to the destination state.
//
// Sets the destination stream as a complete copy of the source stream. If the source stream is using an application-
// supplied history buffer, a new buffer is allocated for the destination stream.  The compressed output buffer is always
// application-supplied. It's the responsibility of the application to provide the correct values of NextOutput and
// AvailableOutput for the next call of Deflate.
//
// This function can be useful when several compression strategies will be tried, for example when there are several
// ways of pre-processing the input data with a filter. The streams that will be discarded should then be freed by
// calling DeflateEnd. Note that DeflateCopy duplicates the internal compression state which can be quite large, so this
// strategy is slow and can consume lots of memory.
//
// DeflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if the source stream
// state was inconsistent (such as zalloc being nil). Msg is left unchanged in both source and destination.

var
  DestState: PDeflateState;
  SourceState: PDeflateState;
  Overlay: PWordArray;

begin
  if (Source = nil) or (Dest = nil) or (Source.State = nil) then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  SourceState := PDeflateState(Source.State);
  Dest^ := Source^;

  try
    DestState := AllocMem(SizeOf(TDeflateState));

    Dest.State := PInternalState(DestState);
    DestState^ := SourceState^;
    DestState.ZState := Dest;

    DestState.Window := AllocMem(2 * DestState.WindowSize);
    DestState.Previous := AllocMem(DestState.WindowSize * SizeOf(Word));
    DestState.Head := AllocMem(DestState.HashSize * SizeOf(Word));
    Overlay := AllocMem(DestState.LiteralBufferSize * SizeOf(Word) + 2);
    DestState.PendingBuffer := PByteArray (Overlay);

    Move(SourceState.Window^, DestState.Window^, 2 * DestState.WindowSize);
    Move(SourceState.Previous^, DestState.Previous^, DestState.WindowSize * SizeOf(Word));
    Move(SourceState.Head^, DestState.Head^, DestState.HashSize * SizeOf(Word));
    Move(SourceState.PendingBuffer^, DestState.PendingBuffer^, DestState.PendingBufferSize);

    DestState.PendingOutput := @DestState.PendingBuffer[Cardinal(SourceState.PendingOutput) - Cardinal(SourceState.PendingBuffer)];
    DestState.DistanceBuffer := @Overlay[DestState.LiteralBufferSize div SizeOf(Word)];
    DestState.LiteralBuffer := @DestState.PendingBuffer[(1 + SizeOf(Word)) * DestState.LiteralBufferSize];

    DestState.LiteralDescriptor.DynamicTree := @DestState.LiteralTree;
    DestState.DistanceDescriptor.DynamicTree := @DestState.DistanceTree;
    DestState.BitLengthDescriptor.DynamicTree := @DestState.BitLengthTree;

    Result := Z_OK;
  except
    DeflateEnd(Dest^);
    raise;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function ReadBuffer(ZState: PZState; Buffer: PByte; Size: Cardinal): Integer;

// Reads a new buffer from the current input stream, updates the Adler32 and total number of bytes read.  All Deflate
// input goes through this function so some applications may wish to modify it to avoid allocating a large
// ZState.NextInput buffer and copying from it (see also FlushPending).

var
  Len: Cardinal;

begin
  Len := ZState.AvailableInput;

  if Len > Size then Len := Size;
  if Len = 0 then
  begin
    Result := 0;
    Exit;
  end;

  Dec(ZState.AvailableInput, Len);

  if PDeflateState(ZState.State).NoHeader = 0 then ZState.Adler := Adler32(ZState.Adler, ZState.NextInput, Len);
  Move(ZState.NextInput^, Buffer^, Len);
  Inc(ZState.NextInput, Len);
  Inc(ZState.TotalInput, Len);
  Result := Len;
end;

//----------------------------------------------------------------------------------------------------------------------

function LongestMatch(var S: TDeflateState; CurrentMatch: Cardinal): Cardinal;

// Sets MatchStart to the longest match starting at the given string and returns its length. Matches shorter or equal to
// PreviousLength are discarded, in which case the result is equal to PreviousLength and MatchStart is garbage.
// CurrentMatch is the head of the hash chain for the current string (StringStart) and its distance is <= MaxDistance,
// and PreviousLength >= 1.
// The match length will not be greater than S.Lookahead. 

var
  ChainLength: Cardinal; // max hash chain length
  Scan: PByte;           // current string
  Match: PByte;          // matched string
  Len: Cardinal;         // length of current match
  BestLen: Cardinal;     // best match length so far
  NiceMatch: Cardinal;    
  Limit: Cardinal;

  Previous: PWordArray;
  WMask: Cardinal;
  StrEnd: PByte;
  ScanEnd1: Byte;
  ScanEnd: Byte;
  MaxDistance: Cardinal;

begin
  ChainLength := S.MaxChainLength;
  Scan := @S.Window[S.StringStart];
  BestLen := S.PreviousLength;
  NiceMatch := S.NiceMatch;
  MaxDistance := S.WindowSize - MIN_LOOKAHEAD;

  // In order to simplify the code, match distances are limited to MaxDistance instead of WSize.
  if S.StringStart > MaxDistance then Limit := S.StringStart - MaxDistance
                                 else Limit := ZNIL;

  // Stop when CurrentMatch becomes <= Limit. To simplify the Code we prevent matches with the string of window index 0.
  Previous := S.Previous;
  WMask := S.WindowMask;

  StrEnd := @S.Window[S.StringStart + MAX_MATCH];
  {$ifopt R+} {$R-} {$define RangeCheck} {$endif}
  ScanEnd1 := PByteArray(Scan)[BestLen - 1];
  ScanEnd := PByteArray(Scan)[BestLen];
  {$ifdef RangeCheck} {$R+} {$undef RangeCheck} {$endif}

  // The code is optimized for HashBits >= 8 and MAX_MATCH - 2 multiple of 16.
  // It is easy to get rid of this optimization if necessary.
  // Do not waste too much time if we already have a good Match.
  if S.PreviousLength >= S.GoodMatch then ChainLength := ChainLength shr 2;

  // Do not look for matches beyond the end of the input. This is necessary to make Deflate deterministic.
  if NiceMatch > S.Lookahead then NiceMatch := S.Lookahead;

  repeat
    Match := @S.Window[CurrentMatch];

    // Skip to next match if the match length cannot increase or if the match length is less than 2.
    {$ifopt R+} {$R-} {$define RangeCheck} {$endif}
    if (PByteArray(Match)[BestLen] = ScanEnd) and
       (PByteArray(Match)[BestLen - 1] = ScanEnd1) and
       (Match^ = Scan^) then
    {$ifdef RangeCheck} {$R+} {$undef RangeCheck} {$endif}
    begin
      Inc(Match);
      if Match^ <> PByteArray(Scan)[1] then
      begin
        // The Check at BestLen - 1 can be removed because it will be made again later (this heuristic is not always a win).
        // It is not necessary to compare Scan[2] and Match[2] since they are always equal when the other bytes match,
        // given that the hash keys are equal and that HashBits >= 8.
        Inc(Scan, 2);
        Inc(Match);

        // We check for insufficient lookahead only every 8th comparison, the 256th check will be made at StringStart + 258.
        repeat
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
          Inc(Scan); Inc(Match); if (Scan^ <> Match^) then Break;
        until (Cardinal(Scan) >= Cardinal(StrEnd));

        Len := MAX_MATCH - Integer(Cardinal(StrEnd) - Cardinal(Scan));
        Scan := StrEnd;
        Dec(Scan, MAX_MATCH);

        if Len > BestLen then
        begin
          S.MatchStart := CurrentMatch;
          BestLen := Len;
          if Len >= NiceMatch then Break;
          {$ifopt R+} {$R-} {$define RangeCheck} {$endif}
          ScanEnd1 := PByteArray(Scan)[BestLen - 1];
          ScanEnd := PByteArray(Scan)[BestLen];
          {$ifdef RangeCheck} {$R+} {$undef RangeCheck} {$endif}
        end;
      end;
    end;
    CurrentMatch := Previous[CurrentMatch and WMask];
    Dec(ChainLength);
  until (CurrentMatch <= Limit) or (ChainLength = 0);

  if BestLen <= S.Lookahead then Result := BestLen
                            else Result := S.Lookahead;
end;

//----------------------------------------------------------------------------------------------------------------------

procedure FillWindow(var S: TDeflateState);

// Fills the window when the lookahead becomes insufficient, updates StringStart and Lookahead.
// Lookahead must be less than MIN_LOOKAHEAD.
// StringStart will be <= CurrentWindowSize - MIN_LOOKAHEAD on exit.
// On exit at least one byte has been read, or AvailableInput = 0. Reads are performed for at least two bytes (required
// for the zip translate_eol option -> not supported here). 

var
  N, M: Cardinal;
  P: PWord;
  More: Cardinal; // amount of free space at the end of the window 
  WSize: Cardinal;

begin
  WSize := S.WindowSize;
  repeat
    More := S.CurrentWindowSize - Integer(S.Lookahead) - Integer(S.StringStart);
    if (More = 0) and (S.StringStart = 0) and (S.Lookahead = 0) then More := WSize
                                                                else
    if More = Cardinal(-1) then
    begin
      // Very unlikely, but sometimes possible if StringStart = 0 and Lookahead = 1 (input done one byte at time)
      Dec(More);
      // If the Window is almost full and there is insufficient lookahead,
      // move the upper half to the lower one to make room in the upper half.
    end
    else
      if S.StringStart >= WSize + (WSize - MIN_LOOKAHEAD) then
      begin
        Move(S.Window[WSize], S.Window^, WSize);
        Dec(S.MatchStart, WSize);
        Dec(S.StringStart, WSize);
        // we now have StringStart >= MaxDistance
        Dec(S.BlockStart, Integer(WSize));

        // Slide the hash table (could be avoided with 32 bit values at the expense of memory usage). We slide even when
        // Level = 0 to keep the hash table consistent if we switch back to Level > 0 later. (Using Level 0 permanently
        // is not an optimal usage of zlib, so we don't care about this pathological case.)
        N := S.HashSize;
        P := @S.Head[N];
        repeat
          Dec(P);
          M := P^;
          if M >= WSize then P^ := M - WSize
                        else P^ := ZNIL;
          Dec(N);
        until N = 0;

        N := WSize;
        P := @S.Previous[N];
        repeat
          Dec(P);
          M := P^;
          if M >= WSize then P^ := M - WSize
                        else P^ := ZNIL;
          // if N is not on any hash chain Previous[N] is garbage but its value will never be used
          Dec(N);
        until N = 0;

        Inc(More, WSize);
      end;


    if S.ZState.AvailableInput = 0 then Exit;

    // If there was no sliding:
    //    StringStart <= WSize + MaxDistance - 1 and Lookahead <= MIN_LOOKAHEAD - 1 and
    //    More = CurrentWindowSize - Lookahead - StringStart
    // => More >= CurrentWindowSize - (MIN_LOOKAHEAD - 1 + WSize + MaxDistance - 1)
    // => More >= CurrentWindowSize - 2 * WSize + 2
    // In the BIG_MEM or MMAP case (not yet supported),
    //    CurrentWindowSize = input_size + MIN_LOOKAHEAD  and
    //    StringStart + S.Lookahead <= input_size => More >= MIN_LOOKAHEAD.
    // Otherwise, CurrentWindowSize = 2 * WSize so More >= 2.
    // If there was sliding More >= WSize. So in all cases More >= 2.

    N := ReadBuffer(S.ZState, @S.Window[S.StringStart + S.Lookahead], More);
    Inc(S.Lookahead, N);

    // Initialize the hash Value now that we have some input:
    if S.Lookahead >= MIN_MATCH then
    begin
      S.InsertHash := S.Window[S.StringStart];
      S.InsertHash := ((S.InsertHash shl S.HashShift) xor S.Window[S.StringStart + 1]) and S.HashMask;
    end;
    // If the whole input has less than MIN_MATCH bytes, InsertHash is garbage,
    // but this is not important since only literal bytes will be emitted.
  until (S.Lookahead >= MIN_LOOKAHEAD) or (S.ZState.AvailableInput = 0);
end;

//----------------------------------------------------------------------------------------------------------------------

procedure FlushBlockOnly(var S: TDeflateState; EOF: Boolean);

// Flushs the current block with given end-of-file flag.
// StringStart must be set to the end of the current match.

begin
  if S.BlockStart >= 0 then TreeFlushBlock(S, @S.Window[Cardinal(S.BlockStart)], Integer(S.StringStart) - S.BlockStart, EOF)
                       else TreeFlushBlock(S, nil, Integer(S.StringStart) - S.BlockStart, EOF);

  S.BlockStart := S.StringStart;
  FlushPending(S.ZState^);
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateStored(var S: TDeflateState; Flush: Integer): TBlockState;

// Copies without compression as much as possible from the input stream and returns the current block state.
// This function does not insert new strings in the dictionary since uncompressible data is probably not useful.
// This function is used only for the Level = 0 compression option.
// NOTE: This function should be optimized to avoid extra copying from Window to PendingBuffer.
//
// Stored blocks are limited to $FFFF bytes, PendingBuffer is limited to PendingBufferSize
// and each stored block has a 5 Byte header.

var
  MaxBlockSize: Integer;
  MaxStart: Cardinal;

begin
  MaxBlockSize := $FFFF;
  if MaxBlockSize > S.PendingBufferSize - 5 then MaxBlockSize := S.PendingBufferSize - 5;

  // copy as much as possible from input to output
  while True do
  begin
    // fill the window as much as possible
    if S.Lookahead <= 1 then
    begin
      FillWindow(S);
      if (S.Lookahead = 0) and (Flush = Z_NO_FLUSH) then
      begin
        Result := bsNeedMore;
        Exit;
      end;

      // flush the current block
      if S.Lookahead = 0 then Break;
    end;
    Inc(S.StringStart, S.Lookahead);
    S.Lookahead := 0;

    // emit a stored block if PendingBuffer will be full
    MaxStart := S.BlockStart + MaxBlockSize;
    if (S.StringStart = 0) or (S.StringStart >= MaxStart) then
    begin
      // StringStart = 0 is possible when wrap around on 16-bit machine 
      S.Lookahead := S.StringStart - MaxStart;
      S.StringStart := MaxStart;
      FlushBlockOnly(S, False);
      if S.ZState.AvailableOutput = 0 then
      begin
        Result := bsNeedMore;
        Exit;
      end;
    end;

    // Flush if we may have to slide, otherwise BlockStart may become negative and the data will be gone.
    if S.StringStart - Cardinal(S.BlockStart) >= S.WindowSize - MIN_LOOKAHEAD then
    begin
      FlushBlockOnly(S, False);
      if S.ZState.AvailableOutput = 0 then
      begin
        Result := bsNeedMore;
        Exit;
      end;
    end;
  end;

  FlushBlockOnly(S, Flush = Z_FINISH);
  if S.ZState.AvailableOutput = 0 then
  begin
    if Flush = Z_FINISH then Result := bsFinishStarted
                        else DeflateStored := bsNeedMore;
    Exit;
  end;

  if Flush = Z_FINISH then Result := bsFinishDone
                      else Result := bsBlockDone;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateFast(var S: TDeflateState; Flush: Integer): TBlockState;

// Compresses as much as possible from the input stream and returns the current block state.
// This function does not perform lazy evaluation of matches and inserts new strings in the Dictionary only for
// unmatched strings or for short matches. It is used only for the fast compression options. 

var
  HashHead: Cardinal;  // head of the hash chain
  BlockFlush: Boolean; // set if current block must be flushed

begin
  HashHead := ZNIL;
  while True do
  begin
    // Make sure that we always have enough lookahead, except at the end of the input file. We need MAX_MATCH bytes
    // for the next match plus MIN_MATCH bytes to insert the string following the next match.
    if S.Lookahead < MIN_LOOKAHEAD then
    begin
      FillWindow(S);
      if (S.Lookahead < MIN_LOOKAHEAD) and (Flush = Z_NO_FLUSH) then
      begin
        Result := bsNeedMore;
        Exit;
      end;

      // flush the current block
      if S.Lookahead = 0 then Break;
    end;

    // Insert the string Window[StringStart .. StringStart + 2] in the
    // dictionary and set HashHead to the head of the hash chain.
    if S.Lookahead >= MIN_MATCH then InsertString(S, S.StringStart, HashHead);

    // Find the longest match, discarding those <= PreviousLength.
    // At this point we have always MatchLength < MIN_MATCH.
    if (HashHead <> ZNIL) and
       (S.StringStart - HashHead <= (S.WindowSize - MIN_LOOKAHEAD)) then
    begin
      // To simplify the code, we prevent matches with the string of window index 0 (in particular we have to
      // avoid a match of the string with itself at the start of the input file).
      if S.Strategy <> Z_HUFFMAN_ONLY then S.MatchLength := LongestMatch(S, HashHead);
    end;
    if S.MatchLength >= MIN_MATCH then
    begin
      BlockFlush := TreeTally(S, S.StringStart - S.MatchStart, S.MatchLength - MIN_MATCH);
      Dec(S.Lookahead, S.MatchLength);

      // Insert new strings in the hash table only if the match length
      // is not too large. This saves time but degrades compression.
      if (S.MatchLength <= S.MaxInsertLength) and (S.Lookahead >= MIN_MATCH) then
      begin
        // string at StringStart already in hash table
        Dec(S.MatchLength);
        repeat
          Inc(S.StringStart);
          InsertString(S, S.StringStart, HashHead);
          // StringStart never exceeds WSize - MAX_MATCH, so there are always MIN_MATCH bytes ahead.
          Dec(S.MatchLength);
        until S.MatchLength = 0;
        Inc(S.StringStart);
      end
      else
      begin
        Inc(S.StringStart, S.MatchLength);
        S.MatchLength := 0;
        S.InsertHash := S.Window[S.StringStart];
        S.InsertHash := ((S.InsertHash shl S.HashShift) xor S.Window[S.StringStart + 1]) and S.HashMask;

        // if Lookahead < MIN_MATCH, InsertHash is garbage, but it does not
        // matter since it will be recomputed at next Deflate call.
      end;
    end
    else
    begin
      // no match, output a literal byte 
      BlockFlush := TreeTally(S, 0, S.Window[S.StringStart]);
      Dec(S.Lookahead);
      Inc(S.StringStart);
    end;

    if BlockFlush then
    begin
      FlushBlockOnly(S, False);
      if S.ZState.AvailableOutput = 0 then
      begin
        Result := bsNeedMore;
        Exit;
      end;
    end;
  end;

  FlushBlockOnly(S, Flush = Z_FINISH);
  if S.ZState.AvailableOutput = 0 then
  begin
    if Flush = Z_FINISH then Result := bsFinishStarted
                        else Result := bsNeedMore;
  end
  else
    if Flush = Z_FINISH then Result := bsFinishDone
                        else Result := bsBlockDone;
end;

//----------------------------------------------------------------------------------------------------------------------

function DeflateSlow(var S: TDeflateState; Flush: Integer): TBlockState;

// Same as above, but achieves better compression. We use a lazy evaluation for matches. A match is finally adopted
// only if there is no better match at the next window position.

var
  HashHead: Cardinal;  // head of hash chain
  BlockFlush: Boolean; // set if current block must be flushed
  MaxInsert: Cardinal;

begin
  HashHead := ZNIL;

  while True do
  begin
    // Make sure that we always have enough lookahead, except at the end of the input file. We need MAX_MATCH bytes
    // for the next match, plus MIN_MATCH bytes to insert the string following the next match.
    if S.Lookahead < MIN_LOOKAHEAD then
    begin
      FillWindow(S);
      if (S.Lookahead < MIN_LOOKAHEAD) and (Flush = Z_NO_FLUSH) then
      begin
        Result := bsNeedMore;
        Exit;
      end;

      // flush the current block
      if S.Lookahead = 0 then Break;
    end;

    // Insert the string Window[StringStart .. StringStart + 2] in the
    // dictionary and set HashHead to the head of the hash chain.
    if S.Lookahead >= MIN_MATCH then InsertString(S, S.StringStart, HashHead);

    // find the longest match, discarding those <= PreviousLength
    S.PreviousLength := S.MatchLength;
    S.PreviousMatch := S.MatchStart;
    S.MatchLength := MIN_MATCH - 1;

    if (HashHead <> ZNIL) and
       (S.PreviousLength < S.MaxLazyMatch) and
       (S.StringStart - HashHead <= (S.WindowSize - MIN_LOOKAHEAD)) then
    begin
      // To simplify the code we prevent matches with the string of window Index 0 (in particular we have
      // to avoid a match of the string with itself at the start of the input file).
      if S.Strategy <> Z_HUFFMAN_ONLY then S.MatchLength := LongestMatch(S, HashHead);
      if (S.MatchLength <= 5) and
         ((S.Strategy = Z_FILTERED) or ((S.MatchLength = MIN_MATCH) and
         (S.StringStart - S.MatchStart > TOO_FAR))) then
      begin
        // If PreviousMatch is also MIN_MATCH MatchStart is garbage but we will ignore the current match anyway.
        S.MatchLength := MIN_MATCH - 1;
      end;
    end;

    // If there was a match at the previous step and the current match is not better output the previous match.
    if (S.PreviousLength >= MIN_MATCH) and (S.MatchLength <= S.PreviousLength) then
    begin
      MaxInsert := S.StringStart + S.Lookahead - MIN_MATCH;
      // Do not insert strings in hash table beyond this.
      BlockFlush := TreeTally(S, S.StringStart - 1 - S.PreviousMatch, S.PreviousLength - MIN_MATCH);

      // Insert in hash table all strings up to the end of the match. StringStart - 1 and StringStart are already inserted.
      // If there is not enough lookahead the last two strings are not inserted in the hash table.
      Dec(S.Lookahead, S.PreviousLength - 1);
      Dec(S.PreviousLength, 2);
      repeat
        Inc(S.StringStart);
        if S.StringStart <= MaxInsert then InsertString(S, S.StringStart, HashHead);
        Dec(S.PreviousLength);
      until S.PreviousLength = 0;

      S.MatchAvailable := False;
      S.MatchLength := MIN_MATCH - 1;
      Inc(S.StringStart);

      if BlockFlush then  
      begin
        FlushBlockOnly(S, False);
        if S.ZState.AvailableOutput = 0 then
        begin
          Result := bsNeedMore;
          Exit;
        end;
      end;
    end
    else
      if S.MatchAvailable then
      begin
        // If there was no match at the previous position output a single literal.
        // If there was a match but the current match is longer truncate the previous match to a single literal.
        BlockFlush := TreeTally (S, 0, S.Window[S.StringStart - 1]);
        if BlockFlush then FlushBlockOnly(S, False);
        Inc(S.StringStart);
        Dec(S.Lookahead);
        if S.ZState.AvailableOutput = 0 then
        begin
          Result := bsNeedMore;
          Exit;
        end;
      end
      else
      begin
        // There is no previous match to compare with wait for the next step to decide.
        S.MatchAvailable := True;
        Inc(S.StringStart);
        Dec(S.Lookahead);
      end;
  end;

  if S.MatchAvailable then
  begin
    TreeTally (S, 0, S.Window[S.StringStart - 1]);
    S.MatchAvailable := False;
  end;

  FlushBlockOnly(S, Flush = Z_FINISH);
  if S.ZState.AvailableOutput = 0 then
  begin
    if Flush = Z_FINISH then Result := bsFinishStarted
                        else Result := bsNeedMore;
  end
  else
    if Flush = Z_FINISH then Result := bsFinishDone
                        else Result := bsBlockDone;
end;

//----------------- Inflate support ------------------------------------------------------------------------------------

const
  InflateMask: array[0..16] of Cardinal = (
    $0000, $0001, $0003, $0007, $000F, $001F, $003F, $007F, $00FF,
    $01FF, $03FF, $07FF, $0FFF, $1FFF, $3FFF, $7FFF, $FFFF
  );

function InflateFlush(var S: TInflateBlocksState; var Z: TZState; R: Integer): Integer;

// copies as much as possible from the sliding window to the output area

var
  N: Cardinal;
  P: PByte;
  Q: PByte;

begin
  // local copies of source and destination pointers
  P := Z.NextOutput;
  Q := S.Read;

  // compute number of bytes to copy as far as end of window 
  if Cardinal(Q) <= Cardinal(S.Write) then N := Cardinal(S.Write) - Cardinal(Q)
                                      else N := Cardinal(S.zend) - Cardinal(Q);
  if N > Z.AvailableOutput then N := Z.AvailableOutput;
  if (N <> 0) and (R = Z_BUF_ERROR) then R := Z_OK;

  // update counters 
  Dec(Z.AvailableOutput, N);
  Inc(Z.TotalOutput, N);

  // update check information
  if Assigned(S.CheckFunction) then
  begin
    S.Check := S.CheckFunction(S.Check, Q, N);
    Z.Adler := S.Check;
  end;

  // copy as far as end of Window 
  Move(Q^, P^, N);
  Inc(P, N);
  Inc(Q, N);

  // see if more to copy at beginning of window 
  if Q = S.zend then
  begin
    // wrap pointers
    Q := S.Window;
    if S.write = S.zend then S.write := S.Window;

    // compute bytes to copy 
    N := Cardinal(S.write) - Cardinal(Q);
    if N > Z.AvailableOutput then N := Z.AvailableOutput;
    if (N <> 0) and (R = Z_BUF_ERROR) then R := Z_OK;

    // update counters 
    Dec(Z.AvailableOutput, N);
    Inc(Z.TotalOutput, N);

    // update check information
    if Assigned(S.CheckFunction) then
    begin
      S.Check := S.CheckFunction(S.Check, Q, N);
      Z.Adler := S.Check;
    end;

    // copy 
    Move(Q^, P^, N);
    Inc(P, N);
    Inc(Q, N);
  end;

  // update pointers
  Z.NextOutput := P;
  S.Read := Q;

  Result := R;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateFast(LiteralBits, DistanceBits: Cardinal; TL, TD: PInflateHuft; var S: TInflateBlocksState; var Z: TZState): Integer;

// Called with number of bytes left to write in window at least 258 (the maximum string length) and number of input
// bytes available at least ten. The ten bytes are six bytes for the longest length/distance pair plus four bytes for
// overloading the bit buffer.

var
  Temp: PInflateHuft;
  Extra: Cardinal;       // extra bits or operation
  BitsBuffer: Cardinal;
  K: Cardinal;           // bits in bit buffer
  P: PByte;              // input data pointer
  N: Cardinal;           // bytes available there
  Q: PByte;              // output window write pointer
  M: Cardinal;           // bytes to end of window or read pointer
  ml: Cardinal;          // mask for literal/length tree
  md: Cardinal;          // mask for distance tree
  C: Cardinal;           // bytes to copy
  D: Cardinal;           // distance back to copy from
  R: PByte;              // copy source pointer

begin
  // load input, output, bit values  
  P := Z.NextInput;
  N := Z.AvailableInput;
  BitsBuffer := S.bitb;
  K := S.bitk;
  Q := S.write;
  if Cardinal(Q) < Cardinal(S.Read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                    else M := Cardinal(S.zend)-Cardinal(Q);

  // initialize masks 
  ml := InflateMask[LiteralBits];
  md := InflateMask[DistanceBits];

  // do until not enough input or output space for fast loop,
  // assume called with (M >= 258) and (N >= 10)
  repeat
    // get literal/length Code
    while K < 20 do
    begin
      Dec(N);
      BitsBuffer := BitsBuffer or (Cardinal(P^) shl K);
      Inc(P);
      Inc(K, 8);
    end;

    Temp := @PHuftField(TL)[BitsBuffer and ml];

    Extra := Temp.exop;
    if Extra = 0 then
    begin
      BitsBuffer := BitsBuffer shr Temp.Bits;
      Dec(K, Temp.Bits);
      Q^ := Temp.Base;
      Inc(Q);
      Dec(M);
      Continue;
    end;

    repeat
      BitsBuffer := BitsBuffer shr Temp.Bits;
      Dec(K, Temp.Bits);

      if (Extra and 16) <> 0 then
      begin
        // get extra bits for length 
        Extra := Extra and 15;
        C := Temp.Base + (BitsBuffer and InflateMask[Extra]);
        BitsBuffer := BitsBuffer shr Extra;
        Dec(K, Extra);
        // decode distance base of block to copy 
        while K < 15 do
        begin
          Dec(N);
          BitsBuffer := BitsBuffer or (Cardinal(P^) shl K);
          Inc(P);
          Inc(K, 8);
        end;

        Temp := @PHuftField(TD)[BitsBuffer and md];
        Extra := Temp.exop;
        repeat
          BitsBuffer := BitsBuffer shr Temp.Bits;
          Dec(K, Temp.Bits);

          if (Extra and 16) <> 0 then
          begin
            // get extra bits to add to distance base 
            Extra := Extra and 15;
            while K < Extra do
            begin
              Dec(N);
              BitsBuffer := BitsBuffer or (Cardinal(P^) shl K);
              Inc(P);
              Inc(K, 8);
            end;

            D := Temp.Base + (BitsBuffer and InflateMask[Extra]);
            BitsBuffer := BitsBuffer shr Extra;
            Dec(K, Extra);

            // do the copy 
            Dec(M, C);
            // offset before Dest
            if (Cardinal(Q) - Cardinal(S.Window)) >= D then
            begin
              //  just copy 
              R := Q;
              Dec(R, D);
              Q^ := R^;  Inc(Q); Inc(R); Dec(C); // minimum count is three,
              Q^ := R^;  Inc(Q); Inc(R); Dec(C); // so unroll loop a little
            end
            else
            begin
              // offset after destination,
              // bytes from offset to end
              Extra := D - (Cardinal(Q) - Cardinal(S.Window));
              R := S.zend;
              // pointer to offset
              Dec(R, Extra);
              if C > Extra then
              begin
                // copy to end of window
                Dec(C, Extra);
                repeat
                  Q^ := R^;
                  Inc(Q);
                  Inc(R);
                  Dec(Extra);
                until Extra = 0;
                // copy rest from start of window
                R := S.Window;
              end;
            end;

            // copy all or what's left
            repeat
              Q^ := R^;
              Inc(Q);
              Inc(R);
              Dec(C);
            until C = 0;
            Break;
          end
          else
            if (Extra and 64) = 0 then
            begin
              Inc(Temp, Temp.Base + (BitsBuffer and InflateMask[Extra]));
              Extra := Temp.exop;
            end
          else
          begin
            Z.Msg := SInvalidDistanceCode;
            C := Z.AvailableInput - N;
            if (K shr 3) < C then C := K shr 3;
            Inc(N, C);
            Dec(P, C);
            Dec(K, C shl 3);
            S.bitb := BitsBuffer;
            S.bitk := K;
            Z.AvailableInput := N;
            Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
            Z.NextInput := P;
            S.write := Q;
            Result := Z_DATA_ERROR;
            Exit;
          end;
        until False;
        Break;
      end;

      if (Extra and 64) = 0 then
      begin
        Inc(Temp, Temp.Base + (BitsBuffer and InflateMask[Extra]));
        Extra := Temp.exop;
        if Extra = 0 then
        begin
          BitsBuffer := BitsBuffer shr Temp.Bits;
          Dec(K, Temp.Bits);

          Q^ := Temp.Base;
          Inc(Q);
          Dec(M);
          Break;
        end;
      end
      else
        if (Extra and 32) <> 0 then
        begin
          C := Z.AvailableInput - N;
          if (K shr 3) < C then C := K shr 3;
          Inc(N, C);
          Dec(P, C);
          Dec(K, C shl 3);
          S.bitb := BitsBuffer;
          S.bitk := K;
          Z.AvailableInput := N;
          Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
          Z.NextInput := P;
          S.write := Q;
          Result := Z_STREAM_END;
          Exit;
        end
        else
        begin
          Z.Msg := SInvalidLengthCode;
          C := Z.AvailableInput - N;
          if (K shr 3) < C then C := K shr 3;
          Inc(N, C);
          Dec(P, C);
          Dec(K, C shl 3);
          S.bitb := BitsBuffer;
          S.bitk := K;
          Z.AvailableInput := N;
          Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
          Z.NextInput := P;
          S.write := Q;
          Result := Z_DATA_ERROR;
          Exit;
        end;
    until False;
  until (M < 258) or (N < 10);

  // not enough input or output -> restore pointers and return 
  C := Z.AvailableInput - N;
  if (K shr 3) < C then C := K shr 3;
  Inc(N, C);
  Dec(P, C);
  Dec(K, C shl 3);
  S.bitb := BitsBuffer;
  S.bitk := K;
  Z.AvailableInput := N;
  Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
  Z.NextInput := P;
  S.write := Q;
  Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateCodesNew(LiteralBits: Cardinal; DistanceBits: Cardinal; TL, TD: PInflateHuft;
  var Z: TZState): PInflateCodesState;

begin
  Result := AllocMem(SizeOf(TInflateCodesState));
  Result.Mode := icmStart;
  Result.LiteralTreeBits := LiteralBits;
  Result.DistanceTreeBits := DistanceBits;
  Result.LiteralTree := TL;
  Result.DistanceTree := TD;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateCodes(var S: TInflateBlocksState; var Z: TZState; R: Integer): Integer;

var
  J: Cardinal;          // temporary storage
  Temp: PInflateHuft;
  Extra: Cardinal;      // extra bits or operation 
  BitsBuffer: Cardinal;
  K: Cardinal;          // bits in bit buffer 
  P: PByte;             // input data pointer 
  N: Cardinal;          // bytes available there
  Q: PByte;             // output window write pointer
  M: Cardinal;          // bytes to end of window or read pointer
  F: PByte;             // pointer to copy strings from 
  C: PInflateCodesState;
  
begin
  C := S.sub.decode.codes;  // codes state 

  // copy input/output information to locals 
  P := Z.NextInput;
  N := Z.AvailableInput;
  BitsBuffer := S.bitb;
  K := S.bitk;
  Q := S.write;
  if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                    else M := Cardinal(S.zend)-Cardinal(Q);

  // process input and output based on current state
  while True do
  begin
    case C.Mode of
      icmStart:
        begin
          if (M >= 258) and (N >= 10) then
          begin
            S.bitb := BitsBuffer;
            S.bitk := K;
            Z.AvailableInput := N;
            Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
            Z.NextInput := P;
            S.write := Q;

            R := InflateFast(C.LiteralTreeBits, C.DistanceTreeBits, C.LiteralTree, C.DistanceTree, S, Z);
            P := Z.NextInput;
            N := Z.AvailableInput;
            BitsBuffer := S.bitb;
            K := S.bitk;
            Q := S.write;
            if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                              else M := Cardinal(S.zend) - Cardinal(Q);

            if R <> Z_OK then
            begin
              if R = Z_STREAM_END then C.mode := icmWash
                                  else C.mode := icmBadCode;
              Continue;    
            end;
          end;
          C.sub.Code.need := C.LiteralTreeBits;
          C.sub.Code.Tree := C.LiteralTree;
          C.mode := icmLen;   
        end;
      icmLen: // I: get length/literal/eob next
        begin
          J := C.sub.Code.need;
          while K < J do
          begin
            if N <> 0 then R := Z_OK
                      else
            begin
              S.bitb := BitsBuffer;
              S.bitk := K;
              Z.AvailableInput := N;
              Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
              Z.NextInput := P;
              S.write := Q;
              Result := InflateFlush(S, Z, R);
              Exit;
            end;
            Dec(N);
            BitsBuffer := BitsBuffer or (Cardinal(P^) shl K);
            Inc(P);
            Inc(K, 8);
          end;
          Temp := C.sub.Code.Tree;
          Inc(Temp, Cardinal(BitsBuffer) and InflateMask[J]);
          BitsBuffer := BitsBuffer shr Temp.Bits;
          Dec(K, Temp.Bits);

          Extra := Temp.exop;
          // literal
          if Extra = 0 then
          begin
            C.sub.lit := Temp.Base;
            C.mode := icmLit;
            Continue;   
          end;
          // length
          if (Extra and 16) <> 0 then
          begin
            C.sub.copy.get := Extra and 15;
            C.Len := Temp.Base;
            C.mode := icmLenNext;
            Continue;
          end;
          // next table
          if (Extra and 64) = 0 then
          begin
            C.sub.Code.need := Extra;
            C.sub.Code.Tree := @PHuftField(Temp)[Temp.Base];
            Continue;          
          end;
          // end of block
          if (Extra and 32) <> 0 then
          begin
            C.mode := icmWash;
            Continue;          
          end;
          // invalid code
          C.mode := icmBadCode;
          Z.Msg := SInvalidLengthCode;
          R := Z_DATA_ERROR;
          S.bitb := BitsBuffer;
          S.bitk := K;
          Z.AvailableInput := N;
          Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
          Z.NextInput := P;
          S.write := Q;
          Result := InflateFlush(S, Z, R);
          Exit;
        end;
      icmLenNext: // I: getting length extra (have base)
        begin
          J := C.sub.copy.get;
          while K < J do
          begin
            if N <> 0 then R := Z_OK
                      else
            begin
              S.bitb := BitsBuffer;
              S.bitk := K;
              Z.AvailableInput := N;
              Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
              Z.NextInput := P;
              S.write := Q;
              Result := InflateFlush(S, Z, R);
              Exit;
            end;
            Dec(N);
            BitsBuffer := BitsBuffer or (Cardinal(P^) shl K);
            Inc(P);
            Inc(K, 8);
          end;
          Inc(C.Len, Cardinal(BitsBuffer and InflateMask[J]));
          BitsBuffer := BitsBuffer shr J;
          Dec(K, J);

          C.sub.Code.need := C.DistanceTreeBits;
          C.sub.Code.Tree := C.DistanceTree;
          C.mode := icmDistance;
        end;
      icmDistance: // I: get distance next 
        begin
          J := C.sub.Code.need;
          while K < J do
          begin
            if N <> 0 then R := Z_OK
                      else
            begin
              S.bitb := BitsBuffer;
              S.bitk := K;
              Z.AvailableInput := N;
              Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
              Z.NextInput := P;
              S.write := Q;
              Result := InflateFlush(S, Z, R);
              Exit;
            end;
            Dec(N);
            BitsBuffer := BitsBuffer or (Cardinal(P^) shl K);
            Inc(P);
            Inc(K, 8);
          end;
          Temp := @PHuftField(C.sub.Code.Tree)[BitsBuffer and InflateMask[J]];
          BitsBuffer := BitsBuffer shr Temp.Bits;
          Dec(K, Temp.Bits);

          Extra := Temp.exop;
          // distance
          if (Extra and 16) <> 0 then
          begin
            C.sub.copy.get := Extra and 15;
            C.sub.copy.Distance := Temp.Base;
            C.mode := icmDistExt;
            Continue;
          end;
          // next table
          if (Extra and 64) = 0 then
          begin
            C.sub.Code.need := Extra;
            C.sub.Code.Tree := @PHuftField(Temp)[Temp.Base];
            Continue;      
          end;
          // invalid code
          C.mode := icmBadCode;
          Z.Msg := SInvalidDistanceCode;
          R := Z_DATA_ERROR;
          S.bitb := BitsBuffer;
          S.bitk := K;
          Z.AvailableInput := N;
          Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
          Z.NextInput := P;
          S.write := Q;
          Result := InflateFlush(S, Z, R);
          Exit;
        end;
      icmDistExt: // I: getting distance extra
        begin
          J := C.sub.copy.get;
          while K < J do
          begin
            if N <> 0 then R := Z_OK
                      else
            begin
              S.bitb := BitsBuffer;
              S.bitk := K;
              Z.AvailableInput := N;
              Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
              Z.NextInput := P;
              S.write := Q;
              Result := InflateFlush(S, Z, R);
              Exit;
            end;
            Dec(N);
            BitsBuffer := BitsBuffer or (Cardinal(P^) shl K);
            Inc(P);
            Inc(K, 8);
          end;
          Inc(C.sub.copy.Distance, Cardinal(BitsBuffer) and InflateMask[J]);
          BitsBuffer := BitsBuffer shr J;
          Dec(K, J);
          C.mode := icmCopy;
        end;
      icmCopy: // O: copying bytes in window, waiting for space
        begin
          F := Q;
          Dec(F, C.sub.copy.Distance);
          if (Cardinal(Q) - Cardinal(S.Window)) < C.sub.copy.Distance then
          begin
            F := S.zend;
            Dec(F, C.sub.copy.Distance - (Cardinal(Q) - Cardinal(S.Window)));
          end;

          while C.Len <> 0 do
          begin
            if M = 0 then
            begin
              if (Q = S.zend) and (S.read <> S.Window) then
              begin
                Q := S.Window;
                if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                  else M := Cardinal(S.zend)-Cardinal(Q);
              end;

              if M = 0 then
              begin
                S.write := Q;
                R := InflateFlush(S, Z, R);
                Q := S.write;
                if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                  else M := Cardinal(S.zend) - Cardinal(Q);

                if (Q = S.zend) and (S.read <> S.Window) then
                begin
                  Q := S.Window;
                  if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                    else M := Cardinal(S.zend) - Cardinal(Q);
                end;

                if M = 0 then
                begin
                  S.bitb := BitsBuffer;
                  S.bitk := K;
                  Z.AvailableInput := N;
                  Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
                  Z.NextInput := P;
                  S.write := Q;
                  Result := InflateFlush(S, Z, R);
                  Exit;
                end;
              end;
            end;
            R := Z_OK;

            Q^ := F^;
            Inc(Q);
            Inc(F);
            Dec(M);

            if (F = S.zend) then F := S.Window;
            Dec(C.Len);
          end;
          C.mode := icmStart;
        end;
      icmLit: // O: got literal, waiting for output space
        begin
          if M = 0 then
          begin
            if (Q = S.zend) and (S.read <> S.Window) then
            begin
              Q := S.Window;
              if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                else M := Cardinal(S.zend) - Cardinal(Q);
            end;

            if M = 0 then
            begin
              S.write := Q;
              R := InflateFlush(S, Z, R);
              Q := S.write;
              if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                else M := Cardinal(S.zend) - Cardinal(Q);

              if (Q = S.zend) and (S.read <> S.Window) then
              begin
                Q := S.Window;
                if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                  else M := Cardinal(S.zend) - Cardinal(Q);
              end;

              if M = 0 then
              begin
                S.bitb := BitsBuffer;
                S.bitk := K;
                Z.AvailableInput := N;
                Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
                Z.NextInput := P;
                S.write := Q;
                Result := InflateFlush(S, Z, R);
                Exit;
              end;
            end;
          end;
          R := Z_OK;
          Q^ := C.sub.lit;
          Inc(Q);
          Dec(M);
          C.mode := icmStart;
        end;
      icmWash: // O: got eob, possibly More output
        begin
          // return unused byte, if any
          if K > 7 then
          begin
            Dec(K, 8);
            Inc(N);
            Dec(P);
            // can always return one
          end;
          S.write := Q;
          R := InflateFlush(S, Z, R);
          Q := S.write;
          if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                            else M := Cardinal(S.zend) - Cardinal(Q);

          if S.read <> S.write then
          begin
            S.bitb := BitsBuffer;
            S.bitk := K;
            Z.AvailableInput := N;
            Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
            Z.NextInput := P;
            S.write := Q;
            Result := InflateFlush(S, Z, R);
            Exit;
          end;
          C.mode := icmZEnd;
        end;
      icmZEnd:
        begin
          R := Z_STREAM_END;
          S.bitb := BitsBuffer;
          S.bitk := K;
          Z.AvailableInput := N;
          Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
          Z.NextInput := P;
          S.write := Q;
          Result := InflateFlush(S, Z, R);
          Exit;
        end;
      icmBadCode: // X: got error
        begin
          R := Z_DATA_ERROR;
          S.bitb := BitsBuffer;
          S.bitk := K;
          Z.AvailableInput := N;
          Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
          Z.NextInput := P;
          S.write := Q;
          Result := InflateFlush(S, Z, R);
          Exit;
        end;
    else
      begin
        R := Z_STREAM_ERROR;
        S.bitb := BitsBuffer;
        S.bitk := K;
        Z.AvailableInput := N;
        Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
        Z.NextInput := P;
        S.write := Q;
        Result := InflateFlush(S, Z, R);
        Exit;
      end;
    end;
  end;
  
  Result := Z_STREAM_ERROR;
end;

//----------------------------------------------------------------------------------------------------------------------

const
  // Maximum Size of dynamic tree. The maximum found in an integer but non-exhaustive search was 1004 huft structures
  // (850 for length/literals and 154 for distances, the latter actually the result of an exhaustive search).
  // The actual maximum is not known, but the value below is more than safe. 
  MANY = 1440;

  // Tables for deflate from PKZIP'S appnote.txt
  // copy lengths for literal codes 257..285 (actually lengths - 2; also see note #13 above about 258)
  CopyLengths: array [0..30] of Cardinal = (
    3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35,
    43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  );

  INVALID_CODE = 112;
  // extra bits for literal codes 257..285
  CopyLiteralExtra: array [0..30] of Cardinal = (
    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, INVALID_CODE, INVALID_CODE
  );

  // copy offsets for distance codes 0..29
  CopyOffsets: array [0..29] of Cardinal = (
    1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385,
    513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577
  );

  // extra bits for distance codes
  CopyExtra: array [0..29] of Cardinal = (
    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
  );

  // Huffman code decoding is performed using a multi-Level table lookup.
  // Fastest way to decode is to simply build a lookup table whose
  // size is determined by the longest code. However, the time it takes
  // to build this table can also be a factor if the data being decoded
  // is not very integer. The most common codes are necessarily the
  // shortest codes so those codes dominate the decoding time and hence
  // the speed. The idea is you can have a shorter table that decodes the
  // shorter, More probable codes, and then point to subsidiary tables for
  // the longer codes. The time it costs to decode the longer codes is
  // then traded against the time it takes to make longer tables.
  //
  // This results of this trade are in the variables LiteralTreeBits and DistanceTreeBits
  // below. LiteralTreeBits is the number of bits the first level table for literal/
  // length codes can decode in one step, and DistanceTreeBits is the same thing for
  // the distance codes. Subsequent tables are also less than or equal to those sizes.
  // These values may be adjusted either when all of the
  // codes are shorter than that, in which case the longest code length in
  // bits is used, or when the shortest code is *longer* than the requested
  // table size, in which case the length of the shortest code in bits is used.
  //
  // There are two different values for the two tables, since they code a
  // different number of possibilities each. The literal/length table
  // codes 286 possible values, or in a flat code, a little over eight
  // bits. The distance table codes 30 possible values, or a little less
  // than five bits, flat. The optimum values for speed end up being
  // about one bit more than those, so LiteralTreeBits is 8 + 1 and DistanceTreeBits is 5 + 1.
  // The optimum values may differ though from machine to machine, and possibly even between compilers. 

const
  // maximum bit length of any code,
  // If BMAX needs to be larger than 16, then H and X[] should be Cardinal.
  BMAX = 15;

//----------------------------------------------------------------------------------------------------------------------

function BuildHuffmanTables(const B: array of Cardinal; N, S: Cardinal; const D, Extra: array of Cardinal;
  Temp: PPInflateHuft; var M: Cardinal; var HP: array of TInflateHuft; var HN: Cardinal;
  var V: array of Cardinal): Integer;

// Given a list of code lengths and a maximum table size, make a set of tables to decode that set of codes. Returns Z_OK
// on success, Z_BUF_ERROR if the given code set is incomplete (the tables are still built in this case), Z_DATA_ERROR
// if the input is invalid (an over-subscribed set of lengths), or Z_MEM_ERROR if not enough memory.
//
// Input pareters:
// B contains the code lenths in bits (all assumed <= BMAX)
// N is the number of codes (<= NMAX)
// S is the number of simple valued codes (0..S - 1)
// D contains a list of base values for non-simple codes
// Extra carries a list of extra bits for non-simple codes
//
// Output parameters:
// Temp points to the starting table
// M receives the maxium lookup bits (actual space for trees)
// HP receives the Huffman tables
// while HN decribes how many of HP is actually used
// finally V is a working area which receives values in order of bit length

var
  A: Cardinal;                     // counter for codes of length K 
  C: array [0..BMAX] of Cardinal;  // bit length count table
  F: Cardinal;                     // I repeats in table every F entries
  G: Integer;                      // maximum code Length
  H: Integer;                      // table Level
  I: Cardinal;                     // counter, current code
  J: Cardinal;                     // counter
  K: Integer;                      // number of bits in current code
  L: Integer;			                 // bits per table (returned in M)
  Mask: Cardinal;                  // (1 shl W) - 1, to avoid cc - O bug on HP
  P: PCardinal;                    // pointer into C[], B[], or V[]
  Q: PInflateHuft;                 // points to current table
  R: TInflateHuft;                 // table entry for structure assignment
  U: array [0..BMAX - 1] of PInflateHuft; // table stack
  W: Integer;                      // bits before this table = (L * H)
  X: array [0..BMAX] of Cardinal;  // bit offsets, then code stack 
  XP: PCardinal;                   // pointer into X 
  Y: Integer;                      // number of dummy codes added 
  Z: Cardinal;                     // number of entries in current table 
  
Begin
  // generate counts for each bit length 
  FillChar(C, SizeOf(C), 0);    

  // assume all entries <= BMAX
  for I := 0 to N - 1 do Inc(C[B[I]]);

  // nil input -> all zero length codes
  if C[0] = N then
  Begin
    Temp^ := nil;
    M := 0 ;
    Result := Z_OK;
    Exit;
  end ;

  // find minimum and maximum length, bound [M] by those 
  L := M;
  for J := 1 to BMAX do
    if C[J] <> 0 then Break;
  // minimum code Length
  K := J ;
  if Cardinal(L) < J then L := J;
  for I := BMAX downto 1 do
    if C[I] <> 0 then Break;
  // maximum code length
  G := I ;
  if Cardinal(L) > I then L := I;
  M := L;

  // adjust last length count to fill out codes if needed
  Y := 1 shl J;
  while J < I do
  begin
    Dec(Y, C[J]);
    if Y < 0 then
    begin
      // bad input: more codes than bits
      Result := Z_DATA_ERROR;
      Exit;
    end ;
    Inc(J);
    Y := Y shl 1;
  end;
  Dec (Y, C[I]);
  if Y < 0 then
  begin
    // bad input: more codes than bits
    Result := Z_DATA_ERROR;
    Exit;
  end;
  Inc(C[I], Y);

  // generate starting offsets into the value table for each length
  X[1] := 0;
  J := 0;

  P := @C[1];
  XP := @X[2];
  // note that I = G from above
  Dec(I);
  while (I > 0) do
  begin
    Inc(J, P^);
    XP^ := J;
    Inc(P);
    Inc(XP);
    Dec(I);
  end;

  // make a table of values in order of bit lengths
  for I := 0 to N - 1 do
  begin
    J := B[I];
    if J <> 0 then
    begin
      V[X[J]] := I;
      Inc(X[J]);
    end;
  end;
  // set N to Length of V
  N := X[G];

  // generate the Huffman codes and for each make the table entries
  I := 0;
  // first Huffman code is zero
  X[0] := 0;
  // grab values in bit order
  P := @V;
  // no tables yet -> Level - 1
  H := -1;
  // bits decoded = (L * H)
  W := -L;

  U[0] := nil;
  Q := nil;
  Z := 0;        

  // go through the bit lengths (K already is bits in shortest code) 
  while K <= G Do
  begin
    A := C[K];
    while A <> 0 Do
    begin
      Dec(A);
      // here I is the Huffman code of length K bits for value P^ 
      // make tables up to required level 
      while K > W + L do
      begin
        Inc(H);
        // add bits already decoded, previous table always L Bits
        Inc(W, L);
        // compute minimum size table less than or equal to L bits
        Z := G - W;
        if Z > Cardinal(L) then Z := L;

        // try a K - W bit table
        J := K - W;
        F := 1 shl J;
        // too few codes for K - W bit table
        if F > A + 1 then
        begin
          // deduct codes from patterns left
          Dec(F,A + 1);
          XP := @C[K];
          if J < Z then
          begin
            Inc(J);
            while J < Z do
            begin
              // try smaller tables up to Z bits
              F := F shl 1;
              Inc(XP);
              // enough codes to use up J Bits
              if F <= XP^ then Break;
              // else deduct codes from patterns
              Dec(F, XP^);
              Inc(J);
            end;
          end;
        end;

        // table entries for J-bit table
        Z := 1 shl J;
        // allocate new table (note: doesn't matter for fixed)
        if HN + Z > MANY then
        begin
          Result := Z_MEM_ERROR;
          Exit;
        end;

        Q := @HP[HN];
        U[H] := Q;
        Inc(HN, Z);

        // connect to last table, if there is one 
        if H <> 0 then
        begin
          // save pattern for backing up
          X[H] := I;
          // bits to dump before this table
          R.Bits := L;
          // bits in this table
          R.exop := J;
          J := I shr (W - L);
          R.Base := (Cardinal(Q) - Cardinal(U[H - 1]) ) div SizeOf(Q^) - J;
          // connect to last table
          PHuftField(U[H - 1])[J] := R;
        end
        else
          // first table is returned result
          Temp^ := Q;
      end;

      // set up table entry in R 
      R.Bits := Byte(K - W);

      // out of values -> invalid code
      if Cardinal(P) >= Cardinal(@V[N]) then R.exop := 128 + 64
                                        else
        if P^ < S then
        begin
          // 256 is end-of-block code
          if P^ < 256 then R.exop := 0
                      else R.exop := 32 + 64;
          // simple code is just the value
          R.Base := P^;
          Inc(P);
        end
        else
        begin
          // non-simple -> look up in lists
          R.exop := Byte(Extra[P^ - S] + 16 + 64);
          R.Base := D[P^ - S];
          Inc (P);
        end;

      // fill xode-like entries with R
      F := 1 shl (K - W);
      J := I shr W;
      while J < Z do
      begin
        PHuftField(Q)[J] := R;
        Inc(J, F);
      end;

      // backwards increment the K-bit code I 
      J := 1 shl (K - 1) ;
      while (I and J) <> 0 do
      begin
        I := I xor J;         
        J := J shr 1
      end;
      I := I xor J;

      // backup over finished tables
      // needed on HP, cc -O bug
      Mask := (1 shl W) - 1;
      while (I and Mask) <> X[H] do
      begin
        // don't need to update Q
        Dec(H);
        Dec(W, L);
        Mask := (1 shl W) - 1;
      end;
    end;
    Inc(K);
  end;

  // Return Z_BUF_ERROR if we were given an incomplete table 
  if (Y <> 0) and (G <> 1) then Result := Z_BUF_ERROR
                           else Result := Z_OK;
end; 

//----------------------------------------------------------------------------------------------------------------------

function InflateTreesBits(var C: array of Cardinal; var BB: Cardinal; var TB: PInflateHuft;
  var HP: array of TInflateHuft; var Z: TZState): Integer;

// C holds 19 code lengths
// BB - bits tree desired/actual depth
// TB - bits tree result
// HP - space for trees
// Z - for messages

var
  R: Integer;
  HN: Cardinal;          // hufts used in space 
  V: PCardinalArray;     // work area for BuildHuffmanTables 

begin
  HN := 0;
  V := AllocMem(19 * SizeOf(Cardinal));
  try
    R := BuildHuffmanTables(C, 19, 19, CopyLengths, CopyLiteralExtra, @TB, BB, HP, HN, V^);
    if R = Z_DATA_ERROR then Z.Msg := SOversubscribedDBLTree
                        else
      if (R = Z_BUF_ERROR) or (BB = 0) then
      begin
        Z.Msg := SIncompleteDBLTree;
        R := Z_DATA_ERROR;
      end;
      
    Result := R;
  finally
    FreeMem(V);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateTreesDynamic(NL: Cardinal; ND: Cardinal; var C: array of Cardinal; var LiteralBits: Cardinal;
  var DistanceBits: Cardinal; var TL: PInflateHuft; var TD: PInflateHuft; var HP: array of TInflateHuft;
  var Z: TZState): Integer;

// NL - number of literal/length codes
// ND - number of distance codes
// C - code lengths
// LiteralBits - literal desired/actual bit depth
// DistanceBits - distance desired/actual bit depth
// TL - literal/length tree result
// TD - distance tree result
// HP - space for trees
// Z - for messages

var
  R: Integer;
  HN: Cardinal;          // hufts used in space
  V: PCardinalArray;     // work area for BuildHuffmanTables

begin
  HN := 0;
  // allocate work area
  V := AllocMem(288 * SizeOf(Cardinal));
  try
    Result := Z_OK;

    // build literal/length tree
    R := BuildHuffmanTables(C, NL, 257, CopyLengths, CopyLiteralExtra, @TL, LiteralBits, HP, HN, V^);
    if (R <> Z_OK) or (LiteralBits = 0) then
    begin
      if R = Z_DATA_ERROR then Z.Msg := SOversubscribedLLTree
                          else
        if R <> Z_MEM_ERROR then
        begin
          Z.Msg := SIncompleteLLTree;
          R := Z_DATA_ERROR;
        end;

      FreeMem(V);
      Result := R;
      Exit;
    end;

    // build distance tree
    R := BuildHuffmanTables(PCardinalArray(@C[NL])^, ND, 0, CopyOffsets, CopyExtra, @TD, DistanceBits, HP, HN, V^);
    if (R <> Z_OK) or ((DistanceBits = 0) and (NL > 257)) then
    begin
      if R = Z_DATA_ERROR then Z.Msg := SOversubscribedLLTree
                          else
        if R = Z_BUF_ERROR then
        begin
          Z.Msg := SIncompleteLLTree;
          R := Z_DATA_ERROR;
        end
        else
          if R <> Z_MEM_ERROR then
          begin
            Z.Msg := SEmptyDistanceTree;
            R := Z_DATA_ERROR;
          end;
      FreeMem(V);
      Result := R;
    end;
  finally
    FreeMem(V);
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

var
  // build fixed tables only once -> keep them here
  FixedBuild: Boolean = False;

const
  // number of hufts used by fixed tables
  FIXEDH = 544;
  
var
  FixedTablesMemory: array[0..FIXEDH - 1] of TInflateHuft;
  FixedLiteralBits: Cardinal;
  FixedDistanceBits: Cardinal;
  FixedLiteralTable: PInflateHuft;
  FixedDistanceTable: PInflateHuft;

//----------------------------------------------------------------------------------------------------------------------

function InflateTreesFixed(var LiteralBits: Cardinal; var DistanceBits: Cardinal; var TL, TD: PInflateHuft;
  var Z: TZState): Integer;

type
  PFixedTable = ^TFixedTable;
  TFixedTable = array[0..287] of Cardinal;

var
  K: Integer;        // temporary variable
  C: PFixedTable;    // length list for BuildHuffmanTables
  V: PCardinalArray; // work area for BuildHuffmanTables
  F: Cardinal;       // number of hufts used in FixedTablesMemory

begin
  // build fixed tables if not already (multiple overlapped executions ok) 
  if not FixedBuild then
  begin
    F := 0;
    C := nil;
    V := nil;

    try
      C := AllocMem(288 * SizeOf(Cardinal));
      V := AllocMem(288 * SizeOf(Cardinal));
      // literal table
      for K := 0 to 143 do C[K] := 8;
      for K := 144 to 255 do C[K] := 9;
      for K := 256 to 279 do C[K] := 7;
      for K := 280 to 287 do C[K] := 8;
      FixedLiteralBits := 9;
      BuildHuffmanTables(C^, 288, 257, CopyLengths, CopyLiteralExtra, @FixedLiteralTable, FixedLiteralBits,
                         FixedTablesMemory, F, V^);

      // distance table
      for K := 0 to 29 do C[K] := 5;
      FixedDistanceBits := 5;
      BuildHuffmanTables(C^, 30, 0, CopyOffsets, CopyExtra, @FixedDistanceTable, FixedDistanceBits, FixedTablesMemory,
                         F, V^);

      FixedBuild := True;
    finally
      if Assigned(V) then FreeMem(V);
      if Assigned(C) then FreeMem(C);
    end;
  end;
  LiteralBits := FixedLiteralBits;
  DistanceBits := FixedDistanceBits;
  TL := FixedLiteralTable;
  TD := FixedDistanceTable;
  Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

// tables for Deflate from PKZIP'S appnote.txt.
const
  // order of the bit length code lengths
  BitOrder: array [0..18] of Word = (
    16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15
  );

// Notes beyond the 1.93a appnote.txt:
// 1. Distance pointers never point before the beginning of the output stream.
// 2. Distance pointers can point back across blocks, up to 32k away.
// 3. There is an implied maximum of 7 Bits for the bit Length table and 15 Bits for the actual data.
// 4. if only one Code exists, then it is encoded using one bit. (zero would be more efficient, but perhaps a little
//    confusing.) If two codes exist, they are coded using one bit each (0 and 1).
// 5. There is no way of sending zero distance codes -> a dummy must be sent if there are none. (History: a pre 2.0
//    Version of PKZIP would store blocks with no distance codes, but this was discovered to be
//    too harsh a criterion.) Valid only for 1.93a. 2.04c does allow zero distance codes, which is sent as one Code of
//    zero Bits in length.
// 6. There are up to 286 literal/Length codes. Code 256 represents the end-of-block. Note however that the static
//    length Tree defines 288 codes just to fill out the Huffman codes. Codes 286 and 287 cannot be used though, since
//    there is no length base or extra bits defined for them. Similarily, there are up to 30 distance codes. However,
//    static trees defines 32 codes (all 5 Bits) to fill out the Huffman codes, but the last two had better not show up
//    in the data.
// 7. Unzip can check dynamic Huffman blocks for complete code sets. The exception is that a single code would not be
//    complete (see #4).
// 8. The five Bits following the block type is really the number of literal codes sent minus 257.
// 9. Length codes 8, 16, 16 are interpreted as 13 Length codes of 8 bits (1 + 6 + 6). Therefore, to output three times
//    the length, you output three codes (1 + 1 + 1), whereas to output four times the same length,
//    you only need two codes (1+3).  Hmm.
// 10. In the tree reconstruction algorithm, Code = Code + Increment only if BitLength(I) is not zero (pretty obvious).
// 11. Correction: 4 Bits: # of Bit Length codes - 4 (4 - 19)
// 12. Note: length code 284 can represent 227 - 258, but length code 285 really is 258. The last length deserves its
//     own, short code since it gets used a lot in very redundant files. The length 258 is special since 258 - 3 (the
//     min match length) is 255.
// 13. The literal/length and distance code bit lengths are read as a single stream of lengths.  It is possible (and
//     advantageous) for a repeat code (16, 17, or 18) to go across the boundary between the two sets of lengths.
//----------------------------------------------------------------------------------------------------------------------

procedure InflateBlockReset(var S: TInflateBlocksState; var Z: TZState; C: PCardinal);

begin
  if Assigned(C) then C^ := S.Check;
  if (S.mode = ibmBitTree) or (S.mode = ibmDistTree) then FreeMem(S.sub.trees.blens);
  if S.mode = ibmCodes then FreeMem(S.sub.decode.codes);

  S.mode := ibmZType;
  S.bitk := 0;
  S.bitb := 0;

  S.write := S.Window;
  S.read := S.Window;
  if Assigned(S.CheckFunction) then
  begin
    S.Check := S.CheckFunction(0, nil, 0);
    Z.Adler := S.Check;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateBlocksNew(var Z: TZState; C: TCheckFunction; W: Cardinal): PInflateBlocksState;

// W is the window size

var
  S: PInflateBlocksState;

begin
  S := AllocMem(SizeOf(TInflateBlocksState));
  if S = nil then Result := S
             else
  try
    S.hufts := AllocMem(SizeOf(TInflateHuft) * MANY);

    S.Window := AllocMem(W);
    S.zend := S.Window;
    Inc(S.zend, W);
    S.CheckFunction := C;
    S.mode := ibmZType;
    InflateBlockReset(S^, Z, nil);
    Result := S;
  except
    if Assigned(S.Window) then FreeMem(S.Window);
    if Assigned(S.hufts) then FreeMem(S.hufts);
    FreeMem(S);
    raise;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateBlocks(var S: TInflateBlocksState; var Z: TZState; R: Integer): Integer;

// R contains the initial return code
                         
var
  Temp: Cardinal;
  B: Cardinal;    // bit buffer
  K: Cardinal;    // bits in bit buffer
  P: PByte;       // input data pointer
  N: Cardinal;    // bytes available there
  Q: PByte;       // output Window write pointer
  M: Cardinal;    // bytes to end of window or read pointer 
  // fixed code blocks 
  LiteralBits,
  DistanceBits: Cardinal;
  TL,
  TD: PInflateHuft;
  H: PInflateHuft;
  I, J, C: Cardinal;
  CodeState: PInflateCodesState;

  //--------------- local functions -------------------------------------------

  function UpdatePointers: Integer;

  begin
    S.bitb := B;
    S.bitk := K;
    Z.AvailableInput := N;
    Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
    Z.NextInput := P;
    S.write := Q;
    Result := InflateFlush(S, Z, R);
  end;

  //--------------- end local functions ---------------------------------------

begin
  // copy input/output information to locals 
  P := Z.NextInput;
  N := Z.AvailableInput;
  B := S.bitb;
  K := S.bitk;
  Q := S.write;
  if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                    else M := Cardinal(S.zend) - Cardinal(Q);

  // decompress an inflated block 
  // process input based on current state
  while True do
  begin
    case S.mode of
      ibmZType:
        begin
          while K < 3 do
          begin
            if N <> 0 then R := Z_OK
                      else
            begin
              Result := UpdatePointers;
              Exit;
            end;
            Dec(N);
            B := B or (Cardinal(P^) shl K);
            Inc(P);
            Inc(K, 8);
          end;

          Temp := B and 7;
          S.last := Boolean(Temp and 1);
          case Temp shr 1 of
            0: // stored
              begin
                B := B shr 3;
                Dec(K, 3);
                // go to byte boundary
                Temp := K and 7;
                B := B shr Temp;
                Dec(K, Temp);
                // get length of stored block
                S.mode := ibmLens;
              end;
            1: // fixed
              begin
                InflateTreesFixed(LiteralBits, DistanceBits, TL, TD, Z);
                S.sub.decode.codes := InflateCodesNew(LiteralBits, DistanceBits, TL, TD, Z);
                if S.sub.decode.codes = nil then
                begin
                  R := Z_MEM_ERROR;
                  Result := UpdatePointers;
                  Exit;
                end;
                B := B shr 3;
                Dec(K, 3);
                S.mode := ibmCodes;
              end;
            2: // dynamic
              begin
                B := B shr 3;
                Dec(K, 3);
                S.mode := ibmTable;
              end;
            3: // illegal
              begin
                B := B shr 3;
                Dec(K, 3);
                S.mode := ibmBlockBad;
                Z.Msg := SInvalidBlockType;
                R := Z_DATA_ERROR;
                Result := UpdatePointers;
                Exit;
              end;
          end;
        end;
      ibmLens:
        begin
          while K < 32 do
          begin
            if N <> 0 then R := Z_OK
                      else
            begin
              Result := UpdatePointers;
              Exit;
            end;
            Dec(N);
            B := B or (Cardinal(P^) shl K);
            Inc(P);
            Inc(K, 8);
          end;

          if (((not B) shr 16) and $FFFF) <> (B and $FFFF) then
          begin
            S.mode := ibmBlockBad;
            Z.Msg := SInvalidStoredBlockLengths;
            R := Z_DATA_ERROR;
            Result := UpdatePointers;
            Exit;
          end;
          S.sub.left := B and $FFFF;
          K := 0;
          B := 0;
          if S.sub.left <> 0 then S.mode := ibmStored
                             else
            if S.last then S.mode := ibmDry
                      else S.mode := ibmZType;
        end;
      ibmStored:
        begin
          if N = 0 then
          begin
            Result := UpdatePointers;
            Exit;
          end;

          if M = 0 then
          begin
            if (Q = S.zend) and (S.read <> S.Window) then
            begin
              Q := S.Window;
              if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                else M := Cardinal(S.zend) - Cardinal(Q);
            end;

            if M = 0 then
            begin
              S.write := Q;
              R := InflateFlush(S, Z, R);
              Q := S.write;
              if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                else M := Cardinal(S.zend) - Cardinal(Q);
              if (Q = S.zend) and (S.read <> S.Window) then
              begin
                Q := S.Window;
                if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                                  else M := Cardinal(S.zend) - Cardinal(Q);
              end;

              if M = 0 then
              begin
                Result := UpdatePointers;
                Exit;
              end;
            end;
          end;
          R := Z_OK;

          Temp := S.sub.left;
          if Temp > N then Temp := N;
          if Temp > M then Temp := M;
          Move(P^, Q^, Temp);
          Inc(P, Temp);
          Dec(N, Temp);
          Inc(Q, Temp);
          Dec(M, Temp);
          Dec(S.sub.left, Temp);
          if S.sub.left = 0 then
          begin
            if S.last then S.mode := ibmDry
                      else S.mode := ibmZType;
          end;
        end;
      ibmTable:
        begin
          while K < 14 do
          begin
            if N <> 0 then R := Z_OK
                      else
            begin
              Result := UpdatePointers;
              Exit;
            end;
            Dec(N);
            B := B or (Cardinal(P^) shl K);
            Inc(P);
            Inc(K, 8);
          end;

          Temp := B and $3FFF;
          S.sub.trees.table := Temp;
          if ((Temp and $1F) > 29) or (((Temp shr 5) and $1F) > 29) then
          begin
            S.mode := ibmBlockBad;
            Z.Msg := STooManyLDSymbols;
            R := Z_DATA_ERROR;
            Result := UpdatePointers;
            Exit;
          end;
          Temp := 258 + (Temp and $1F) + ((Temp shr 5) and $1F);
          try
            S.sub.trees.blens := AllocMem(Temp * SizeOf(Cardinal));
          except
            R := Z_MEM_ERROR;
            UpdatePointers;
            raise;
          end;
          B := B shr 14;
          Dec(K, 14);

          S.sub.trees.Index := 0;
          S.mode := ibmBitTree;
        end;
      ibmBitTree:
        begin
          while (S.sub.trees.Index < 4 + (S.sub.trees.table shr 10)) do
          begin
            while K < 3 do
            begin
              if N <> 0 then R := Z_OK
                        else
              begin
                Result := UpdatePointers;
                Exit;
              end;
              Dec(N);
              B := B or (Cardinal(P^) shl K);
              Inc(P);
              Inc(K, 8);
            end;

            S.sub.trees.blens[BitOrder[S.sub.trees.Index]] := B and 7;
            Inc(S.sub.trees.Index);
            B := B shr 3;
            Dec(K, 3);
          end;

          while S.sub.trees.Index < 19 do
          begin
            S.sub.trees.blens[BitOrder[S.sub.trees.Index]] := 0;
            Inc(S.sub.trees.Index);
          end;
          S.sub.trees.BB := 7;
          Temp := InflateTreesBits(S.sub.trees.blens^, S.sub.trees.BB, S.sub.trees.TB, S.hufts^, Z);
          if Temp <> Z_OK then
          begin
            FreeMem(S.sub.trees.blens);
            R := Temp;
            if R = Z_DATA_ERROR then S.mode := ibmBlockBad;
            Result := UpdatePointers;
            Exit;
          end;
          S.sub.trees.Index := 0;
          S.mode := ibmDistTree;
        end;
      ibmDistTree:
        begin
          while True do
          begin
            Temp := S.sub.trees.table;
            if not (S.sub.trees.Index < 258 + (Temp and $1F) + ((Temp shr 5) and $1F)) then Break;
            Temp := S.sub.trees.BB;
            while K < Temp do
            begin
              if N <> 0 then R := Z_OK
                        else
              begin
                Result := UpdatePointers;
                Exit;
              end;
              Dec(N);
              B := B or (Cardinal(P^) shl K);
              Inc(P);
              Inc(K, 8);
            end;

            H := S.sub.trees.TB;
            Inc(H, B and InflateMask[Temp]);
            Temp := H^.Bits;
            C := H^.Base;

            if C < 16 then
            begin
              B := B shr Temp;
              Dec(K, Temp);
              S.sub.trees.blens^[S.sub.trees.Index] := C;
              Inc(S.sub.trees.Index);
            end
            else
            begin
              // C = 16..18
              if C = 18 then
              begin
                I := 7;
                J := 11;
              end
              else
              begin
                I := C - 14;
                J := 3;
              end;

              while K < Temp + I do
              begin
                if N <> 0 then R := Z_OK
                          else
                begin
                  Result := UpdatePointers;
                  Exit;
                end;
                Dec(N);
                B := B or (Cardinal(P^) shl K);
                Inc(P);
                Inc(K, 8);
              end;

              B := B shr Temp;
              Dec(K, Temp);

              Inc(J, Cardinal(B) and InflateMask[I]);
              B := B shr I;
              Dec(K, I);

              I := S.sub.trees.Index;
              Temp := S.sub.trees.table;
              if (I + J > 258 + (Temp and $1F) + ((Temp shr 5) and $1F)) or ((C = 16) and (I < 1)) then
              begin
                FreeMem(S.sub.trees.blens);
                S.mode := ibmBlockBad;
                Z.Msg := SInvalidBitLengthRepeat;
                R := Z_DATA_ERROR;
                Result := UpdatePointers;
                Exit;
              end;

              if C = 16 then C := S.sub.trees.blens[I - 1]
                        else C := 0;
              repeat
                S.sub.trees.blens[I] := C;
                Inc(I);
                Dec(J);
              until J = 0;
              S.sub.trees.Index := I;
            end;
          end; // while

          S.sub.trees.TB := nil;
          begin
            LiteralBits := 9;
            DistanceBits := 6;
            Temp := S.sub.trees.table;
            Temp := InflateTreesDynamic(257 + (Temp and $1F), 1 + ((Temp shr 5) and $1F),
                                        S.sub.trees.blens^, LiteralBits, DistanceBits, TL, TD, S.hufts^, Z);
            FreeMem(S.sub.trees.blens);
            if Temp <> Z_OK then
            begin
              if Integer(Temp) = Z_DATA_ERROR then S.mode := ibmBlockBad;
              R := Temp;
              Result := UpdatePointers;
              Exit;
            end;
            CodeState := InflateCodesNew(LiteralBits, DistanceBits, TL, TD, Z);
            if CodeState = nil then
            begin
              R := Z_MEM_ERROR;
              Result := UpdatePointers;
              Exit;
            end;
            S.sub.decode.codes := CodeState;
          end;
          S.mode := ibmCodes;
        end;
      ibmCodes:
        begin
          // update pointers
          S.bitb := B;
          S.bitk := K;
          Z.AvailableInput := N;
          Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
          Z.NextInput := P;
          S.write := Q;
          R := InflateCodes(S, Z, R);

          // very strange, I have no clue why the local function does not work here...
          // R := UpdatePointers;
          if R <> Z_STREAM_END then
          begin
            Result := InflateFlush(S, Z, R);
            Exit;
          end;
          R := Z_OK;
          Freemem(S.sub.decode.codes);
          // load local pointers
          P := Z.NextInput;
          N := Z.AvailableInput;
          B := S.bitb;
          K := S.bitk;
          Q := S.write;
          if Cardinal(Q) < Cardinal(S.read) then M := Cardinal(S.read) - Cardinal(Q) - 1
                                            else M := Cardinal(S.zend) - Cardinal(Q);
          if not S.last then
          begin
            S.mode := ibmZType;
            Continue;  
          end;
          S.mode := ibmDry;
        end;
      ibmDry:
        begin
          S.write := Q;
          R := InflateFlush(S, Z, R);
          Q := S.write;

          if S.read <> S.write then
          begin
            Result := UpdatePointers;
            Exit;
          end;
          S.mode := ibmBlockDone;
        end;
      ibmBlockDone:
        begin
          R := Z_STREAM_END;
          Result := UpdatePointers;
          Exit;
        end;
      ibmBlockBad:
        begin
          R := Z_DATA_ERROR;
          Result := UpdatePointers;
          Exit;
        end;
    else
      R := Z_STREAM_ERROR;
      Result := UpdatePointers;
      Exit;
    end; // case S.mode of
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateBlocksFree(S: PInflateBlocksState; var Z: TZState): Integer;

begin
  InflateBlockReset(S^, Z, nil);
  FreeMem(S.Window);
  FreeMem(S.hufts);
  FreeMem(S);
  Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

function IsInflateBlocksSynchPoint(var S: TInflateBlocksState): Boolean;

// returns True if Inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH

begin
  Result := S.mode = ibmLens;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateReset(var Z: TZState): Integer;

// This function is equivalent to InflateEnd followed by InflateInit, but does not free and reallocate all the internal
// decompression state. The stream will keep attributes that may have been set by InflateInit2.
//
// InflateReset returns Z_OK if success, or Z_STREAM_ERROR if the Source
// stream state was inconsistent (such State being nil).

begin
  if Z.State = nil then Result :=  Z_STREAM_ERROR
                   else
  begin
    Z.TotalOutput := 0;
    Z.TotalInput := 0;
    Z.Msg := '';
    if Z.State.nowrap then Z.State.mode := imBlocks
                      else Z.State.mode := imMethod;
    InflateBlockReset(Z.State.blocks^, Z, nil);
    Result := Z_OK;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateEnd(var Z: TZState): Integer;

// All dynamically allocated data structures for this stream are freed. This function discards any unprocessed input and
// does not flush any pending output.
//
// InflateEnd returns Z_OK on success, Z_STREAM_ERROR if the stream state was inconsistent. 

begin
  if Z.State = nil then Result :=  Z_STREAM_ERROR
                   else
  begin
    if Assigned(Z.State.blocks) then InflateBlocksFree(Z.State.blocks, Z);
    FreeMem(Z.State);
    Z.State := nil;
    Result := Z_OK;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateInit2_(var Z: TZState; W: Integer; const Version: String; StreamSize: Integer): Integer;

begin
  if (Version = '') or
     (Version[1] <> ZLIB_VERSION[1]) or
     (StreamSize <> SizeOf(TZState)) then Result := Z_VERSION_ERROR
                                     else
  begin
    // initialize state
    Z.Msg := '';
    Z.State := AllocMem(SizeOf(TInternalState));

    // handle undocumented nowrap option (no zlib header or check)
    if W < 0 then
    begin
      W := - W;
      Z.State.nowrap := True;
    end;

    // set window size
    if (W < 8) or (W > 15) then
    begin
      InflateEnd(Z);
      Result := Z_STREAM_ERROR;
      Exit;
    end;
    Z.State.wbits := W;

    // create InflateBlocks state
    if Z.State.nowrap then Z.State.blocks := InflateBlocksNew(Z, nil, 1 shl W)
                      else Z.State.blocks := InflateBlocksNew(Z, Adler32, 1 shl W);
    if Z.State.blocks = nil then
    begin
      InflateEnd(Z);
      Result := Z_MEM_ERROR;
      Exit;
    end;
    // reset state
    InflateReset(Z);
    Result := Z_OK;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateInit2(var Z: TZState; AWindowBits: Integer): Integer;

// This is another Version of InflateInit with an extra parameter. The fields NextInput and AvailableInput must be
// initialized before by the caller.
//
// The WindowBits parameter is the base two logarithm of the maximum window size (the Size of the history buffer). It
// should be in the range 8..15 for this version of the library. The default value is 15 if InflateInit is used instead.
// If a compressed stream with a larger window size is given as input, Inflate will return with the error code
// Z_DATA_ERROR instead of trying to allocate a larger window.
//
// InflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_STREAM_ERROR if a parameter is
// invalid (such as a negative MemLevel). Msg is reset if there is no error message.  InflateInit2 does not perform any
// decompression apart from reading the zlib Header if present, this will be done by Inflate. (So NextInput and
// AvailableInput may be modified, but NextOutput and AvailableOutput are unchanged.)

begin
  Result := InflateInit2_(Z, AWindowBits, ZLIB_VERSION, SizeOf(TZState));
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateInit(var Z: TZState): Integer;

// Initializes the internal stream state for decompression. 
//
// InflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough memory, Z_VERSION_ERROR if the zlib library
// version is incompatible with the version assumed by the caller. Msg is reset if there is no
// error message. InflateInit does not perform any decompression: this will be done by Inflate.

begin
  Result := InflateInit2_(Z, DEF_WBITS, ZLIB_VERSION, SizeOf(TZState));
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateInit_(var Z: TZState; const Version: String; StreamSize: Integer): Integer;

begin
  Result := InflateInit2_(Z, DEF_WBITS, Version, StreamSize);
end;

//----------------------------------------------------------------------------------------------------------------------

function Inflate(var Z: TZState; F: Integer): Integer;

// Inflate decompresses as much data as possible and stops when the input buffer becomes empty or the output buffer
// becomes full. It may introduce some output latency (reading input without producing any output) except when forced to
// flush.
//
// The detailed semantics are as follows. Inflate performs one or both of the following actions:
// - Decompress more input starting at NextInput and update NextInput and AvailableInput accordingly. if not all input
//   can be processed (because there is not enough room in the output buffer), NextInput is updated and processing will
//   resume at this point for the next call of Inflate.
//
// - Provide more output starting at NextOutput and update NextOutput and AvailableOutput accordingly. Inflate provides
//   as much output as possible, until there is no more input data or no more space in the output buffer (see below
//   about the Flush parameter).
//
// Before the call of Inflate the application should ensure that at least one of the actions is possible, by providing
// more input and/or consuming more output, and updating the Next* and Avail* values accordingly. The application can
// consume the uncompressed output when it wants, for example when the output buffer is full (AvailableOutput = 0), or
// after each call of Inflate. If Inflate returns Z_OK and with zero AvailableOutput, it must be called again after
// making room in the output buffer because there might be more output pending.
//
// If the parameter Flush is set to Z_SYNC_FLUSH, Inflate flushes as much output as possible to the output buffer. The
// flushing behavior of Inflate is not specified for values of the Flush parameter other than Z_SYNC_FLUSH and Z_FINISH,
// but the current implementation actually flushes as much output as possible anyway.
//
// Inflate should normally be called until it returns Z_STREAM_END or an error. However if all decompression is to be
// performed in a single step (a single call of Inflate), the parameter Flush should be set to Z_FINISH. In this case
// all pending input is processed and all pending output is flushed; AvailableOutput must be large enough to hold all
// the uncompressed data. (The size of the uncompressed data may have been saved by the compressor for this purpose.)
// The next operation on this stream must be InflateEnd to deallocate the decompression State. The use of Z_FINISH is
// never required, but can be used to inform Inflate that a faster routine may be used for the single Inflate call.
//
// if a preset dictionary is needed at this point (see InflateSetDictionary below), Inflate sets ZState.Adler to the
// Adler32 checksum of the dictionary chosen by the compressor and returns Z_NEED_DICT. Otherwise it sets ZState.Adler
// to the Adler32 checksum of all output produced so far (that is, TotalOutput bytes) and returns Z_OK, Z_STREAM_END or
// an error code as described below. At the end of the stream, Inflate checks that its computed Adler32 checksum is
// equal to that saved by the compressor and returns Z_STREAM_END only if the checksum is correct.
//
// Inflate returns Z_OK if some progress has been made (more input processed or more output produced), Z_STREAM_END if
// the end of the compressed data has been reached and all uncompressed output has been produced, Z_NEED_DICT if a
// preset dictionary is needed at this point, Z_DATA_ERROR if the input data was corrupted (input stream not conforming
// to the zlib format or incorrect Adler32 checksum), Z_STREAM_ERROR if the stream structure was inconsistent (for
// example if NextInput or NextOutput was nil), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR if no progress
// is possible or if there was not enough room in the output buffer when Z_FINISH is used. In the Z_DATA_ERROR
// case, the application may then call InflateSync to look for a good compression block.

var
  R: Integer;
  B: Cardinal;

begin
  if (Z.State = nil) or (Z.NextInput = nil) then Result := Z_STREAM_ERROR
                                            else
  begin
    if F = Z_FINISH then F := Z_BUF_ERROR
                    else F := Z_OK;
    R := Z_BUF_ERROR;
    while True do
    begin
      case Z.State.mode of
        imBlocks:
          begin
            R := InflateBlocks(Z.State.blocks^, Z, R);
            if R = Z_DATA_ERROR then
            begin
              Z.State.mode := imBad;
              // can try InflateSync
              Z.State.sub.marker := 0;
              Continue;
            end;

            if R = Z_OK then R := F;
            if R <> Z_STREAM_END then
            begin
              Result := R;
              Exit;
            end;
            R := F;
            InflateBlockReset(Z.State.blocks^, Z, @Z.State.sub.Check.was);
            if Z.State.nowrap then
            begin
              Z.State.mode := imDone;
              Continue;            
            end;
            Z.State.mode := imCheck4;  
          end;
        imCheck4:
          begin
            if (Z.AvailableInput = 0) then
            begin
              Result := R;
              Exit;
            end;
            R := F;

            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Z.State.sub.Check.need := Cardinal(Z.NextInput^) shl 24;
            Inc(Z.NextInput);

            Z.State.mode := imCheck3;    
          end;
        imCheck3:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F;
            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Inc(Z.State.sub.Check.need, Cardinal(Z.NextInput^) shl 16);
            Inc(Z.NextInput);

            Z.State.mode := imCheck2;   
          end;
        imCheck2:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F;

            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Inc(Z.State.sub.Check.need, Cardinal(Z.NextInput^) shl 8);
            Inc(Z.NextInput);

            Z.State.mode := imCheck1;    
          end;
        imCheck1:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F;
            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Inc(Z.State.sub.Check.need, Cardinal(Z.NextInput^));
            Inc(Z.NextInput);

            if Z.State.sub.Check.was <> Z.State.sub.Check.need then
            begin
              Z.State.mode := imBad;
              Z.Msg := SIncorrectDataCheck;
              // can't try InflateSync
              Z.State.sub.marker := 5;
              Continue;
            end;
            Z.State.mode := imDone;  
          end;
        imDone:
          begin
            Result := Z_STREAM_END;
            Exit;
          end;
        imMethod:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F; 

            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Z.State.sub.imMethod := Z.NextInput^;
            Inc(Z.NextInput);

            if (Z.State.sub.imMethod and $0F) <> Z_DEFLATED then
            begin
              Z.State.mode := imBad;
              Z.Msg := SUnknownCompression;
              // can't try InflateSync
              Z.State.sub.marker := 5;
              Continue;   
            end;

            if (Z.State.sub.imMethod shr 4) + 8 > Z.State.wbits then
            begin
              Z.State.mode := imBad;
              Z.Msg := SInvalidWindowSize;
              // can't try InflateSync
              Z.State.sub.marker := 5;
              Continue;  
            end;
            Z.State.mode := imFlag;
          end;
        imFlag:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F; 
            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            B := Z.NextInput^;
            Inc(Z.NextInput);

            if (((Z.State.sub.imMethod shl 8) + B) mod 31) <> 0 then
            begin
              Z.State.mode := imBad;
              Z.Msg := SIncorrectHeaderCheck;
              // can't try InflateSync
              Z.State.sub.marker := 5;
              Continue;       
            end;

            if (B and PRESET_DICT) = 0 then
            begin
              Z.State.mode := imBlocks;
              Continue;
            end;
            Z.State.mode := imDict4;
          end;
        imDict4:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F;

            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Z.State.sub.Check.need :=  Cardinal(Z.NextInput^) shl 24;
            Inc(Z.NextInput);

            Z.State.mode := imDict3;    
          end;
        imDict3:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F;
            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Inc(Z.State.sub.Check.need, Cardinal(Z.NextInput^) shl 16);
            Inc(Z.NextInput);

            Z.State.mode := imDict2;         
          end;
        imDict2:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            R := F;

            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Inc(Z.State.sub.Check.need, Cardinal(Z.NextInput^) shl 8);
            Inc(Z.NextInput);

            Z.State.mode := imDict1;         
          end;
        imDict1:
          begin
            if Z.AvailableInput = 0 then
            begin
              Result := R;
              Exit;
            end;
            Dec(Z.AvailableInput);
            Inc(Z.TotalInput);
            Inc(Z.State.sub.Check.need, Cardinal(Z.NextInput^) );
            Inc(Z.NextInput);

            Z.Adler := Z.State.sub.Check.need;
            Z.State.mode := imDict0;
            Inflate := Z_NEED_DICT;
            Exit;
          end;
        imDict0:
          begin
            Z.State.mode := imBad;
            Z.Msg := SNeedDictionary;
            // can try InflateSync
            Z.State.sub.marker := 0;
            Inflate := Z_STREAM_ERROR;
            Exit;
          end;
        imBad:
          begin
            Result := Z_DATA_ERROR;
            Exit;
          end;
        else
          begin
            Result := Z_STREAM_ERROR;
            Exit;
          end;
      end;
    end;
  end;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateSetDictionary(var Z: TZState; Dictionary: PByte; DictLength: Cardinal): Integer;

// Initializes the decompression dictionary from the given uncompressed byte sequence. This function must be called
// immediately after a call of Inflate if this call returned Z_NEED_DICT. The dictionary chosen by the compressor
// can be determined from the Adler32 Value returned by this call of Inflate. The compressor and decompressor must use
// exactly the same dictionary (see DeflateSetDictionary).
//
// InflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a parameter is invalid (such as nil dictionary) or
// the stream state is inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the expected one (incorrect
// Adler32 Value). InflateSetDictionary does not perform any decompression: this will be done by subsequent calls of Inflate.

var
  Length: Cardinal;

begin
  Length := DictLength;

  if (Z.State = nil) or (Z.State.mode <> imDict0) then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  if Adler32(1, Dictionary, DictLength) <> Z.Adler then
  begin
    Result := Z_DATA_ERROR;
    Exit;
  end;

  Z.Adler := 1;

  if Length >= (1 shl Z.State.wbits) then
  begin
    Length := (1 shl Z.State.wbits) - 1;
    Inc( Dictionary, DictLength - Length);
  end;

  with Z.State.blocks^ do
  begin
    Move(Dictionary^, Window^, Length);
    write := Window;
    Inc(write, Length);
    read := write;
  end;
  Z.State.mode := imBlocks;
  Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

function InflateSync(var Z: TZState): Integer;

// Skips invalid compressed data until a full flush point (see above the description of Deflate with Z_FULL_FLUSH) can
// be found, or until all available input is skipped. No output is provided.
//
// InflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR if no more input was provided,
// Z_DATA_ERROR if no flush point has been found, or Z_STREAM_ERROR if the stream structure was inconsistent. In the
// success case, the application may save the current current value of TotalInput which indicates where valid compressed
// data was found. In the error case, the application may repeatedly call InflateSync, providing more input each time,
// until success or end of the input data.

const
  Mark: packed array[0..3] of Byte = (0, 0, $FF, $FF);

var
  N: Cardinal;    // number of bytes to look at
  P: PByte;       // pointer to bytes
  M: Cardinal;    // number of marker bytes found in a row
  R, W: Cardinal; // temporaries to save TotalInput and TotalOutput

begin
  if Z.State = nil then
  begin
    Result := Z_STREAM_ERROR;
    Exit;
  end;

  if Z.State.mode <> imBad then
  begin
    Z.State.mode := imBad;
    Z.State.sub.marker := 0;
  end;

  N := Z.AvailableInput;
  if N = 0 then
  begin
    Result := Z_BUF_ERROR;
    Exit;
  end;

  P := Z.NextInput;
  M := Z.State.sub.marker;

  // search
  while (N <> 0) and (M < 4) do
  begin
    if P^ = Mark[M] then Inc(M)
                    else
      if P^ <> 0 then M := 0
                 else M := 4 - M;
    Inc(P);
    Dec(N);
  end;

  // restore
  Inc(Z.TotalInput, Cardinal(P) - Cardinal(Z.NextInput));
  Z.NextInput := P;
  Z.AvailableInput := N;
  Z.State.sub.marker := M;

  // return no joy or set up to restart on a new block
  if M <> 4 then
  begin
    Result := Z_DATA_ERROR;
    Exit;
  end;

  R := Z.TotalInput;
  W := Z.TotalOutput;
  InflateReset(Z);
  Z.TotalInput := R;
  Z.TotalOutput := W;
  Z.State.mode := imBlocks;
  Result := Z_OK;
end;

//----------------------------------------------------------------------------------------------------------------------

function IsInflateSyncPoint(var Z: TZState): Integer;

// Returns 1 if Inflate is currently at the end of a block generated by Z_SYNC_FLUSH or Z_FULL_FLUSH.
// This function is used by one PPP implementation to provide an additional safety Check. PPP uses Z_SYNC_FLUSH but
// removes the length bytes of the resulting empty stored block. When decompressing, PPP checks that at the end of input
// packet, Inflate is waiting for these length bytes.

begin
  if (Z.State = nil) or (Z.State.blocks = nil) then Result := Z_STREAM_ERROR
                                               else Result := Ord(IsInflateBlocksSynchPoint(Z.State.blocks^));
end;

//----------------------------------------------------------------------------------------------------------------------

end.

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us