home *** CD-ROM | disk | FTP | other *** search
/ Source Code 1994 March / Source_Code_CD-ROM_Walnut_Creek_March_1994.iso / compsrcs / misc / volume31 / zip19 / part03 < prev    next >
Encoding:
Text File  |  1992-08-22  |  59.9 KB  |  1,672 lines

  1. Newsgroups: comp.sources.misc
  2. From: zip-bugs@cs.ucla.edu (Info-ZIP group)
  3. Subject:  v31i095:  zip19 - Info-ZIP portable Zip, version 1.9, Part03/11
  4. Message-ID: <1992Aug23.064551.29045@sparky.imd.sterling.com>
  5. X-Md4-Signature: 5ca732e6f20f0ad06e2b983530c09eca
  6. Date: Sun, 23 Aug 1992 06:45:51 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8.  
  9. Submitted-by: zip-bugs@cs.ucla.edu (Info-ZIP group)
  10. Posting-number: Volume 31, Issue 95
  11. Archive-name: zip19/part03
  12. Supersedes: zip: Volume 23, Issue 88-96
  13. Environment: UNIX, VMS, OS/2, MS-DOS, MACINTOSH, WIN-NT, LINUX, MINIX, XOS, !AMIGA, ATARI, symlink, SGI, DEC, Cray, Convex, Amdahl, Sun, PC
  14.  
  15. #! /bin/sh
  16. # This is a shell archive.  Remove anything before this line, then feed it
  17. # into a shell via "sh file" or similar.  To overwrite existing files,
  18. # type "sh file -c".
  19. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  20. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  21. # Contents:  trees.c util.c vms/makefile.vms
  22. # Wrapped by kent@sparky on Sun Aug 23 01:00:43 1992
  23. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  24. echo If this archive is complete, you will see the following message:
  25. echo '          "shar: End of archive 3 (of 11)."'
  26. if test -f 'trees.c' -a "${1}" != "-c" ; then 
  27.   echo shar: Will not clobber existing file \"'trees.c'\"
  28. else
  29.   echo shar: Extracting \"'trees.c'\" \(40777 characters\)
  30.   sed "s/^X//" >'trees.c' <<'END_OF_FILE'
  31. X/*
  32. X
  33. X Copyright (C) 1990-1992 Mark Adler, Richard B. Wales, Jean-loup Gailly,
  34. X Kai Uwe Rommel and Igor Mandrichenko.
  35. X Permission is granted to any individual or institution to use, copy, or
  36. X redistribute this software so long as all of the original files are included
  37. X unmodified, that it is not sold for profit, and that this copyright notice
  38. X is retained.
  39. X
  40. X*/
  41. X
  42. X/*
  43. X *  trees.c by Jean-loup Gailly
  44. X *
  45. X *  This is a new version of im_ctree.c originally written by Richard B. Wales
  46. X *  for the defunct implosion method.
  47. X *
  48. X *  PURPOSE
  49. X *
  50. X *      Encode various sets of source values using variable-length
  51. X *      binary code trees.
  52. X *
  53. X *  DISCUSSION
  54. X *
  55. X *      The PKZIP "deflation" process uses several Huffman trees. The more
  56. X *      common source values are represented by shorter bit sequences.
  57. X *
  58. X *      Each code tree is stored in the ZIP file in a compressed form
  59. X *      which is itself a Huffman encoding of the lengths of
  60. X *      all the code strings (in ascending order by source values).
  61. X *      The actual code strings are reconstructed from the lengths in
  62. X *      the UNZIP process, as described in the "application note"
  63. X *      (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  64. X *
  65. X *  REFERENCES
  66. X *
  67. X *      Lynch, Thomas J.
  68. X *          Data Compression:  Techniques and Applications, pp. 53-55.
  69. X *          Lifetime Learning Publications, 1985.  ISBN 0-534-03418-7.
  70. X *
  71. X *      Storer, James A.
  72. X *          Data Compression:  Methods and Theory, pp. 49-50.
  73. X *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
  74. X *
  75. X *      Sedgewick, R.
  76. X *          Algorithms, p290.
  77. X *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
  78. X *
  79. X *  INTERFACE
  80. X *
  81. X *      void ct_init (ush *attr, int *method)
  82. X *          Allocate the match buffer, initialize the various tables and save
  83. X *          the location of the internal file attribute (ascii/binary) and
  84. X *          method (DEFLATE/STORE)
  85. X *
  86. X *      void ct_tally (int dist, int lc);
  87. X *          Save the match info and tally the frequency counts.
  88. X *
  89. X *      long flush_block (char *buf, ulg stored_len, int eof)
  90. X *          Determine the best encoding for the current block: dynamic trees,
  91. X *          static trees or store, and output the encoded block to the zip
  92. X *          file. Returns the total compressed length for the file so far.
  93. X *
  94. X */
  95. X
  96. X#include <ctype.h>
  97. X#include "zip.h"
  98. X
  99. X/* ===========================================================================
  100. X * Constants
  101. X */
  102. X
  103. X#define MAX_BITS 15
  104. X/* All codes must not exceed MAX_BITS bits */
  105. X
  106. X#define MAX_BL_BITS 7
  107. X/* Bit length codes must not exceed MAX_BL_BITS bits */
  108. X
  109. X#define LENGTH_CODES 29
  110. X/* number of length codes, not counting the special END_BLOCK code */
  111. X
  112. X#define LITERALS  256
  113. X/* number of literal bytes 0..255 */
  114. X
  115. X#define END_BLOCK 256
  116. X/* end of block literal code */
  117. X
  118. X#define L_CODES (LITERALS+1+LENGTH_CODES)
  119. X/* number of Literal or Length codes, including the END_BLOCK code */
  120. X
  121. X#define D_CODES   30
  122. X/* number of distance codes */
  123. X
  124. X#define BL_CODES  19
  125. X/* number of codes used to transfer the bit lengths */
  126. X
  127. X
  128. Xlocal int near extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  129. X   = {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};
  130. X
  131. Xlocal int near extra_dbits[D_CODES] /* extra bits for each distance code */
  132. X   = {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};
  133. X
  134. Xlocal int near extra_blbits[BL_CODES]/* extra bits for each bit length code */
  135. X   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  136. X
  137. X#define STORED_BLOCK 0
  138. X#define STATIC_TREES 1
  139. X#define DYN_TREES    2
  140. X/* The three kinds of block type */
  141. X
  142. X#ifndef LIT_BUFSIZE
  143. X#  ifdef SMALL_MEM
  144. X#    define LIT_BUFSIZE  0x2000
  145. X#  else
  146. X#  ifdef MEDIUM_MEM
  147. X#    define LIT_BUFSIZE  0x4000
  148. X#  else
  149. X#    define LIT_BUFSIZE  0x8000
  150. X#  endif
  151. X#  endif
  152. X#endif
  153. X#define DIST_BUFSIZE  LIT_BUFSIZE
  154. X/* Sizes of match buffers for literals/lengths and distances.  There are
  155. X * 4 reasons for limiting LIT_BUFSIZE to 64K:
  156. X *   - frequencies can be kept in 16 bit counters
  157. X *   - if compression is not successful for the first block, all input data is
  158. X *     still in the window so we can still emit a stored block even when input
  159. X *     comes from standard input.  (This can also be done for all blocks if
  160. X *     LIT_BUFSIZE is not greater than 32K.)
  161. X *   - if compression is not successful for a file smaller than 64K, we can
  162. X *     even emit a stored file instead of a stored block (saving 5 bytes).
  163. X *   - creating new Huffman trees less frequently may not provide fast
  164. X *     adaptation to changes in the input data statistics. (Take for
  165. X *     example a binary file with poorly compressible code followed by
  166. X *     a highly compressible string table.) Smaller buffer sizes give
  167. X *     fast adaptation but have of course the overhead of transmitting trees
  168. X *     more frequently.
  169. X *   - I can't count above 4
  170. X * The current code is general and allows DIST_BUFSIZE < LIT_BUFSIZE (to save
  171. X * memory at the expense of compression). Some optimizations would be possible
  172. X * if we rely on DIST_BUFSIZE == LIT_BUFSIZE.
  173. X */
  174. X
  175. X#define REP_3_6      16
  176. X/* repeat previous bit length 3-6 times (2 bits of repeat count) */
  177. X
  178. X#define REPZ_3_10    17
  179. X/* repeat a zero length 3-10 times  (3 bits of repeat count) */
  180. X
  181. X#define REPZ_11_138  18
  182. X/* repeat a zero length 11-138 times  (7 bits of repeat count) */
  183. X
  184. X/* ===========================================================================
  185. X * Local data
  186. X */
  187. X
  188. X/* Data structure describing a single value and its code string. */
  189. Xtypedef struct ct_data {
  190. X    union {
  191. X        ush  freq;       /* frequency count */
  192. X        ush  code;       /* bit string */
  193. X    } fc;
  194. X    union {
  195. X        ush  dad;        /* father node in Huffman tree */
  196. X        ush  len;        /* length of bit string */
  197. X    } dl;
  198. X} ct_data;
  199. X
  200. X#define Freq fc.freq
  201. X#define Code fc.code
  202. X#define Dad  dl.dad
  203. X#define Len  dl.len
  204. X
  205. X#define HEAP_SIZE (2*L_CODES+1)
  206. X/* maximum heap size */
  207. X
  208. Xlocal ct_data near dyn_ltree[HEAP_SIZE];   /* literal and length tree */
  209. Xlocal ct_data near dyn_dtree[2*D_CODES+1]; /* distance tree */
  210. X
  211. Xlocal ct_data near static_ltree[L_CODES+2];
  212. X/* The static literal tree. Since the bit lengths are imposed, there is no
  213. X * need for the L_CODES extra codes used during heap construction. However
  214. X * The codes 286 and 287 are needed to build a canonical tree (see ct_init
  215. X * below).
  216. X */
  217. X
  218. Xlocal ct_data near static_dtree[D_CODES];
  219. X/* The static distance tree. (Actually a trivial tree since all codes use
  220. X * 5 bits.)
  221. X */
  222. X
  223. Xlocal ct_data near bl_tree[2*BL_CODES+1];
  224. X/* Huffman tree for the bit lengths */
  225. X
  226. Xtypedef struct tree_desc {
  227. X    ct_data near *dyn_tree;      /* the dynamic tree */
  228. X    ct_data near *static_tree;   /* corresponding static tree or NULL */
  229. X    int     near *extra_bits;    /* extra bits for each code or NULL */
  230. X    int     extra_base;          /* base index for extra_bits */
  231. X    int     elems;               /* max number of elements in the tree */
  232. X    int     max_length;          /* max bit length for the codes */
  233. X    int     max_code;            /* largest code with non zero frequency */
  234. X} tree_desc;
  235. X
  236. Xlocal tree_desc near l_desc =
  237. X{dyn_ltree, static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS, 0};
  238. X
  239. Xlocal tree_desc near d_desc =
  240. X{dyn_dtree, static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS, 0};
  241. X
  242. Xlocal tree_desc near bl_desc =
  243. X{bl_tree, NULL,       extra_blbits, 0,         BL_CODES, MAX_BL_BITS, 0};
  244. X
  245. X
  246. Xlocal ush near bl_count[MAX_BITS+1];
  247. X/* number of codes at each bit length for an optimal tree */
  248. X
  249. Xlocal uch near bl_order[BL_CODES]
  250. X   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  251. X/* The lengths of the bit length codes are sent in order of decreasing
  252. X * probability, to avoid transmitting the lengths for unused bit length codes.
  253. X */
  254. X
  255. Xlocal int near heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  256. Xlocal int heap_len;               /* number of elements in the heap */
  257. Xlocal int heap_max;               /* element of largest frequency */
  258. X/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  259. X * The same heap array is used to build all trees.
  260. X */
  261. X
  262. Xlocal uch near depth[2*L_CODES+1];
  263. X/* Depth of each subtree used as tie breaker for trees of equal frequency */
  264. X
  265. Xlocal uch length_code[MAX_MATCH-MIN_MATCH+1];
  266. X/* length code for each normalized match length (0 == MIN_MATCH) */
  267. X
  268. Xlocal uch dist_code[512];
  269. X/* distance codes. The first 256 values correspond to the distances
  270. X * 3 .. 258, the last 256 values correspond to the top 8 bits of
  271. X * the 15 bit distances.
  272. X */
  273. X
  274. Xlocal int near base_length[LENGTH_CODES];
  275. X/* First normalized length for each code (0 = MIN_MATCH) */
  276. X
  277. Xlocal int near base_dist[D_CODES];
  278. X/* First normalized distance for each code (0 = distance of 1) */
  279. X
  280. X#ifndef DYN_ALLOC
  281. X  local uch far l_buf[LIT_BUFSIZE];  /* buffer for literals/lengths */
  282. X  local ush far d_buf[DIST_BUFSIZE]; /* buffer for distances */
  283. X#else
  284. X  local uch far *l_buf;
  285. X  local ush far *d_buf;
  286. X#endif
  287. X
  288. Xlocal uch near flag_buf[(LIT_BUFSIZE/8)];
  289. X/* flag_buf is a bit array distinguishing literals from lengths in
  290. X * l_buf, and thus indicating the presence or absence of a distance.
  291. X */
  292. X
  293. Xlocal unsigned last_lit;    /* running index in l_buf */
  294. Xlocal unsigned last_dist;   /* running index in d_buf */
  295. Xlocal unsigned last_flags;  /* running index in flag_buf */
  296. Xlocal uch flags;            /* current flags not yet saved in flag_buf */
  297. Xlocal uch flag_bit;         /* current bit used in flags */
  298. X/* bits are filled in flags starting at bit 0 (least significant).
  299. X * Note: these flags are overkill in the current code since we don't
  300. X * take advantage of DIST_BUFSIZE == LIT_BUFSIZE.
  301. X */
  302. X
  303. Xlocal ulg opt_len;        /* bit length of current block with optimal trees */
  304. Xlocal ulg static_len;     /* bit length of current block with static trees */
  305. X
  306. Xlocal ulg compressed_len; /* total bit length of compressed file */
  307. X
  308. Xlocal ulg input_len;      /* total byte length of input file */
  309. X/* input_len is for debugging only since we can get it by other means. */
  310. X
  311. Xush *file_type;        /* pointer to UNKNOWN, BINARY or ASCII */
  312. Xint *file_method;      /* pointer to DEFLATE or STORE */
  313. X
  314. X#ifdef DEBUG
  315. Xextern ulg bits_sent;  /* bit length of the compressed data */
  316. Xextern ulg isize;      /* byte length of input file */
  317. X#endif
  318. X
  319. Xextern long block_start;       /* window offset of current block */
  320. Xextern unsigned near strstart; /* window offset of current string */
  321. X
  322. X/* ===========================================================================
  323. X * Local (static) routines in this file.
  324. X */
  325. X
  326. Xlocal void init_block     OF((void));
  327. Xlocal void pqdownheap     OF((ct_data near *tree, int k));
  328. Xlocal void gen_bitlen     OF((tree_desc near *desc));
  329. Xlocal void gen_codes      OF((ct_data near *tree, int max_code));
  330. Xlocal void build_tree     OF((tree_desc near *desc));
  331. Xlocal void scan_tree      OF((ct_data near *tree, int max_code));
  332. Xlocal void send_tree      OF((ct_data near *tree, int max_code));
  333. Xlocal int  build_bl_tree  OF((void));
  334. Xlocal void send_all_trees OF((int lcodes, int dcodes, int blcodes));
  335. Xlocal void compress_block OF((ct_data near *ltree, ct_data near *dtree));
  336. Xlocal void set_file_type  OF((void));
  337. X
  338. X
  339. X#ifndef DEBUG
  340. X#  define send_code(c, tree) send_bits(tree[c].Code, tree[c].Len)
  341. X   /* Send a code of the given tree. c and tree must not have side effects */
  342. X
  343. X#else /* DEBUG */
  344. X#  define send_code(c, tree) \
  345. X     { if (verbose>1) fprintf(stderr,"\ncd %3d ",(c)); \
  346. X       send_bits(tree[c].Code, tree[c].Len); }
  347. X#endif
  348. X
  349. X#define d_code(dist) \
  350. X   ((dist) < 256 ? dist_code[dist] : dist_code[256+((dist)>>7)])
  351. X/* Mapping from a distance to a distance code. dist is the distance - 1 and
  352. X * must not have side effects. dist_code[256] and dist_code[257] are never
  353. X * used.
  354. X */
  355. X
  356. X#define MAX(a,b) (a >= b ? a : b)
  357. X/* the arguments must not have side effects */
  358. X
  359. X/* ===========================================================================
  360. X * Allocate the match buffer, initialize the various tables and save the
  361. X * location of the internal file attribute (ascii/binary) and method
  362. X * (DEFLATE/STORE).
  363. X */
  364. Xvoid ct_init(attr, method)
  365. X    ush  *attr;   /* pointer to internal file attribute */
  366. X    int  *method; /* pointer to compression method */
  367. X{
  368. X    int n;        /* iterates over tree elements */
  369. X    int bits;     /* bit counter */
  370. X    int length;   /* length value */
  371. X    int code;     /* code value */
  372. X    int dist;     /* distance index */
  373. X
  374. X    file_type = attr;
  375. X    file_method = method;
  376. X    compressed_len = input_len = 0L;
  377. X        
  378. X    if (static_dtree[0].Len != 0) return; /* ct_init already called */
  379. X
  380. X#ifdef DYN_ALLOC
  381. X    d_buf = (ush far*) fcalloc(DIST_BUFSIZE, sizeof(ush));
  382. X    l_buf = (uch far*) fcalloc(LIT_BUFSIZE/2, 2);
  383. X    /* Avoid using the value 64K on 16 bit machines */
  384. X    if (l_buf == NULL || d_buf == NULL) error("ct_init: out of memory");
  385. X#endif
  386. X
  387. X    /* Initialize the mapping length (0..255) -> length code (0..28) */
  388. X    length = 0;
  389. X    for (code = 0; code < LENGTH_CODES-1; code++) {
  390. X        base_length[code] = length;
  391. X        for (n = 0; n < (1<<extra_lbits[code]); n++) {
  392. X            length_code[length++] = (uch)code;
  393. X        }
  394. X    }
  395. X    Assert (length == 256, "ct_init: length != 256");
  396. X    /* Note that the length 255 (match length 258) can be represented
  397. X     * in two different ways: code 284 + 5 bits or code 285, so we
  398. X     * overwrite length_code[255] to use the best encoding:
  399. X     */
  400. X    length_code[length-1] = (uch)code;
  401. X
  402. X    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  403. X    dist = 0;
  404. X    for (code = 0 ; code < 16; code++) {
  405. X        base_dist[code] = dist;
  406. X        for (n = 0; n < (1<<extra_dbits[code]); n++) {
  407. X            dist_code[dist++] = (uch)code;
  408. X        }
  409. X    }
  410. X    Assert (dist == 256, "ct_init: dist != 256");
  411. X    dist >>= 7; /* from now on, all distances are divided by 128 */
  412. X    for ( ; code < D_CODES; code++) {
  413. X        base_dist[code] = dist << 7;
  414. X        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  415. X            dist_code[256 + dist++] = (uch)code;
  416. X        }
  417. X    }
  418. X    Assert (dist == 256, "ct_init: 256+dist != 512");
  419. X
  420. X    /* Construct the codes of the static literal tree */
  421. X    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  422. X    n = 0;
  423. X    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  424. X    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  425. X    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  426. X    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  427. X    /* Codes 286 and 287 do not exist, but we must include them in the
  428. X     * tree construction to get a canonical Huffman tree (longest code
  429. X     * all ones)
  430. X     */
  431. X    gen_codes(static_ltree, L_CODES+1);
  432. X
  433. X    /* The static distance tree is trivial: */
  434. X    for (n = 0; n < D_CODES; n++) {
  435. X        static_dtree[n].Len = 5;
  436. X        static_dtree[n].Code = bi_reverse(n, 5);
  437. X    }
  438. X
  439. X    /* Initialize the first block of the first file: */
  440. X    init_block();
  441. X}
  442. X
  443. X/* ===========================================================================
  444. X * Initialize a new block.
  445. X */
  446. Xlocal void init_block()
  447. X{
  448. X    int n; /* iterates over tree elements */
  449. X
  450. X    /* Initialize the trees. */
  451. X    for (n = 0; n < L_CODES;  n++) dyn_ltree[n].Freq = 0;
  452. X    for (n = 0; n < D_CODES;  n++) dyn_dtree[n].Freq = 0;
  453. X    for (n = 0; n < BL_CODES; n++) bl_tree[n].Freq = 0;
  454. X
  455. X    dyn_ltree[END_BLOCK].Freq = 1;
  456. X    opt_len = static_len = 0L;
  457. X    last_lit = last_dist = last_flags = 0;
  458. X    flags = 0; flag_bit = 1;
  459. X}
  460. X
  461. X#define SMALLEST 1
  462. X/* Index within the heap array of least frequent node in the Huffman tree */
  463. X
  464. X
  465. X/* ===========================================================================
  466. X * Remove the smallest element from the heap and recreate the heap with
  467. X * one less element. Updates heap and heap_len.
  468. X */
  469. X#define pqremove(tree, top) \
  470. X{\
  471. X    top = heap[SMALLEST]; \
  472. X    heap[SMALLEST] = heap[heap_len--]; \
  473. X    pqdownheap(tree, SMALLEST); \
  474. X}
  475. X
  476. X/* ===========================================================================
  477. X * Compares to subtrees, using the tree depth as tie breaker when
  478. X * the subtrees have equal frequency. This minimizes the worst case length.
  479. X */
  480. X#define smaller(tree, n, m) \
  481. X   (tree[n].Freq < tree[m].Freq || \
  482. X   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  483. X
  484. X/* ===========================================================================
  485. X * Restore the heap property by moving down the tree starting at node k,
  486. X * exchanging a node with the smallest of its two sons if necessary, stopping
  487. X * when the heap property is re-established (each father smaller than its
  488. X * two sons).
  489. X */
  490. Xlocal void pqdownheap(tree, k)
  491. X    ct_data near *tree;  /* the tree to restore */
  492. X    int k;               /* node to move down */
  493. X{
  494. X    int v = heap[k];
  495. X    int j = k << 1;  /* left son of k */
  496. X    while (j <= heap_len) {
  497. X        /* Set j to the smallest of the two sons: */
  498. X        if (j < heap_len && smaller(tree, heap[j+1], heap[j])) j++;
  499. X
  500. X        /* Exit if v is smaller than both sons */
  501. X        if (smaller(tree, v, heap[j])) break;
  502. X
  503. X        /* Exchange v with the smallest son */
  504. X        heap[k] = heap[j],  k = j;
  505. X
  506. X        /* And continue down the tree, setting j to the left son of k */
  507. X        j <<= 1;
  508. X    }
  509. X    heap[k] = v;
  510. X}
  511. X
  512. X/* ===========================================================================
  513. X * Compute the optimal bit lengths for a tree and update the total bit length
  514. X * for the current block.
  515. X * IN assertion: the fields freq and dad are set, heap[heap_max] and
  516. X *    above are the tree nodes sorted by increasing frequency.
  517. X * OUT assertions: the field len is set to the optimal bit length, the
  518. X *     array bl_count contains the frequencies for each bit length.
  519. X *     The length opt_len is updated; static_len is also updated if stree is
  520. X *     not null.
  521. X */
  522. Xlocal void gen_bitlen(desc)
  523. X    tree_desc near *desc; /* the tree descriptor */
  524. X{
  525. X    ct_data near *tree  = desc->dyn_tree;
  526. X    int near *extra     = desc->extra_bits;
  527. X    int base            = desc->extra_base;
  528. X    int max_code        = desc->max_code;
  529. X    int max_length      = desc->max_length;
  530. X    ct_data near *stree = desc->static_tree;
  531. X    int h;              /* heap index */
  532. X    int n, m;           /* iterate over the tree elements */
  533. X    int bits;           /* bit length */
  534. X    int xbits;          /* extra bits */
  535. X    ush f;              /* frequency */
  536. X    int overflow = 0;   /* number of elements with bit length too large */
  537. X
  538. X    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  539. X
  540. X    /* In a first pass, compute the optimal bit lengths (which may
  541. X     * overflow in the case of the bit length tree).
  542. X     */
  543. X    tree[heap[heap_max]].Len = 0; /* root of the heap */
  544. X
  545. X    for (h = heap_max+1; h < HEAP_SIZE; h++) {
  546. X        n = heap[h];
  547. X        bits = tree[tree[n].Dad].Len + 1;
  548. X        if (bits > max_length) bits = max_length, overflow++;
  549. X        tree[n].Len = bits;
  550. X        /* We overwrite tree[n].Dad which is no longer needed */
  551. X
  552. X        if (n > max_code) continue; /* not a leaf node */
  553. X
  554. X        bl_count[bits]++;
  555. X        xbits = 0;
  556. X        if (n >= base) xbits = extra[n-base];
  557. X        f = tree[n].Freq;
  558. X        opt_len += (ulg)f * (bits + xbits);
  559. X        if (stree) static_len += (ulg)f * (stree[n].Len + xbits);
  560. X    }
  561. X    if (overflow == 0) return;
  562. X
  563. X    Trace((stderr,"\nbit length overflow\n"));
  564. X    /* This happens for example on obj2 and pic of the Calgary corpus */
  565. X
  566. X    /* Find the first bit length which could increase: */
  567. X    do {
  568. X        bits = max_length-1;
  569. X        while (bl_count[bits] == 0) bits--;
  570. X        bl_count[bits]--;      /* move one leaf down the tree */
  571. X        bl_count[bits+1] += 2; /* move one overflow item as its brother */
  572. X        bl_count[max_length]--;
  573. X        /* The brother of the overflow item also moves one step up,
  574. X         * but this does not affect bl_count[max_length]
  575. X         */
  576. X        overflow -= 2;
  577. X    } while (overflow > 0);
  578. X
  579. X    /* Now recompute all bit lengths, scanning in increasing frequency.
  580. X     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  581. X     * lengths instead of fixing only the wrong ones. This idea is taken
  582. X     * from 'ar' written by Haruhiko Okumura.)
  583. X     */
  584. X    for (bits = max_length; bits != 0; bits--) {
  585. X        n = bl_count[bits];
  586. X        while (n != 0) {
  587. X            m = heap[--h];
  588. X            if (m > max_code) continue;
  589. X            if (tree[m].Len != (unsigned) bits) {
  590. X                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  591. X                opt_len += ((long)bits-(long)tree[m].Len)*(long)tree[m].Freq;
  592. X                tree[m].Len = bits;
  593. X            }
  594. X            n--;
  595. X        }
  596. X    }
  597. X}
  598. X
  599. X/* ===========================================================================
  600. X * Generate the codes for a given tree and bit counts (which need not be
  601. X * optimal).
  602. X * IN assertion: the array bl_count contains the bit length statistics for
  603. X * the given tree and the field len is set for all tree elements.
  604. X * OUT assertion: the field code is set for all tree elements of non
  605. X *     zero code length.
  606. X */
  607. Xlocal void gen_codes (tree, max_code)
  608. X    ct_data near *tree;        /* the tree to decorate */
  609. X    int max_code;              /* largest code with non zero frequency */
  610. X{
  611. X    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  612. X    ush code = 0;              /* running code value */
  613. X    int bits;                  /* bit index */
  614. X    int n;                     /* code index */
  615. X
  616. X    /* The distribution counts are first used to generate the code values
  617. X     * without bit reversal.
  618. X     */
  619. X    for (bits = 1; bits <= MAX_BITS; bits++) {
  620. X        next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  621. X    }
  622. X    /* Check that the bit counts in bl_count are consistent. The last code
  623. X     * must be all ones.
  624. X     */
  625. X    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  626. X            "inconsistent bit counts");
  627. X    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  628. X
  629. X    for (n = 0;  n <= max_code; n++) {
  630. X        int len = tree[n].Len;
  631. X        if (len == 0) continue;
  632. X        /* Now reverse the bits */
  633. X        tree[n].Code = bi_reverse(next_code[len]++, len);
  634. X
  635. X        Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  636. X             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  637. X    }
  638. X}
  639. X
  640. X/* ===========================================================================
  641. X * Construct one Huffman tree and assigns the code bit strings and lengths.
  642. X * Update the total bit length for the current block.
  643. X * IN assertion: the field freq is set for all tree elements.
  644. X * OUT assertions: the fields len and code are set to the optimal bit length
  645. X *     and corresponding code. The length opt_len is updated; static_len is
  646. X *     also updated if stree is not null. The field max_code is set.
  647. X */
  648. Xlocal void build_tree(desc)
  649. X    tree_desc near *desc; /* the tree descriptor */
  650. X{
  651. X    ct_data near *tree   = desc->dyn_tree;
  652. X    ct_data near *stree  = desc->static_tree;
  653. X    int elems            = desc->elems;
  654. X    int n, m;          /* iterate over heap elements */
  655. X    int max_code = -1; /* largest code with non zero frequency */
  656. X    int node = elems;  /* next internal node of the tree */
  657. X
  658. X    /* Construct the initial heap, with least frequent element in
  659. X     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  660. X     * heap[0] is not used.
  661. X     */
  662. X    heap_len = 0, heap_max = HEAP_SIZE;
  663. X
  664. X    for (n = 0; n < elems; n++) {
  665. X        if (tree[n].Freq != 0) {
  666. X            heap[++heap_len] = max_code = n;
  667. X            depth[n] = 0;
  668. X        } else {
  669. X            tree[n].Len = 0;
  670. X        }
  671. X    }
  672. X
  673. X    /* The pkzip format requires that at least one distance code exists,
  674. X     * and that at least one bit should be sent even if there is only one
  675. X     * possible code. So to avoid special checks later on we force at least
  676. X     * two codes of non zero frequency.
  677. X     */
  678. X    while (heap_len < 2) {
  679. X        int new = heap[++heap_len] = (max_code < 2 ? ++max_code : 0);
  680. X        tree[new].Freq = 1;
  681. X        depth[new] = 0;
  682. X        opt_len--; if (stree) static_len -= stree[new].Len;
  683. X        /* new is 0 or 1 so it does not have extra bits */
  684. X    }
  685. X    desc->max_code = max_code;
  686. X
  687. X    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  688. X     * establish sub-heaps of increasing lengths:
  689. X     */
  690. X    for (n = heap_len/2; n >= 1; n--) pqdownheap(tree, n);
  691. X
  692. X    /* Construct the Huffman tree by repeatedly combining the least two
  693. X     * frequent nodes.
  694. X     */
  695. X    do {
  696. X        pqremove(tree, n);   /* n = node of least frequency */
  697. X        m = heap[SMALLEST];  /* m = node of next least frequency */
  698. X
  699. X        heap[--heap_max] = n; /* keep the nodes sorted by frequency */
  700. X        heap[--heap_max] = m;
  701. X
  702. X        /* Create a new node father of n and m */
  703. X        tree[node].Freq = tree[n].Freq + tree[m].Freq;
  704. X        depth[node] = (uch) (MAX(depth[n], depth[m]) + 1);
  705. X        tree[n].Dad = tree[m].Dad = node;
  706. X#ifdef DUMP_BL_TREE
  707. X        if (tree == bl_tree) {
  708. X            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  709. X                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  710. X        }
  711. X#endif
  712. X        /* and insert the new node in the heap */
  713. X        heap[SMALLEST] = node++;
  714. X        pqdownheap(tree, SMALLEST);
  715. X
  716. X    } while (heap_len >= 2);
  717. X
  718. X    heap[--heap_max] = heap[SMALLEST];
  719. X
  720. X    /* At this point, the fields freq and dad are set. We can now
  721. X     * generate the bit lengths.
  722. X     */
  723. X    gen_bitlen(desc);
  724. X
  725. X    /* The field len is now set, we can generate the bit codes */
  726. X    gen_codes (tree, max_code);
  727. X}
  728. X
  729. X/* ===========================================================================
  730. X * Scan a literal or distance tree to determine the frequencies of the codes
  731. X * in the bit length tree. Updates opt_len to take into account the repeat
  732. X * counts. (The contribution of the bit length codes will be added later
  733. X * during the construction of bl_tree.)
  734. X */
  735. Xlocal void scan_tree (tree, max_code)
  736. X    ct_data near *tree; /* the tree to be scanned */
  737. X    int max_code;       /* and its largest code of non zero frequency */
  738. X{
  739. X    int n;                     /* iterates over all tree elements */
  740. X    int prevlen = -1;          /* last emitted length */
  741. X    int curlen;                /* length of current code */
  742. X    int nextlen = tree[0].Len; /* length of next code */
  743. X    int count = 0;             /* repeat count of the current code */
  744. X    int max_count = 7;         /* max repeat count */
  745. X    int min_count = 4;         /* min repeat count */
  746. X
  747. X    if (nextlen == 0) max_count = 138, min_count = 3;
  748. X    tree[max_code+1].Len = (ush)-1; /* guard */
  749. X
  750. X    for (n = 0; n <= max_code; n++) {
  751. X        curlen = nextlen; nextlen = tree[n+1].Len;
  752. X        if (++count < max_count && curlen == nextlen) {
  753. X            continue;
  754. X        } else if (count < min_count) {
  755. X            bl_tree[curlen].Freq += count;
  756. X        } else if (curlen != 0) {
  757. X            if (curlen != prevlen) bl_tree[curlen].Freq++;
  758. X            bl_tree[REP_3_6].Freq++;
  759. X        } else if (count <= 10) {
  760. X            bl_tree[REPZ_3_10].Freq++;
  761. X        } else {
  762. X            bl_tree[REPZ_11_138].Freq++;
  763. X        }
  764. X        count = 0; prevlen = curlen;
  765. X        if (nextlen == 0) {
  766. X            max_count = 138, min_count = 3;
  767. X        } else if (curlen == nextlen) {
  768. X            max_count = 6, min_count = 3;
  769. X        } else {
  770. X            max_count = 7, min_count = 4;
  771. X        }
  772. X    }
  773. X}
  774. X
  775. X/* ===========================================================================
  776. X * Send a literal or distance tree in compressed form, using the codes in
  777. X * bl_tree.
  778. X */
  779. Xlocal void send_tree (tree, max_code)
  780. X    ct_data near *tree; /* the tree to be scanned */
  781. X    int max_code;       /* and its largest code of non zero frequency */
  782. X{
  783. X    int n;                     /* iterates over all tree elements */
  784. X    int prevlen = -1;          /* last emitted length */
  785. X    int curlen;                /* length of current code */
  786. X    int nextlen = tree[0].Len; /* length of next code */
  787. X    int count = 0;             /* repeat count of the current code */
  788. X    int max_count = 7;         /* max repeat count */
  789. X    int min_count = 4;         /* min repeat count */
  790. X
  791. X    /* tree[max_code+1].Len = -1; */  /* guard already set */
  792. X    if (nextlen == 0) max_count = 138, min_count = 3;
  793. X
  794. X    for (n = 0; n <= max_code; n++) {
  795. X        curlen = nextlen; nextlen = tree[n+1].Len;
  796. X        if (++count < max_count && curlen == nextlen) {
  797. X            continue;
  798. X        } else if (count < min_count) {
  799. X            do { send_code(curlen, bl_tree); } while (--count != 0);
  800. X
  801. X        } else if (curlen != 0) {
  802. X            if (curlen != prevlen) {
  803. X                send_code(curlen, bl_tree); count--;
  804. X            }
  805. X            Assert(count >= 3 && count <= 6, " 3_6?");
  806. X            send_code(REP_3_6, bl_tree); send_bits(count-3, 2);
  807. X
  808. X        } else if (count <= 10) {
  809. X            send_code(REPZ_3_10, bl_tree); send_bits(count-3, 3);
  810. X
  811. X        } else {
  812. X            send_code(REPZ_11_138, bl_tree); send_bits(count-11, 7);
  813. X        }
  814. X        count = 0; prevlen = curlen;
  815. X        if (nextlen == 0) {
  816. X            max_count = 138, min_count = 3;
  817. X        } else if (curlen == nextlen) {
  818. X            max_count = 6, min_count = 3;
  819. X        } else {
  820. X            max_count = 7, min_count = 4;
  821. X        }
  822. X    }
  823. X}
  824. X
  825. X/* ===========================================================================
  826. X * Construct the Huffman tree for the bit lengths and return the index in
  827. X * bl_order of the last bit length code to send.
  828. X */
  829. Xlocal int build_bl_tree()
  830. X{
  831. X    int max_blindex;  /* index of last bit length code of non zero freq */
  832. X
  833. X    /* Determine the bit length frequencies for literal and distance trees */
  834. X    scan_tree(dyn_ltree, l_desc.max_code);
  835. X    scan_tree(dyn_dtree, d_desc.max_code);
  836. X
  837. X    /* Build the bit length tree: */
  838. X    build_tree(&bl_desc);
  839. X    /* opt_len now includes the length of the tree representations, except
  840. X     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  841. X     */
  842. X
  843. X    /* Determine the number of bit length codes to send. The pkzip format
  844. X     * requires that at least 4 bit length codes be sent. (appnote.txt says
  845. X     * 3 but the actual value used is 4.)
  846. X     */
  847. X    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  848. X        if (bl_tree[bl_order[max_blindex]].Len != 0) break;
  849. X    }
  850. X    /* Update opt_len to include the bit length tree and counts */
  851. X    opt_len += 3*(max_blindex+1) + 5+5+4;
  852. X    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", opt_len, static_len));
  853. X
  854. X    return max_blindex;
  855. X}
  856. X
  857. X/* ===========================================================================
  858. X * Send the header for a block using dynamic Huffman trees: the counts, the
  859. X * lengths of the bit length codes, the literal tree and the distance tree.
  860. X * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  861. X */
  862. Xlocal void send_all_trees(lcodes, dcodes, blcodes)
  863. X    int lcodes, dcodes, blcodes; /* number of codes for each tree */
  864. X{
  865. X    int rank;                    /* index in bl_order */
  866. X
  867. X    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  868. X    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  869. X            "too many codes");
  870. X    Tracev((stderr, "\nbl counts: "));
  871. X    send_bits(lcodes-257, 5); /* not -255 as stated in appnote.txt */
  872. X    send_bits(dcodes-1,   5);
  873. X    send_bits(blcodes-4,  4); /* not -3 as stated in appnote.txt */
  874. X    for (rank = 0; rank < blcodes; rank++) {
  875. X        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  876. X        send_bits(bl_tree[bl_order[rank]].Len, 3);
  877. X    }
  878. X    Tracev((stderr, "\nbl tree: sent %ld", bits_sent));
  879. X
  880. X    send_tree(dyn_ltree, lcodes-1); /* send the literal tree */
  881. X    Tracev((stderr, "\nlit tree: sent %ld", bits_sent));
  882. X
  883. X    send_tree(dyn_dtree, dcodes-1); /* send the distance tree */
  884. X    Tracev((stderr, "\ndist tree: sent %ld", bits_sent));
  885. X}
  886. X
  887. X/* ===========================================================================
  888. X * Determine the best encoding for the current block: dynamic trees, static
  889. X * trees or store, and output the encoded block to the zip file. This function
  890. X * returns the total compressed length for the file so far.
  891. X */
  892. Xulg flush_block(buf, stored_len, eof)
  893. X    char *buf;        /* input block, or NULL if too old */
  894. X    ulg stored_len;   /* length of input block */
  895. X    int eof;          /* true if this is the last block for a file */
  896. X{
  897. X    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  898. X    int max_blindex;  /* index of last bit length code of non zero freq */
  899. X
  900. X    flag_buf[last_flags] = flags; /* Save the flags for the last 8 items */
  901. X
  902. X     /* Check if the file is ascii or binary */
  903. X    if (*file_type == (ush)UNKNOWN) set_file_type();
  904. X
  905. X    /* Construct the literal and distance trees */
  906. X    build_tree(&l_desc);
  907. X    Tracev((stderr, "\nlit data: dyn %ld, stat %ld", opt_len, static_len));
  908. X
  909. X    build_tree(&d_desc);
  910. X    Tracev((stderr, "\ndist data: dyn %ld, stat %ld", opt_len, static_len));
  911. X    /* At this point, opt_len and static_len are the total bit lengths of
  912. X     * the compressed block data, excluding the tree representations.
  913. X     */
  914. X
  915. X    /* Build the bit length tree for the above two trees, and get the index
  916. X     * in bl_order of the last bit length code to send.
  917. X     */
  918. X    max_blindex = build_bl_tree();
  919. X
  920. X    /* Determine the best encoding. Compute first the block length in bytes */
  921. X    opt_lenb = (opt_len+3+7)>>3;
  922. X    static_lenb = (static_len+3+7)>>3;
  923. X    input_len += stored_len; /* for debugging only */
  924. X
  925. X    Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
  926. X            opt_lenb, opt_len, static_lenb, static_len, stored_len,
  927. X            last_lit, last_dist));
  928. X
  929. X    if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  930. X
  931. X    /* If compression failed and this is the first and last block,
  932. X     * and if the zip file can be seeked (to rewrite the local header),
  933. X     * the whole file is transformed into a stored file:
  934. X     */
  935. X#ifdef FORCE_METHOD
  936. X    if (level == 1 && eof && compressed_len == 0L) { /* force stored file */
  937. X#else
  938. X    if (stored_len <= opt_lenb && eof && compressed_len == 0L && seekable()) {
  939. X#endif
  940. X        /* Since LIT_BUFSIZE <= 2*WSIZE, the input data must be there: */
  941. X        if (buf == NULL) error ("block vanished");
  942. X
  943. X        copy_block(buf, (unsigned)stored_len, 0); /* without header */
  944. X        compressed_len = stored_len << 3;
  945. X        *file_method = STORE;
  946. X
  947. X#ifdef FORCE_METHOD
  948. X    } else if (level == 2 && buf != NULL) { /* force stored block */
  949. X#else
  950. X    } else if (stored_len+4 <= opt_lenb && buf != NULL) {
  951. X                       /* 4: two words for the lengths */
  952. X#endif
  953. X        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  954. X         * Otherwise we can't have processed more than WSIZE input bytes since
  955. X         * the last block flush, because compression would have been
  956. X         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  957. X         * transform a block into a stored block.
  958. X         */
  959. X        send_bits((STORED_BLOCK<<1)+eof, 3);  /* send block type */
  960. X        compressed_len = (compressed_len + 3 + 7) & ~7L;
  961. X        compressed_len += (stored_len + 4) << 3;
  962. X
  963. X        copy_block(buf, (unsigned)stored_len, 1); /* with header */
  964. X
  965. X#ifdef FORCE_METHOD
  966. X    } else if (level == 3) { /* force static trees */
  967. X#else
  968. X    } else if (static_lenb == opt_lenb) {
  969. X#endif
  970. X        send_bits((STATIC_TREES<<1)+eof, 3);
  971. X        compress_block(static_ltree, static_dtree);
  972. X        compressed_len += 3 + static_len;
  973. X    } else {
  974. X        send_bits((DYN_TREES<<1)+eof, 3);
  975. X        send_all_trees(l_desc.max_code+1, d_desc.max_code+1, max_blindex+1);
  976. X        compress_block(dyn_ltree, dyn_dtree);
  977. X        compressed_len += 3 + opt_len;
  978. X    }
  979. X    Assert (compressed_len == bits_sent, "bad compressed size");
  980. X    init_block();
  981. X
  982. X    if (eof) {
  983. X        Assert (input_len == isize, "bad input size");
  984. X        bi_windup();
  985. X        compressed_len += 7;  /* align on byte boundary */
  986. X    }
  987. X    Tracev((stderr,"\ncomprlen %lu(%lu) ", compressed_len>>3,
  988. X           compressed_len-7*eof));
  989. X
  990. X    return compressed_len >> 3;
  991. X}
  992. X
  993. X/* ===========================================================================
  994. X * Save the match info and tally the frequency counts. Return true if
  995. X * the current block must be flushed.
  996. X */
  997. Xint ct_tally (dist, lc)
  998. X    int dist;  /* distance of matched string */
  999. X    int lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
  1000. X{
  1001. X    l_buf[last_lit++] = (uch)lc;
  1002. X    if (dist == 0) {
  1003. X        /* lc is the unmatched char */
  1004. X        dyn_ltree[lc].Freq++;
  1005. X    } else {
  1006. X        /* Here, lc is the match length - MIN_MATCH */
  1007. X        dist--;             /* dist = match distance - 1 */
  1008. X        Assert((ush)dist < (ush)MAX_DIST &&
  1009. X               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  1010. X               (ush)d_code(dist) < (ush)D_CODES,  "ct_tally: bad match");
  1011. X
  1012. X        dyn_ltree[length_code[lc]+LITERALS+1].Freq++;
  1013. X        dyn_dtree[d_code(dist)].Freq++;
  1014. X
  1015. X        d_buf[last_dist++] = dist;
  1016. X        flags |= flag_bit;
  1017. X    }
  1018. X    flag_bit <<= 1;
  1019. X
  1020. X    /* Output the flags if they fill a byte: */
  1021. X    if ((last_lit & 7) == 0) {
  1022. X        flag_buf[last_flags++] = flags;
  1023. X        flags = 0, flag_bit = 1;
  1024. X    }
  1025. X    /* Try to guess if it is profitable to stop the current block here */
  1026. X    if (level > 2 && (last_lit & 0xfff) == 0) {
  1027. X        /* Compute an upper bound for the compressed length */
  1028. X        ulg out_length = (ulg)last_lit*8L;
  1029. X        ulg in_length = (ulg)strstart-block_start;
  1030. X        int dcode;
  1031. X        for (dcode = 0; dcode < D_CODES; dcode++) {
  1032. X            out_length += (ulg)dyn_dtree[dcode].Freq*(5L+extra_dbits[dcode]);
  1033. X        }
  1034. X        out_length >>= 3;
  1035. X        Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
  1036. X               last_lit, last_dist, in_length, out_length,
  1037. X               100L - out_length*100L/in_length));
  1038. X        if (last_dist < last_lit/2 && out_length < in_length/2) return 1;
  1039. X    }
  1040. X    return (last_lit == LIT_BUFSIZE-1 || last_dist == DIST_BUFSIZE);
  1041. X    /* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
  1042. X     * on 16 bit machines and because stored blocks are restricted to
  1043. X     * 64K-1 bytes.
  1044. X     */
  1045. X}
  1046. X
  1047. X/* ===========================================================================
  1048. X * Send the block data compressed using the given Huffman trees
  1049. X */
  1050. Xlocal void compress_block(ltree, dtree)
  1051. X    ct_data near *ltree; /* literal tree */
  1052. X    ct_data near *dtree; /* distance tree */
  1053. X{
  1054. X    unsigned dist;      /* distance of matched string */
  1055. X    int lc;             /* match length or unmatched char (if dist == 0) */
  1056. X    unsigned lx = 0;    /* running index in l_buf */
  1057. X    unsigned dx = 0;    /* running index in d_buf */
  1058. X    unsigned fx = 0;    /* running index in flag_buf */
  1059. X    uch flag = 0;       /* current flags */
  1060. X    unsigned code;      /* the code to send */
  1061. X    int extra;          /* number of extra bits to send */
  1062. X
  1063. X    if (last_lit != 0) do {
  1064. X        if ((lx & 7) == 0) flag = flag_buf[fx++];
  1065. X        lc = l_buf[lx++];
  1066. X        if ((flag & 1) == 0) {
  1067. X            send_code(lc, ltree); /* send a literal byte */
  1068. X            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  1069. X        } else {
  1070. X            /* Here, lc is the match length - MIN_MATCH */
  1071. X            code = length_code[lc];
  1072. X            send_code(code+LITERALS+1, ltree); /* send the length code */
  1073. X            extra = extra_lbits[code];
  1074. X            if (extra != 0) {
  1075. X                lc -= base_length[code];
  1076. X                send_bits(lc, extra);        /* send the extra length bits */
  1077. X            }
  1078. X            dist = d_buf[dx++];
  1079. X            /* Here, dist is the match distance - 1 */
  1080. X            code = d_code(dist);
  1081. X            Assert (code < D_CODES, "bad d_code");
  1082. X
  1083. X            send_code(code, dtree);       /* send the distance code */
  1084. X            extra = extra_dbits[code];
  1085. X            if (extra != 0) {
  1086. X                dist -= base_dist[code];
  1087. X                send_bits(dist, extra);   /* send the extra distance bits */
  1088. X            }
  1089. X        } /* literal or match pair ? */
  1090. X        flag >>= 1;
  1091. X    } while (lx < last_lit);
  1092. X
  1093. X    send_code(END_BLOCK, ltree);
  1094. X}
  1095. X
  1096. X/* ===========================================================================
  1097. X * Set the file type to ASCII or BINARY, using a crude approximation:
  1098. X * binary if more than 20% of the bytes are <= 6 or >= 128, ascii otherwise.
  1099. X * IN assertion: the fields freq of dyn_ltree are set and the total of all
  1100. X * frequencies does not exceed 64K (to fit in an int on 16 bit machines).
  1101. X */
  1102. Xlocal void set_file_type()
  1103. X{
  1104. X    int n = 0;
  1105. X    unsigned ascii_freq = 0;
  1106. X    unsigned bin_freq = 0;
  1107. X    while (n < 7)        bin_freq += dyn_ltree[n++].Freq;
  1108. X    while (n < 128)    ascii_freq += dyn_ltree[n++].Freq;
  1109. X    while (n < LITERALS) bin_freq += dyn_ltree[n++].Freq;
  1110. X    *file_type = bin_freq > (ascii_freq >> 2) ? BINARY : ASCII;
  1111. X    if (*file_type == BINARY && translate_eol) {
  1112. X        warn("-l used on binary file", "");
  1113. X    }
  1114. X}
  1115. END_OF_FILE
  1116.   if test 40777 -ne `wc -c <'trees.c'`; then
  1117.     echo shar: \"'trees.c'\" unpacked with wrong size!
  1118.   fi
  1119.   # end of 'trees.c'
  1120. fi
  1121. if test -f 'util.c' -a "${1}" != "-c" ; then 
  1122.   echo shar: Will not clobber existing file \"'util.c'\"
  1123. else
  1124.   echo shar: Extracting \"'util.c'\" \(12887 characters\)
  1125.   sed "s/^X//" >'util.c' <<'END_OF_FILE'
  1126. X/*
  1127. X
  1128. X Copyright (C) 1990-1992 Mark Adler, Richard B. Wales, Jean-loup Gailly,
  1129. X Kai Uwe Rommel and Igor Mandrichenko.
  1130. X Permission is granted to any individual or institution to use, copy, or
  1131. X redistribute this software so long as all of the original files are included
  1132. X unmodified, that it is not sold for profit, and that this copyright notice
  1133. X is retained.
  1134. X
  1135. X*/
  1136. X
  1137. X/*
  1138. X *  util.c by Mark Adler.
  1139. X */
  1140. X
  1141. X#include "zip.h"
  1142. X#include <ctype.h>
  1143. X
  1144. X#if defined(MSDOS) && !defined(OS2) && !defined(__GO32__) && !defined(WIN32)
  1145. X#  include <dos.h>
  1146. X#endif
  1147. X
  1148. Xuch upper[256], lower[256];
  1149. X/* Country-dependent case map table */
  1150. X
  1151. X
  1152. X#ifndef UTIL /* UTIL picks out namecmp code (all utils) and crc32 (zipcloak) */
  1153. X
  1154. X/* Local functions */
  1155. X#ifdef PROTO
  1156. X  local int recmatch(char *, char *);
  1157. X  local unsigned ident(unsigned chr);
  1158. X#endif /* PROTO */
  1159. X
  1160. Xchar *isshexp(p)
  1161. Xchar *p;                /* candidate sh expression */
  1162. X/* If p is a sh expression, a pointer to the first special character is
  1163. X   returned.  Otherwise, NULL is returned. */
  1164. X{
  1165. X  for (; *p; p++)
  1166. X    if (*p == '\\' && *(p+1))
  1167. X      p++;
  1168. X#ifdef VMS
  1169. X    else if (*p == '%' || *p == '*')
  1170. X#else /* !VMS */
  1171. X    else if (*p == '?' || *p == '*' || *p == '[')
  1172. X#endif /* ?VMS */
  1173. X      return p;
  1174. X  return NULL;
  1175. X}
  1176. X
  1177. X
  1178. Xlocal int recmatch(p, s)
  1179. Xchar *p;                /* sh pattern to match */
  1180. Xchar *s;                /* string to match it to */
  1181. X/* Recursively compare the sh pattern p with the string s and return 1 if
  1182. X   they match, and 0 or 2 if they don't or if there is a syntax error in the
  1183. X   pattern.  This routine recurses on itself no deeper than the number of
  1184. X   characters in the pattern. */
  1185. X{
  1186. X  int c;                /* pattern char or start of range in [-] loop */ 
  1187. X
  1188. X  /* Get first character, the pattern for new recmatch calls follows */
  1189. X  c = *p++;
  1190. X
  1191. X  /* If that was the end of the pattern, match if string empty too */
  1192. X  if (c == 0)
  1193. X    return *s == 0;
  1194. X
  1195. X  /* '?' (or '%') matches any character (but not an empty string) */
  1196. X#ifdef VMS
  1197. X  if (c == '%')
  1198. X#else /* !VMS */
  1199. X  if (c == '?')
  1200. X#endif /* ?VMS */
  1201. X    return *s ? recmatch(p, s + 1) : 0;
  1202. X
  1203. X  /* '*' matches any number of characters, including zero */
  1204. X  if (c == '*')
  1205. X  {
  1206. X    if (*p == 0)
  1207. X      return 1;
  1208. X    for (; *s; s++)
  1209. X      if ((c = recmatch(p, s)) != 0)
  1210. X        return c;
  1211. X    return 2;           /* 2 means give up--shmatch will return false */
  1212. X  }
  1213. X
  1214. X#ifndef VMS             /* No bracket matching in VMS */
  1215. X  /* Parse and process the list of characters and ranges in brackets */
  1216. X  if (c == '[')
  1217. X  {
  1218. X    int e;              /* flag true if next char to be taken literally */
  1219. X    char *q;            /* pointer to end of [-] group */
  1220. X    int r;              /* flag true to match anything but the range */
  1221. X
  1222. X    if (*s == 0)                        /* need a character to match */
  1223. X      return 0;
  1224. X    p += (r = *p == '!');               /* see if reverse */
  1225. X    for (q = p, e = 0; *q; q++)         /* find closing bracket */
  1226. X      if (e)
  1227. X        e = 0;
  1228. X      else
  1229. X        if (*q == '\\')
  1230. X          e = 1;
  1231. X        else if (*q == ']')
  1232. X          break;
  1233. X    if (*q != ']')                      /* nothing matches if bad syntax */
  1234. X      return 0;
  1235. X    for (c = 0, e = *p == '-'; p < q; p++)      /* go through the list */
  1236. X    {
  1237. X      if (e == 0 && *p == '\\')         /* set escape flag if \ */
  1238. X        e = 1;
  1239. X      else if (e == 0 && *p == '-')     /* set start of range if - */
  1240. X        c = *(p-1);
  1241. X      else
  1242. X      {
  1243. X        if (*(p+1) != '-')
  1244. X          for (c = c ? c : *p; c <= *p; c++)    /* compare range */
  1245. X            if (case_map(c) == case_map(*s))
  1246. X              return r ? 0 : recmatch(q + 1, s + 1);
  1247. X        c = e = 0;                      /* clear range, escape flags */
  1248. X      }
  1249. X    }
  1250. X    return r ? recmatch(q + 1, s + 1) : 0;      /* bracket match failed */
  1251. X  }
  1252. X#endif /* !VMS */
  1253. X
  1254. X  /* If escape ('\'), just compare next character */
  1255. X  if (c == '\\')
  1256. X    if ((c = *p++) == 0)                /* if \ at end, then syntax error */
  1257. X      return 0;
  1258. X
  1259. X  /* Just a character--compare it */
  1260. X  return case_map(c) == case_map(*s) ? recmatch(p, ++s) : 0;
  1261. X}
  1262. X
  1263. X
  1264. Xint shmatch(p, s)
  1265. Xchar *p;                /* sh pattern to match */
  1266. Xchar *s;                /* string to match it to */
  1267. X/* Compare the sh pattern p with the string s and return true if they match,
  1268. X   false if they don't or if there is a syntax error in the pattern. */
  1269. X{
  1270. X  return recmatch(p, s) == 1;
  1271. X}
  1272. X
  1273. X
  1274. X#ifdef MSDOS
  1275. X
  1276. Xint dosmatch(p, s)
  1277. Xchar *p;                /* dos pattern to match */
  1278. Xchar *s;                /* string to match it to */
  1279. X/* Break the pattern and string into name and extension parts and match
  1280. X   each separately using shmatch(). */
  1281. X{
  1282. X  char *p1, *p2;        /* pattern sections */
  1283. X  char *s1, *s2;        /* string sections */
  1284. X  int r;                /* result */
  1285. X
  1286. X  if ((p1 = malloc(strlen(p) + 1)) == NULL ||
  1287. X      (s1 = malloc(strlen(s) + 1)) == NULL)
  1288. X  {
  1289. X    if (p1 != NULL)
  1290. X      free((voidp *)p1);
  1291. X    return 0;
  1292. X  }
  1293. X  strcpy(p1, p);
  1294. X  strcpy(s1, s);
  1295. X  if ((p2 = strrchr(p1, '.')) != NULL)
  1296. X    *p2++ = 0;
  1297. X  else
  1298. X    p2 = "";
  1299. X  if ((s2 = strrchr(s1, '.')) != NULL)
  1300. X    *s2++ = 0;
  1301. X  else
  1302. X    s2 = "";
  1303. X  r = shmatch(p2, s2) && shmatch(p1, s1);
  1304. X  free((voidp *)p1);
  1305. X  free((voidp *)s1);
  1306. X  return r;
  1307. X}
  1308. X#endif /* MSDOS */
  1309. X
  1310. Xvoidp far **search(b, a, n, cmp)
  1311. Xvoidp *b;               /* pointer to value to search for */
  1312. Xvoidp far **a;          /* table of pointers to values, sorted */
  1313. Xextent n;               /* number of pointers in a[] */
  1314. Xint (*cmp) OF((voidp *, voidp far *));  /* comparison function for search */
  1315. X/* Search for b in the pointer list a[0..n-1] using the compare function
  1316. X   cmp(b, c) where c is an element of a[i] and cmp() returns negative if
  1317. X   *b < *c, zero if *b == *c, or positive if *b > *c.  If *b is found,
  1318. X   search returns a pointer to the entry in a[], else search() returns
  1319. X   NULL.  The nature and size of *b and *c (they can be different) are
  1320. X   left up to the cmp() function.  A binary search is used, and it is
  1321. X   assumed that the list is sorted in ascending order. */
  1322. X{
  1323. X  voidp far **i;        /* pointer to midpoint of current range */
  1324. X  voidp far **l;        /* pointer to lower end of current range */
  1325. X  int r;                /* result of (*cmp)() call */
  1326. X  voidp far **u;        /* pointer to upper end of current range */
  1327. X
  1328. X  l = (voidp far **)a;  u = l + (n-1);
  1329. X  while (u >= l)
  1330. X    if ((r = (*cmp)(b, *(i = l + ((u - l) >> 1)))) < 0)
  1331. X      u = i - 1;
  1332. X    else if (r > 0)
  1333. X      l = i + 1;
  1334. X    else
  1335. X      return (voidp far **)i;
  1336. X  return NULL;          /* If b were in list, it would belong at l */
  1337. X}
  1338. X
  1339. X#endif /* !UTIL */
  1340. X
  1341. X
  1342. X/* Table of CRC-32's of all single byte values (made by makecrc.c) */
  1343. Xlocal ulg crctab[] = {
  1344. X  0x00000000L, 0x77073096L, 0xee0e612cL, 0x990951baL, 0x076dc419L,
  1345. X  0x706af48fL, 0xe963a535L, 0x9e6495a3L, 0x0edb8832L, 0x79dcb8a4L,
  1346. X  0xe0d5e91eL, 0x97d2d988L, 0x09b64c2bL, 0x7eb17cbdL, 0xe7b82d07L,
  1347. X  0x90bf1d91L, 0x1db71064L, 0x6ab020f2L, 0xf3b97148L, 0x84be41deL,
  1348. X  0x1adad47dL, 0x6ddde4ebL, 0xf4d4b551L, 0x83d385c7L, 0x136c9856L,
  1349. X  0x646ba8c0L, 0xfd62f97aL, 0x8a65c9ecL, 0x14015c4fL, 0x63066cd9L,
  1350. X  0xfa0f3d63L, 0x8d080df5L, 0x3b6e20c8L, 0x4c69105eL, 0xd56041e4L,
  1351. X  0xa2677172L, 0x3c03e4d1L, 0x4b04d447L, 0xd20d85fdL, 0xa50ab56bL,
  1352. X  0x35b5a8faL, 0x42b2986cL, 0xdbbbc9d6L, 0xacbcf940L, 0x32d86ce3L,
  1353. X  0x45df5c75L, 0xdcd60dcfL, 0xabd13d59L, 0x26d930acL, 0x51de003aL,
  1354. X  0xc8d75180L, 0xbfd06116L, 0x21b4f4b5L, 0x56b3c423L, 0xcfba9599L,
  1355. X  0xb8bda50fL, 0x2802b89eL, 0x5f058808L, 0xc60cd9b2L, 0xb10be924L,
  1356. X  0x2f6f7c87L, 0x58684c11L, 0xc1611dabL, 0xb6662d3dL, 0x76dc4190L,
  1357. X  0x01db7106L, 0x98d220bcL, 0xefd5102aL, 0x71b18589L, 0x06b6b51fL,
  1358. X  0x9fbfe4a5L, 0xe8b8d433L, 0x7807c9a2L, 0x0f00f934L, 0x9609a88eL,
  1359. X  0xe10e9818L, 0x7f6a0dbbL, 0x086d3d2dL, 0x91646c97L, 0xe6635c01L,
  1360. X  0x6b6b51f4L, 0x1c6c6162L, 0x856530d8L, 0xf262004eL, 0x6c0695edL,
  1361. X  0x1b01a57bL, 0x8208f4c1L, 0xf50fc457L, 0x65b0d9c6L, 0x12b7e950L,
  1362. X  0x8bbeb8eaL, 0xfcb9887cL, 0x62dd1ddfL, 0x15da2d49L, 0x8cd37cf3L,
  1363. X  0xfbd44c65L, 0x4db26158L, 0x3ab551ceL, 0xa3bc0074L, 0xd4bb30e2L,
  1364. X  0x4adfa541L, 0x3dd895d7L, 0xa4d1c46dL, 0xd3d6f4fbL, 0x4369e96aL,
  1365. X  0x346ed9fcL, 0xad678846L, 0xda60b8d0L, 0x44042d73L, 0x33031de5L,
  1366. X  0xaa0a4c5fL, 0xdd0d7cc9L, 0x5005713cL, 0x270241aaL, 0xbe0b1010L,
  1367. X  0xc90c2086L, 0x5768b525L, 0x206f85b3L, 0xb966d409L, 0xce61e49fL,
  1368. X  0x5edef90eL, 0x29d9c998L, 0xb0d09822L, 0xc7d7a8b4L, 0x59b33d17L,
  1369. X  0x2eb40d81L, 0xb7bd5c3bL, 0xc0ba6cadL, 0xedb88320L, 0x9abfb3b6L,
  1370. X  0x03b6e20cL, 0x74b1d29aL, 0xead54739L, 0x9dd277afL, 0x04db2615L,
  1371. X  0x73dc1683L, 0xe3630b12L, 0x94643b84L, 0x0d6d6a3eL, 0x7a6a5aa8L,
  1372. X  0xe40ecf0bL, 0x9309ff9dL, 0x0a00ae27L, 0x7d079eb1L, 0xf00f9344L,
  1373. X  0x8708a3d2L, 0x1e01f268L, 0x6906c2feL, 0xf762575dL, 0x806567cbL,
  1374. X  0x196c3671L, 0x6e6b06e7L, 0xfed41b76L, 0x89d32be0L, 0x10da7a5aL,
  1375. X  0x67dd4accL, 0xf9b9df6fL, 0x8ebeeff9L, 0x17b7be43L, 0x60b08ed5L,
  1376. X  0xd6d6a3e8L, 0xa1d1937eL, 0x38d8c2c4L, 0x4fdff252L, 0xd1bb67f1L,
  1377. X  0xa6bc5767L, 0x3fb506ddL, 0x48b2364bL, 0xd80d2bdaL, 0xaf0a1b4cL,
  1378. X  0x36034af6L, 0x41047a60L, 0xdf60efc3L, 0xa867df55L, 0x316e8eefL,
  1379. X  0x4669be79L, 0xcb61b38cL, 0xbc66831aL, 0x256fd2a0L, 0x5268e236L,
  1380. X  0xcc0c7795L, 0xbb0b4703L, 0x220216b9L, 0x5505262fL, 0xc5ba3bbeL,
  1381. X  0xb2bd0b28L, 0x2bb45a92L, 0x5cb36a04L, 0xc2d7ffa7L, 0xb5d0cf31L,
  1382. X  0x2cd99e8bL, 0x5bdeae1dL, 0x9b64c2b0L, 0xec63f226L, 0x756aa39cL,
  1383. X  0x026d930aL, 0x9c0906a9L, 0xeb0e363fL, 0x72076785L, 0x05005713L,
  1384. X  0x95bf4a82L, 0xe2b87a14L, 0x7bb12baeL, 0x0cb61b38L, 0x92d28e9bL,
  1385. X  0xe5d5be0dL, 0x7cdcefb7L, 0x0bdbdf21L, 0x86d3d2d4L, 0xf1d4e242L,
  1386. X  0x68ddb3f8L, 0x1fda836eL, 0x81be16cdL, 0xf6b9265bL, 0x6fb077e1L,
  1387. X  0x18b74777L, 0x88085ae6L, 0xff0f6a70L, 0x66063bcaL, 0x11010b5cL,
  1388. X  0x8f659effL, 0xf862ae69L, 0x616bffd3L, 0x166ccf45L, 0xa00ae278L,
  1389. X  0xd70dd2eeL, 0x4e048354L, 0x3903b3c2L, 0xa7672661L, 0xd06016f7L,
  1390. X  0x4969474dL, 0x3e6e77dbL, 0xaed16a4aL, 0xd9d65adcL, 0x40df0b66L,
  1391. X  0x37d83bf0L, 0xa9bcae53L, 0xdebb9ec5L, 0x47b2cf7fL, 0x30b5ffe9L,
  1392. X  0xbdbdf21cL, 0xcabac28aL, 0x53b39330L, 0x24b4a3a6L, 0xbad03605L,
  1393. X  0xcdd70693L, 0x54de5729L, 0x23d967bfL, 0xb3667a2eL, 0xc4614ab8L,
  1394. X  0x5d681b02L, 0x2a6f2b94L, 0xb40bbe37L, 0xc30c8ea1L, 0x5a05df1bL,
  1395. X  0x2d02ef8dL
  1396. X};
  1397. X
  1398. X
  1399. Xulg crc32(c, b)
  1400. Xulg c;                  /* current contents of crc shift register */
  1401. Xint b;                  /* byte (eight bits) to run through */
  1402. X/* Return the CRC-32 c updated with the eight bits in b. */
  1403. X{
  1404. X  return crctab[((int)c ^ b) & 0xff] ^ (c >> 8);
  1405. X}
  1406. X
  1407. X
  1408. X#ifndef UTIL /* UTIL picks out namecmp code (all utils) and crc32 (zipcloak) */
  1409. X
  1410. Xulg updcrc(s, n)
  1411. Xchar *s;                /* pointer to bytes to pump through */
  1412. Xextent n;               /* number of bytes in s[] */
  1413. X/* Run a set of bytes through the crc shift register.  If s is a NULL
  1414. X   pointer, then initialize the crc shift register contents instead.
  1415. X   Return the current crc in either case. */
  1416. X{
  1417. X  register ulg c;       /* temporary variable */
  1418. X
  1419. X  static ulg crc = 0xffffffffL; /* shift register contents */
  1420. X
  1421. X  if (s == NULL)
  1422. X    c = 0xffffffffL;
  1423. X  else
  1424. X  {
  1425. X    c = crc;
  1426. X    while (n--)
  1427. X      c = crctab[((int)c ^ (*s++)) & 0xff] ^ (c >> 8);
  1428. X  }
  1429. X  crc = c;
  1430. X  return c ^ 0xffffffffL;       /* (instead of ~c for 64-bit machines) */
  1431. X}
  1432. X
  1433. X#endif /* !UTIL */
  1434. X
  1435. X
  1436. X#if (defined(MSDOS) && !defined(OS2) && !defined(__GO32__) && !defined(WIN32))
  1437. X
  1438. Xlocal unsigned ident(unsigned chr)
  1439. X{
  1440. X   return chr; /* in al */
  1441. X}
  1442. X
  1443. Xvoid init_upper()
  1444. X{
  1445. X  static struct country {
  1446. X    uch ignore[18];
  1447. X    int (far *casemap)(int);
  1448. X    uch filler[16];
  1449. X  } country_info;
  1450. X
  1451. X  struct country far *info = &country_info;
  1452. X  union REGS regs;
  1453. X  struct SREGS sregs;
  1454. X  int c;
  1455. X
  1456. X  regs.x.ax = 0x3800; /* get country info */
  1457. X  regs.x.dx = FP_OFF(info);
  1458. X  sregs.ds  = FP_SEG(info);
  1459. X  intdosx(®s, ®s, &sregs);
  1460. X  for (c = 0; c < 128; c++) {
  1461. X    upper[c] = (uch) toupper(c);
  1462. X    lower[c] = (uch) c;
  1463. X  }
  1464. X  for (; c < sizeof(upper); c++) {
  1465. X    upper[c] = (uch) (*country_info.casemap)(ident(c));
  1466. X    /* ident() required because casemap takes its parameter in al */
  1467. X    lower[c] = (uch) c;
  1468. X  }
  1469. X  for (c = 0; c < sizeof(upper); c++ ) {
  1470. X    int u = upper[c];
  1471. X    if (u != c && lower[u] == (uch) u) {
  1472. X      lower[u] = (uch)c;
  1473. X    }
  1474. X  }
  1475. X  for (c = 'A'; c <= 'Z'; c++) {
  1476. X    lower[c] = (uch) (c - 'A' + 'a');
  1477. X  }
  1478. X}
  1479. X#else
  1480. X#  ifndef OS2
  1481. X
  1482. Xvoid init_upper()
  1483. X{
  1484. X  int c;
  1485. X  for (c = 0; c < sizeof(upper); c++) upper[c] = lower[c] = c;
  1486. X  for (c = 'a'; c <= 'z';        c++) upper[c] = c - 'a' + 'A';
  1487. X  for (c = 'A'; c <= 'Z';        c++) lower[c] = c - 'A' + 'a';
  1488. X}
  1489. X#  endif /* OS2 */
  1490. X
  1491. X#endif /* MSDOS && !__GO32__ && !OS2 */
  1492. X
  1493. Xint namecmp(string1, string2)
  1494. X  char *string1, *string2;
  1495. X/* Compare the two strings ignoring case, and correctly taking into
  1496. X * account national language characters. For operating systems with
  1497. X * case sensitive file names, this function is equivalent to strcmp.
  1498. X */
  1499. X{
  1500. X  int d;
  1501. X
  1502. X  for (;;)
  1503. X  {
  1504. X    d = (int) (unsigned char) case_map(*string1)
  1505. X      - (int) (unsigned char) case_map(*string2);
  1506. X    
  1507. X    if (d || *string1 == 0 || *string2 == 0)
  1508. X      return d;
  1509. X      
  1510. X    string1++;
  1511. X    string2++;
  1512. X  }
  1513. X}
  1514. END_OF_FILE
  1515.   if test 12887 -ne `wc -c <'util.c'`; then
  1516.     echo shar: \"'util.c'\" unpacked with wrong size!
  1517.   fi
  1518.   # end of 'util.c'
  1519. fi
  1520. if test -f 'vms/makefile.vms' -a "${1}" != "-c" ; then 
  1521.   echo shar: Will not clobber existing file \"'vms/makefile.vms'\"
  1522. else
  1523.   echo shar: Extracting \"'vms/makefile.vms'\" \(3279 characters\)
  1524.   sed "s/^X//" >'vms/makefile.vms' <<'END_OF_FILE'
  1525. X#============================================================================
  1526. X# Makefile for VMS Zip, ZipCloak, ZipNote  and ZipSplit          Greg Roelofs
  1527. X# Version:  1.8f   [for use with Todd Aven's MAKE/VMS 3.4]       25 June 1992
  1528. X#============================================================================
  1529. X
  1530. X# Most recent revisions:  25 June 1992
  1531. X
  1532. X
  1533. X#####################
  1534. X# MACRO DEFINITIONS #
  1535. X#####################
  1536. X
  1537. XCRYPTO =
  1538. XCLOAK =
  1539. XCFLAGS =
  1540. XUFLAGS = /def=UTIL
  1541. X# Uncomment next three lines for decryption version:
  1542. X#CRYPTO = crypt.obj,
  1543. X#CLOAK = zipcloak.exe
  1544. X#CFLAGS = /def=CRYPT
  1545. X#UFLAGS = /def=(UTIL,CRYPT)
  1546. X
  1547. XCC = cc
  1548. XLIB =
  1549. X# Uncomment next two lines to use the GNU compiler (also add /undef=__STDC__
  1550. X# to CFLAGS and UFLAGS, possibly split UFLAGS into two /def's, and possibly
  1551. X# replace /obj=$@ [below] with copy/rename/delete setup).  NOT TESTED.
  1552. X#CC = gcc
  1553. X#LIB = gnu_cc:[000000]gcclib.olb/lib,
  1554. X
  1555. XE = .exe
  1556. XO = .obj
  1557. XLD = link
  1558. XLDFLAGS =
  1559. X
  1560. XZIPS = zip$E zipnote$E zipsplit$E $(CLOAK)
  1561. X
  1562. X# object file lists
  1563. XOBJZ = zip$O, zipfile$O, zipup$O, fileio$O, $(CRYPTO) util$O,-
  1564. X   globals$O, VMSmunch$O, vms$O
  1565. XOBJI = deflate$O, trees$O, bits$O
  1566. XOBJN = zipnote$O, zipfile_$O, zipup_$O, fileio_$O, util_$O,-
  1567. X   globals$O, VMSmunch$O
  1568. XOBJS = zipsplit$O, zipfile_$O, zipup_$O, fileio_$O, util_$O,-
  1569. X   globals$O, VMSmunch$O
  1570. XOBJC = zipcloak$O, zipfile_$O, zipup_$O, fileio_$O, util$O,-
  1571. X   globals$O, VMSmunch$O, crypt_$O
  1572. X
  1573. X
  1574. X###############################################
  1575. X# BASIC COMPILE INSTRUCTIONS AND DEPENDENCIES #
  1576. X###############################################
  1577. X
  1578. Xdefault:    $(ZIPS)
  1579. X
  1580. X
  1581. X# suffix rules
  1582. X*.obj:    *.c                # `*.c' necessary?
  1583. X    $(CC) $(CFLAGS) $<
  1584. X
  1585. X*_.obj:    *.c                # `$*' not legal
  1586. X    $(CC) $(UFLAGS) /obj=$@ $<
  1587. X
  1588. X
  1589. X# executables makerules (trailing `$' makes line a data line)
  1590. Xzip$E:        $(OBJZ), $(OBJI)
  1591. X    $(LD) $(LDFLAGS) $(OBJZ), $(OBJI), $(LIB) sys$input/opt
  1592. X    sys$share:vaxcrtl.exe/shareable $
  1593. X
  1594. Xzipnote$E:    $(OBJN)
  1595. X    $(LD) $(LDFLAGS) $(OBJN), $(LIB) sys$input/opt
  1596. X    sys$share:vaxcrtl.exe/shareable $
  1597. X
  1598. Xzipcloak$E:    $(OBJC)
  1599. X    $(LD) $(LDFLAGS) $(OBJC), $(LIB) sys$input/opt
  1600. X    sys$share:vaxcrtl.exe/shareable $
  1601. X
  1602. Xzipsplit$E:    $(OBJS)
  1603. X    $(LD) $(LDFLAGS) $(OBJS), $(LIB) sys$input/opt
  1604. X    sys$share:vaxcrtl.exe/shareable $
  1605. X
  1606. X# dependencies for zip, zipnote, zipcloak, and zipsplit
  1607. X$(OBJZ):    zip.h ziperr.h tailor.h
  1608. X$(OBJI):    zip.h ziperr.h tailor.h
  1609. X$(OBJN):    zip.h ziperr.h tailor.h
  1610. X$(OBJS):    zip.h ziperr.h tailor.h
  1611. X$(OBJC):    zip.h ziperr.h tailor.h
  1612. Xfileio$O:    VMSmunch.h
  1613. Xvms$O:          vms.c zip.h
  1614. XVMSmunch$O:     VMSmunch.c VMSmunch.h
  1615. Xzip$O:        revision.h
  1616. Xzipcloak$O:    revision.h
  1617. Xzipfile$O:    VMSmunch.h
  1618. Xzipnote$O:    revision.h
  1619. Xzipsplit$O:    revision.h
  1620. Xzipup$O:    revision.h
  1621. X
  1622. X
  1623. Xclean:
  1624. X    del *.obj;*
  1625. X    del *.exe;*         # use "purge/log" instead?
  1626. X
  1627. X
  1628. X# the backslash '\' is the continuation character if it occurs as
  1629. X# the last non-white character on the line.
  1630. X# the hyphen '-' is the DCL continuation character, so if it occurs
  1631. X# as the last non-white character on the line, the next line will
  1632. X# not have the dollar sign '$' prepended.
  1633. X
  1634. X
  1635. X################################
  1636. X# INDIVIDUAL MACHINE MAKERULES #
  1637. X################################
  1638. X
  1639. Xgeneric:    default        # first try if unknown
  1640. Xgeneric2:    default        # second try if unknown
  1641. Xvax:        default
  1642. Xvms:        default
  1643. X
  1644. Xall:        $(ZIPS)
  1645. Xzip:        zip$E
  1646. Xzipcloak:    zipcloak$E
  1647. Xzipnote:    zipnote$E
  1648. Xzipsplit:    zipsplit$E
  1649. END_OF_FILE
  1650.   if test 3279 -ne `wc -c <'vms/makefile.vms'`; then
  1651.     echo shar: \"'vms/makefile.vms'\" unpacked with wrong size!
  1652.   fi
  1653.   # end of 'vms/makefile.vms'
  1654. fi
  1655. echo shar: End of archive 3 \(of 11\).
  1656. cp /dev/null ark3isdone
  1657. MISSING=""
  1658. for I in 1 2 3 4 5 6 7 8 9 10 11 ; do
  1659.     if test ! -f ark${I}isdone ; then
  1660.     MISSING="${MISSING} ${I}"
  1661.     fi
  1662. done
  1663. if test "${MISSING}" = "" ; then
  1664.     echo You have unpacked all 11 archives.
  1665.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1666. else
  1667.     echo You still must unpack the following archives:
  1668.     echo "        " ${MISSING}
  1669. fi
  1670. exit 0
  1671. exit 0 # Just in case...
  1672.