home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 October / usenetsourcesnewsgroupsinfomagicoctober1994disk2.iso / misc / volume23 / zip / part01 next >
Text File  |  1991-10-21  |  55KB  |  1,599 lines

  1. Newsgroups: comp.sources.misc
  2. From: kirsch@usasoc.soc.mil (David Kirschbaum)
  3. Subject:  v23i088:  zip - Portable zip v1.0, Part01/09
  4. Message-ID: <csm-v23i088=zip.231424@sparky.IMD.Sterling.COM>
  5. X-Md4-Signature: 61134dcb2a8c2cb49e9e129416f582d3
  6. Date: Mon, 21 Oct 1991 04:20:22 GMT
  7. Approved: kent@sparky.imd.sterling.com
  8.  
  9. Submitted-by: kirsch@usasoc.soc.mil (David Kirschbaum)
  10. Posting-number: Volume 23, Issue 88
  11. Archive-name: zip/part01
  12. Environment: UNIX, Minix, MSDOS, OS/2, VMS
  13.  
  14. Here's the product of the Info-ZIP Workgroup:  a portable, generic
  15. compatible zip file compressor.  This is a companion to the unzip utility
  16. also distributed by this group.
  17.  
  18. I extracted the original zip10ex.zip distribution files, changed them all
  19. to Unix end_of_line, lower-cased a bunch of the file names (just to give
  20. the Unix systems something familiar), and used cshar (comp.sources.unix
  21. volume15) to create the Partnn shar files.  Other than those minor changes
  22. (for transmission only), all honor and glory to the original authors.
  23. (Be sure to contact *them* (or Info-ZIP@valeria.cs.ucla.edu) if there
  24. are any bugs or problems.)
  25.  
  26. Oh, yes, this is the *export* version (no encryption).  The domestic
  27. version (with encryption) is not available for general distribution
  28. (because of various Federal regulations).  No, you don't want to know.
  29.  
  30. Following is the README file from the original zip10ex.zip distribution.
  31.  
  32. David Kirschbaum
  33. Info-ZIP Coordinator
  34. kirsch@usasoc.soc.mil
  35. ===
  36. Copyright (C) 1990,1991 Mark Adler, Richard B. Wales, and Jean-loup Gailly.
  37. Permission is granted to any individual or institution to use, copy, or
  38. redistribute this software so long as all of the original files are included
  39. unmodified, that it is not sold for profit, and that this copyright notice
  40. is retained.
  41.  
  42. LIKE ANYTHING ELSE THAT'S FREE, ZIP AND ITS ASSOCIATED UTILITIES ARE
  43. PROVIDED AS IS AND COME WITH NO WARRANTY OF ANY KIND, EITHER EXPRESSED OR
  44. IMPLIED. IN NO EVENT WILL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES
  45. RESULTING FROM THE USE OF THIS SOFTWARE.
  46.  
  47. Please read the file zip.doc for information on how to compile, install, and
  48. use zip, zipcloak (if this is not an export version), zipsplit, zipnote, and
  49. ship.  The file "contents" is a complete list of the files you should have in
  50. this distribution.  Also, if you are using MSDOS, you should read the note on
  51. file formats at the end of the contents file.
  52. ----------
  53. #! /bin/sh
  54. # This is a shell archive.  Remove anything before this line, then feed it
  55. # into a shell via "sh file" or similar.  To overwrite existing files,
  56. # type "sh file -c".
  57. # The tool that generated this appeared in the comp.sources.unix newsgroup;
  58. # send mail to comp-sources-unix@uunet.uu.net if you want that tool.
  59. # Contents:  README im_ctree.c makevms.com
  60. # Wrapped by kent@sparky on Sun Oct 20 22:58:51 1991
  61. PATH=/bin:/usr/bin:/usr/ucb ; export PATH
  62. echo If this archive is complete, you will see the following message:
  63. echo '          "shar: End of archive 1 (of 9)."'
  64. if test -f 'README' -a "${1}" != "-c" ; then 
  65.   echo shar: Will not clobber existing file \"'README'\"
  66. else
  67.   echo shar: Extracting \"'README'\" \(929 characters\)
  68.   sed "s/^X//" >'README' <<'END_OF_FILE'
  69. XCopyright (C) 1990,1991 Mark Adler, Richard B. Wales, and Jean-loup Gailly.
  70. XPermission is granted to any individual or institution to use, copy, or
  71. Xredistribute this software so long as all of the original files are included
  72. Xunmodified, that it is not sold for profit, and that this copyright notice
  73. Xis retained.
  74. X
  75. XLIKE ANYTHING ELSE THAT'S FREE, ZIP AND ITS ASSOCIATED UTILITIES ARE
  76. XPROVIDED AS IS AND COME WITH NO WARRANTY OF ANY KIND, EITHER EXPRESSED OR
  77. XIMPLIED. IN NO EVENT WILL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY DAMAGES
  78. XRESULTING FROM THE USE OF THIS SOFTWARE.
  79. X
  80. XPlease read the file zip.doc for information on how to compile, install, and
  81. Xuse zip, zipcloak (if this is not an export version), zipsplit, zipnote, and
  82. Xship.  The file "contents" is a complete list of the files you should have in
  83. Xthis distribution.  Also, if you are using MSDOS, you should read the note on
  84. Xfile formats at the end of the contents file.
  85. END_OF_FILE
  86.   if test 929 -ne `wc -c <'README'`; then
  87.     echo shar: \"'README'\" unpacked with wrong size!
  88.   fi
  89.   # end of 'README'
  90. fi
  91. if test -f 'im_ctree.c' -a "${1}" != "-c" ; then 
  92.   echo shar: Will not clobber existing file \"'im_ctree.c'\"
  93. else
  94.   echo shar: Extracting \"'im_ctree.c'\" \(45523 characters\)
  95.   sed "s/^X//" >'im_ctree.c' <<'END_OF_FILE'
  96. X/*
  97. X
  98. X Copyright (C) 1990,1991 Mark Adler, Richard B. Wales, and Jean-loup Gailly.
  99. X Permission is granted to any individual or institution to use, copy, or
  100. X redistribute this software so long as all of the original files are included
  101. X unmodified, that it is not sold for profit, and that this copyright notice
  102. X is retained.
  103. X
  104. X*/
  105. X
  106. X/*
  107. X *  im_ctree.c by Richard B. Wales.
  108. X *
  109. X *  Includes modifications by Jean-Loup Gailly.
  110. X *
  111. X *  PURPOSE
  112. X *
  113. X *      Encode various sets of source values using variable-length
  114. X *      binary code trees.
  115. X *
  116. X *  DISCUSSION
  117. X *
  118. X *      The PKZIP "implosion" process uses several variable-depth binary
  119. X *      code trees, similar to Huffman trees.  The more common source
  120. X *      values are represented by shorter bit sequences.
  121. X *
  122. X *      Each code tree is stored in the ZIP file in a compressed form
  123. X *      that is essentially a run-length-encoded list of the lengths of
  124. X *      all the code strings (in ascending order by source values).
  125. X *      The actual code strings are reconstructed from the lengths in
  126. X *      the UNZIP process, as described in the "application note"
  127. X *      (APPNOTE.TXT) distributed as part of PKWARE's PKZIP program.
  128. X *
  129. X *      Because of the way a code tree is stored in the ZIP file, the
  130. X *      codes must conform to the following restrictions:
  131. X *
  132. X *      (1) No code string may ever exceed 16 bits in length.
  133. X *
  134. X *      (2) If all code strings are extended to 16 bits by padding on
  135. X *          the right (low-order end) with zeros, and then treated as
  136. X *          unsigned 16-bit integers, then:
  137. X *
  138. X *          (a) The arithmetically higher 16-bit values must correspond
  139. X *              to the shorter code strings.
  140. X *
  141. X *          (b) If two source values map into code strings of the same
  142. X *              length, the higher code string must correspond to the
  143. X *              lower source value (where source values are treated as
  144. X *              unsigned).
  145. X *
  146. X *      Further, shortcuts taken by PKUNZIP 1.10 in the way it decodes
  147. X *      the compressed data via the trees impose the following extra
  148. X *      limitations:
  149. X *
  150. X *      (3) No code string in the "distance" tree can be longer than 8
  151. X *          bits.
  152. X *
  153. X *      (4) The maximum length of any code string is limited by the
  154. X *          number of initial zero bits, as follows:
  155. X *
  156. X *          (a) 0-3 leading zeros:  maximum length is 8.
  157. X *
  158. X *          (b) 4-5 leading zeros:  maximum length is 12.
  159. X *
  160. X *          (c) 6-7 leading zeros:  maximum length is 14.
  161. X *
  162. X *      (5) In the "literal" tree, the code string corresponding to the
  163. X *          source value 255 must be at least 10 bits in length, regard-
  164. X *          less of the frequency of the value 255 in the file.
  165. X *
  166. X *      PKWARE calls the code trees "Shannon-Fano trees".  (Shannon-Fano
  167. X *      coding was a predecessor to the better-known Huffman coding
  168. X *      technique; see the references below.)  Although it appears that
  169. X *      the Shannon-Fano (top-down partitioning) algorithm is in fact
  170. X *      used by PKZIP in the process of creating the code trees, the
  171. X *      resulting trees are not in fact "pure" Shannon-Fano, because of
  172. X *      the extra processing required in order to meet the restrictions
  173. X *      described above.
  174. X *
  175. X *  REFERENCES
  176. X *
  177. X *      Lynch, Thomas J.
  178. X *          Data Compression:  Techniques and Applications, pp. 53-55.
  179. X *          Lifetime Learning Publications, 1985.  ISBN 0-534-03418-7.
  180. X *
  181. X *      Storer, James A.
  182. X *          Data Compression:  Methods and Theory, pp. 49-50.
  183. X *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
  184. X *
  185. X *  INTERFACE
  186. X *
  187. X *      ImpErr ct_init (void)
  188. X *          Initialize the code tree routines.  This routine must be
  189. X *          called before any other code tree routines may be called.
  190. X *
  191. X *      ImpErr ct_tally (MATCH *ma)
  192. X *          Tally a "string match" data set.  The tally results will be
  193. X *          used to determine how large the imploded result will be.
  194. X *
  195. X *      ImpErr ct_mktrees (FDATA *fd)
  196. X *          Construct all code trees, and then determine how big the
  197. X *          imploded file will be under both "literal tree" and "no
  198. X *          literal tree" conditions.  Choose the best option.
  199. X *
  200. X *      ImpErr ct_wrtrees (FILE *outfp)
  201. X *          Output the code trees to the ZIP file.
  202. X *
  203. X *      ImpErr ct_wrdata (FILE *outfp)
  204. X *          Output the file data to the ZIP file.
  205. X *
  206. X *      ImpErr ct_windup (void)
  207. X *          Deallocate all code trees.
  208. X */
  209. X
  210. X
  211. X#ifdef DEBUG
  212. X#   define VALIDATE
  213. X#endif /* DEBUG */
  214. X
  215. X#include "implode.h"
  216. X
  217. X
  218. X/***********************************************************************
  219. X *
  220. X * Local data used by the "code tree" routines.
  221. X */
  222. X
  223. X
  224. X/* Data structure describing a single value and its code string. */
  225. Xtypedef
  226. Xstruct  ct_data
  227. X    {   UL_INT  ct_freq;                /* frequency count */
  228. X        US_INT  ct_code;                /* bit string */
  229. X        U_CHAR  ct_len;                 /* length of bit string */
  230. X        U_CHAR  ct_val;                 /* source value */
  231. X    }
  232. X    TRDATA;
  233. X
  234. X
  235. X/*
  236. X * Data structure for re-sorting source values by bit string length;
  237. X * used during tree generation.
  238. X */
  239. Xtypedef
  240. Xstruct  ct_resort
  241. X    {   U_CHAR  ct_rlen;                /* length of bit string */
  242. X        U_CHAR  ct_rval;                /* source value */
  243. X#ifdef VMS
  244. X        US_INT  dummy;                  /* because of bug in qsort() */
  245. X#endif /* VMS */
  246. X    }
  247. X    RESORT;
  248. X
  249. X
  250. X/* Header for a code tree. */
  251. Xtypedef
  252. Xstruct  ct_desc
  253. X    {   TRDATA *ct_array;               /* array of TRDATA */
  254. X        int     ct_size;                /* # of entries in tree */
  255. X    }
  256. X    TRDESC;
  257. X
  258. X
  259. X/*
  260. X * Currently active code trees.
  261. X * We allow for five trees (one literal tree, two length trees, and
  262. X * two distance trees) so that we can evaluate the total compression
  263. X * with or without the use of the literal tree.  Remember that the
  264. X * minimum matching distance depends on whether or not a literal tree
  265. X * is used; hence, the "length" and "distance" trees will differ.
  266. X */
  267. X#define MAXTREES        5               /* max # of trees at once */
  268. Xlocal   TRDESC  ct_table[MAXTREES];
  269. X
  270. X
  271. X/* Macro to validate a code tree handle. */
  272. X#define VALID_HANDLE(x) \
  273. X        ((x) >= 0 && (x) < MAXTREES && ct_table[x].ct_array != NULL)
  274. X
  275. X
  276. X/*
  277. X * Assorted frequency counts.
  278. X * The "Minimum Match Length" (MML) is 2 if a "literal character" code
  279. X * tree is not used, or 3 if a "literal character" tree is used.  Thus,
  280. X * we need to keep two sets of "length" and "distance" frequency counts.
  281. X * Also, 2-character matches need to be counted separately; depending
  282. X * on whether a "literal character" tree is used or not, these will be
  283. X * processed either as literal characters or as distance/length pairs.
  284. X */
  285. X
  286. X/* Total number of source values from Pass One. */
  287. Xlocal   long    ct_litc_num;            /* total # literal chars */
  288. Xlocal   long    ct_lit2_num;            /* total # of 2-char matches */
  289. Xlocal   long    ct_strg_num;            /* total # of string matches */
  290. X
  291. X/* Source value frequencies for the five trees. */
  292. Xlocal   long    ct_litc_freq[256];      /* literal character freqs */
  293. Xlocal   long    ct_len2_freq[64];       /* length freqs (MML=2) */
  294. Xlocal   long    ct_len3_freq[64];       /* length freqs (MML=3) */
  295. Xlocal   long    ct_dst2_freq[64];       /* distance freqs (MML=2) */
  296. Xlocal   long    ct_dst3_freq[64];       /* distance freqs (MML=3) */
  297. X
  298. X/* Number of bits saved by using each of the trees. */
  299. Xlocal   long    ct_litc_saved;          /* literal tree */
  300. Xlocal   long    ct_len2_saved;          /* length tree (MML=2) */
  301. Xlocal   long    ct_len3_saved;          /* length tree (MML=3) */
  302. Xlocal   long    ct_dst2_saved;          /* distance tree (MML=2) */
  303. Xlocal   long    ct_dst3_saved;          /* distance tree (MML=3) */
  304. X
  305. X/* Handles for the code trees to be used. */
  306. Xlocal   int     ct_litc_tree;           /* temp literal tree */
  307. Xlocal   int     ct_len2_tree;           /* temp length tree (MML=2) */
  308. Xlocal   int     ct_len3_tree;           /* temp length tree (MML=3) */
  309. Xlocal   int     ct_dst2_tree;           /* temp distance tree (MML=2) */
  310. Xlocal   int     ct_dst3_tree;           /* temp distance tree (MML=3) */
  311. Xlocal   int     lit_tree;               /* literal tree (-1 if none) */
  312. Xlocal   int     len_tree;               /* length tree */
  313. Xlocal   int     dst_tree;               /* distance tree */
  314. X
  315. X
  316. X/***********************************************************************
  317. X *
  318. X * Local (static) routines in this file.
  319. X */
  320. X
  321. Xlocal ImpErr ct_alloc
  322. X        OF ((int size, int *handle));
  323. X
  324. Xlocal ImpErr ct_free
  325. X        OF ((int handle));
  326. X
  327. Xlocal ImpErr ct_loadf
  328. X        OF ((int handle, long *freq));
  329. X
  330. Xlocal ImpErr ct_ziprep
  331. X        OF ((int handle, U_CHAR **result));
  332. X
  333. Xlocal ImpErr ct_gencodes
  334. X        OF ((int handle, int minbits, int maxbits, long *saved));
  335. X
  336. Xlocal ImpErr ct_split
  337. X        OF ((TRDATA *part, int size, long freq,
  338. X             int prefix, int preflen, int minbits, int maxbits));
  339. X
  340. Xlocal int ct_fsort
  341. X        OF ((TRDATA *tr1, TRDATA *tr2));
  342. X
  343. Xlocal int ct_rsort
  344. X        OF ((RESORT *cr1, RESORT *cr2));
  345. X
  346. X
  347. X/***********************************************************************
  348. X *
  349. X * Allocate a code tree.
  350. X */
  351. X
  352. Xlocal
  353. XImpErr
  354. Xct_alloc (size, handle)
  355. X    int size;
  356. X    int *handle;
  357. X{   register TRDATA *ct;
  358. X    int n;
  359. X
  360. X#ifdef VALIDATE
  361. X    /* Validate the arguments. */
  362. X    if (size < 2 || size > 256) goto badarg;
  363. X    if (handle == NULL)         goto badarg;
  364. X#endif /* VALIDATE */
  365. X
  366. X    /* Allocate an available code tree handle. */
  367. X    for (n = 0;
  368. X         n < MAXTREES && ct_table[n].ct_array != NULL;
  369. X         n++) ;
  370. X    if (n >= MAXTREES) return IM_NOCTBLS;
  371. X    *handle = n;
  372. X    ct_table[n].ct_size  = size;
  373. X
  374. X    /* Allocate space for the code tree. */
  375. X    ct = (TRDATA *) malloc ((unsigned) (size * sizeof (TRDATA)));
  376. X    if (ct == NULL) return IM_NOMEM;
  377. X    ct_table[n].ct_array = ct;
  378. X
  379. X    /* Initialize the code tree. */
  380. X    for (n = 0; n < size; n++, ct++)
  381. X    {   ct->ct_freq = 0;
  382. X        ct->ct_code = 0;
  383. X        ct->ct_val  = (U_CHAR)n;
  384. X        ct->ct_len  = 0;
  385. X    }
  386. X
  387. X    /* That's all. */
  388. X    return IM_OK;
  389. X
  390. X#ifdef VALIDATE
  391. Xbadarg:
  392. X    fprintf (stderr, "\nError in ct_alloc: bad argument(s)");
  393. X    return IM_BADARG;
  394. X#endif /* VALIDATE */
  395. X}
  396. X
  397. X
  398. X/***********************************************************************
  399. X *
  400. X * Free a code tree.
  401. X */
  402. X
  403. Xlocal
  404. XImpErr
  405. Xct_free (handle)
  406. X    int handle;
  407. X{
  408. X#ifdef VALIDATE
  409. X    /* Validate the argument. */
  410. X    if (!VALID_HANDLE (handle)) goto badarg;
  411. X#endif /* VALIDATE */
  412. X
  413. X    /* Free the code tree. */
  414. X    free ((char *) ct_table[handle].ct_array);
  415. X    ct_table[handle].ct_array = NULL;
  416. X    ct_table[handle].ct_size  = 0;
  417. X
  418. X    /* That's all. */
  419. X    return IM_OK;
  420. X
  421. X#ifdef VALIDATE
  422. Xbadarg:
  423. X    fprintf (stderr, "\nError in ct_free: bad argument(s)");
  424. X    return IM_BADARG;
  425. X#endif /* VALIDATE */
  426. X}
  427. X
  428. X
  429. X/***********************************************************************
  430. X *
  431. X * Update a code tree with frequency data.
  432. X *
  433. X * In order to allow for the later addition of "adaptive" coding,
  434. X * the new frequencies are added to the existing data.
  435. X */
  436. X
  437. Xlocal
  438. XImpErr
  439. Xct_loadf (handle, freq)
  440. X    int   handle;
  441. X    long *freq;
  442. X{   register long *f;
  443. X    register TRDATA *ct;
  444. X    int n;
  445. X
  446. X#ifdef VALIDATE
  447. X    /* Validate the arguments. */
  448. X    if (!VALID_HANDLE (handle)) goto badarg;
  449. X#endif /* VALIDATE */
  450. X
  451. X    /* Add in the frequencies. */
  452. X    for (f = freq,
  453. X             ct = ct_table[handle].ct_array,
  454. X             n = ct_table[handle].ct_size;
  455. X         n > 0;
  456. X         f++, ct++, n--)
  457. X        ct->ct_freq += *f;
  458. X
  459. X    /* That's all. */
  460. X    return IM_OK;
  461. X
  462. X#ifdef VALIDATE
  463. Xbadarg:
  464. X    fprintf (stderr, "\nError in ct_loadf: bad argument(s)");
  465. X    return IM_BADARG;
  466. X#endif /* VALIDATE */
  467. X}
  468. X
  469. X
  470. X/***********************************************************************
  471. X *
  472. X * Generate the ZIP-file representation for a code tree.
  473. X *
  474. X * The returned "result" value points to static data which will be
  475. X * overwritten on the next call to "ct_ziprep".
  476. X *
  477. X * The length of the result string is implicit in the first byte of
  478. X * the value, as specified in the PKZIP applications note.
  479. X */
  480. X
  481. X#ifdef IMPDEBUG
  482. Xchar *treename;
  483. X#endif /* IMPDEBUG */
  484. X
  485. Xlocal
  486. XImpErr
  487. Xct_ziprep (handle, result)
  488. X    int      handle;
  489. X    U_CHAR **result;
  490. X{   static U_CHAR buffer[257];          /* result info */
  491. X    register U_CHAR *c;
  492. X    register TRDATA *ct;
  493. X    int s, n, l;
  494. X
  495. X#ifdef VALIDATE
  496. X    /* Validate the arguments. */
  497. X    if (!VALID_HANDLE (handle)) goto badarg;
  498. X    if (result == NULL)         goto badarg;
  499. X#endif /* VALIDATE */
  500. X
  501. X#ifdef  IMPDEBUG
  502. X    if (treename != NULL && treename[0] != 0)
  503. X    {   /* Print the code tree info. */
  504. X        fprintf (stderr, "\n%s tree:\n  value      len   string\n",
  505. X                 treename);
  506. X        for (ct = ct_table[handle].ct_array,
  507. X                  s = ct_table[handle].ct_size,
  508. X                  n = 0;
  509. X             s > 0;
  510. X             ct++, n++, s--)
  511. X            fprintf (stderr, "  %3d (%02x)    %2d    %04x (rev %04x)\n",
  512. X                     n, n, ct->ct_len,
  513. X                     bi_reverse(ct->ct_code << (16 - ct->ct_len),
  514. X                                ct->ct_len) << (16 - ct->ct_len),
  515. X                     ct->ct_code);
  516. X    }
  517. X#endif  /* IMPDEBUG */
  518. X
  519. X    /* Generate the returned value. */
  520. X    for (c = buffer+1,
  521. X             ct = ct_table[handle].ct_array,
  522. X             s = ct_table[handle].ct_size,
  523. X             n = 0,
  524. X             l = ct->ct_len;
  525. X         s > 0;
  526. X         ct++, s--)
  527. X    {   if (l < 1 || l > 16)
  528. X        {   fprintf (stderr, "\nError in ct_ziprep: bad code length");
  529. X            return IM_LOGICERR;
  530. X        }
  531. X        if (n >= 16 || (int)ct->ct_len != l)
  532. X        {   *c++ = (U_CHAR)((((n-1) << 4) & 0xf0) | ((l-1) & 0x0f));
  533. X            n = 1; l = ct->ct_len;
  534. X        }
  535. X        else n++;
  536. X    }
  537. X    if (n > 0)
  538. X        *c++ = (U_CHAR)((((n-1) << 4) & 0xf0) | ((l-1) & 0x0f));
  539. X    buffer[0] = (U_CHAR)((c - buffer) - 2);
  540. X
  541. X    /* That's all. */
  542. X    *result = buffer;
  543. X    return IM_OK;
  544. X
  545. X#ifdef VALIDATE
  546. Xbadarg:
  547. X    fprintf (stderr, "\nError in ct_ziprep: bad argument(s)");
  548. X    return IM_BADARG;
  549. X#endif /* VALIDATE */
  550. X}
  551. X
  552. X
  553. X/***********************************************************************
  554. X *
  555. X * Look up the code string for a given value.
  556. X */
  557. X
  558. X#define ct_lookup(handle, value, string, length) \
  559. X{   register TRDATA *ct; \
  560. X    ct = ct_table[handle].ct_array + (value); \
  561. X    string = ct->ct_code; \
  562. X    length = ct->ct_len; \
  563. X}
  564. X
  565. X
  566. X/***********************************************************************
  567. X *
  568. X * Generate the codes for a code tree.  If old codes already exist for
  569. X * the tree, they are discarded, and a new set of codes is generated
  570. X * from scratch.
  571. X * IN assertion: ma_buf is already allocated and can be overwritten.
  572. X */
  573. X
  574. Xlocal
  575. XImpErr
  576. Xct_gencodes (handle, minbits, maxbits, saved)
  577. X    int   handle;                       /* which tree */
  578. X    int   minbits;                      /* min code string bit length */
  579. X    int   maxbits;                      /* max code string bit length */
  580. X    long *saved;                        /* how many bits saved */
  581. X{   register TRDATA *ct;
  582. X    TRDATA *ct2;
  583. X    register int n;
  584. X    UL_INT f;
  585. X    register RESORT *cr;
  586. X    int code, srclen;
  587. X    long totalfreq, totalbits;
  588. X    ImpErr retcode;
  589. X    RESORT rbuf[256];
  590. X    int size; /* alias for ct_table[handle].ct_size */
  591. X    int z;    /* index of zero frequency element */
  592. X    int nz;   /* index of non zero frequency element */
  593. X
  594. X#ifdef VALIDATE
  595. X    /* Validate the arguments. */
  596. X    if (!VALID_HANDLE (handle)) goto badarg;
  597. X    if (minbits < 1)            goto badarg;
  598. X    if (maxbits > 16)           goto badarg;
  599. X    if (maxbits < minbits)      goto badarg;
  600. X    if (saved == NULL)          goto badarg;
  601. X#endif /* VALIDATE */
  602. X    size = ct_table[handle].ct_size;
  603. X
  604. X    /*
  605. X     * Start by sorting the data by frequency.  The source values with
  606. X     * higher frequency need to get the shorter Shannon-Fano codes.
  607. X     * First exclude the elements with zero frequency, to speed up the sort.
  608. X     * This optimization is very important for small files, otherwise the sort
  609. X     * takes most of the implode time.
  610. X     *    Also determine the total of all frequencies.  This will be needed in
  611. X     * order to partition the source values in the Shannon-Fano bit
  612. X     * string computation. Finally clear the "code" (bit string) and "len"
  613. X     * (bit string length) fields in the code tree array.
  614. X     */
  615. X    totalfreq = 0;
  616. X    ct = ct_table[handle].ct_array;
  617. X    /* Copy ct into a tempo */
  618. X    ct2 = (TRDATA*) ma_buf;
  619. X    memcpy((char*)ct2, (char*)ct, size * sizeof(TRDATA));
  620. X    for (nz = 0, z = n = size-1; n >= 0; n--) {
  621. X        int m;
  622. X        if (ct2[n].ct_freq != 0L) {
  623. X            m = nz++;
  624. X            totalfreq += (ct[m].ct_freq = ct2[n].ct_freq);
  625. X        } else {
  626. X            m = z--;
  627. X            ct[m].ct_freq = 0L;
  628. X        }
  629. X        ct[m].ct_code = 0;
  630. X        ct[m].ct_len = 0;
  631. X        ct[m].ct_val = (U_CHAR)n; /* ct2[n].ct_val */
  632. X    }
  633. X    qsort ((char *) (ct_table[handle].ct_array), nz,
  634. X           sizeof (TRDATA), (int (*)())ct_fsort);
  635. X
  636. X    /*
  637. X     * Generate the bit strings via a Shannon-Fano (top-down) algorithm.
  638. X     */
  639. X    retcode =
  640. X        ct_split (ct_table[handle].ct_array,    /* partition start */
  641. X                  size,                         /* partition size */
  642. X                  totalfreq,                    /* total frequency */
  643. X                  0,                            /* code string prefix */
  644. X                  0,                            /* # bits in prefix */
  645. X                  minbits,                      /* minimum tree depth */
  646. X                  maxbits);                     /* maximum tree depth */
  647. X    if (retcode != IM_OK) return retcode;
  648. X
  649. X    /*
  650. X     * The source value 255 needs to be assigned a bit string with a
  651. X     * length of at least 10, in order to accommodate shortcuts in
  652. X     * PKUNZIP's decoding algorithm.  If no bit string in the tree is
  653. X     * of length 10, we assign 255 to the longest string and hope for
  654. X     * the best.
  655. X     */
  656. X    n = size;
  657. X    if (n == 256)
  658. X    {   for (ct = ct_table[handle].ct_array;
  659. X             n > 0 && ct->ct_val != 255;
  660. X             n--, ct++) ;
  661. X        if (n == 0)
  662. X        {   fprintf (stderr, "\nError in ct_gencodes: no value 255");
  663. X            return IM_LOGICERR;
  664. X        }
  665. X        if (ct->ct_len < 10)
  666. X        {   ct2 = ct;
  667. X            while (n > 0 && ct->ct_len < 10) n--, ct++;
  668. X            if (n == 0) ct--;   /* no len>=10 in tree; use longest */
  669. X            n = ct->ct_val;
  670. X                ct->ct_val = ct2->ct_val;
  671. X                ct2->ct_val = (U_CHAR)n;
  672. X            f = ct->ct_freq;
  673. X                ct->ct_freq = ct2->ct_freq;
  674. X                ct2->ct_freq = f;
  675. X    }   }
  676. X
  677. X    /*
  678. X     * The source values need to be re-sorted so that all source values
  679. X     * with code strings of the same length will be in ascending order.
  680. X     * This is because of the compression scheme used to represent the
  681. X     * tree in the ZIP file.
  682. X     */
  683. X    for (n = size,
  684. X             ct = ct_table[handle].ct_array,
  685. X             cr = rbuf;
  686. X         n > 0;
  687. X         n--, ct++, cr++)
  688. X    {   cr->ct_rlen = ct->ct_len;
  689. X        cr->ct_rval = ct->ct_val;
  690. X    }
  691. X    n = size;
  692. X    qsort ((char *) rbuf, n, sizeof (RESORT), (int (*)())ct_rsort);
  693. X    for (ct = ct_table[handle].ct_array,
  694. X             cr = rbuf;
  695. X         n > 0;
  696. X         n--, ct++, cr++)
  697. X        ct->ct_val = cr->ct_rval;
  698. X
  699. X#ifdef DUMP_TREE
  700. X    printf ("Finished tree:\n");
  701. X    for (n = size,
  702. X             ct = ct_table[handle].ct_array;
  703. X         n > 0;
  704. X         n--, ct++)
  705. X        printf ("  %3d (0x%02x)  l %2d  c 0x%04x f %ld\n",
  706. X                ct->ct_val, ct->ct_val, ct->ct_len, ct->ct_code, ct->ct_freq);
  707. X    putchar ('\n');
  708. X#endif /* DUMP_TREE */
  709. X
  710. X    /*
  711. X     * Finally, sort the tree back in ascending order by source value
  712. X     * -- which is the order expected by other portions of the program.
  713. X     */
  714. X    ct = ct_table[handle].ct_array;
  715. X    /* Copy ct into a tempo */
  716. X    ct2 = (TRDATA*)ma_buf;
  717. X    memcpy((char*)ct2, (char*)ct, size * sizeof(TRDATA));
  718. X    for (n = size-1; n >= 0; n--) {
  719. X        U_CHAR v = ct2[n].ct_val;
  720. X        ct[v].ct_freq = ct2[n].ct_freq;
  721. X        ct[v].ct_code = ct2[n].ct_code;
  722. X        ct[v].ct_len = ct2[n].ct_len;
  723. X        ct[v].ct_val = v;
  724. X    }
  725. X
  726. X    /*
  727. X     * Determine how many bits will be saved if all the source data is
  728. X     * encoded using this new set of code strings, as opposed to being
  729. X     * represented directly in unencoded form.
  730. X     */
  731. X    /* # of bits needed for unencoded source values */
  732. X    n = ct_table[handle].ct_size;
  733. X    for (code = 1, srclen = 0; code < n; code <<= 1, srclen++) ;
  734. X    /* # of bits used if all source values encoded via this tree */
  735. X    for (ct = ct_table[handle].ct_array,
  736. X             totalbits = 0;
  737. X         n > 0;
  738. X         n--, ct++)
  739. X        totalbits += ct->ct_freq * ct->ct_len;
  740. X    /* # bits saved by using the tree */
  741. X    *saved = (totalfreq * srclen) - totalbits;
  742. X
  743. X    /* That's all. */
  744. X    return IM_OK;
  745. X
  746. X#ifdef VALIDATE
  747. Xbadarg:
  748. X    fprintf (stderr, "\nError in ct_gencodes: bad argument(s)");
  749. X    return IM_BADARG;
  750. X#endif /* VALIDATE */
  751. X}
  752. X
  753. X
  754. X/***********************************************************************
  755. X *
  756. X * Split a portion of a code tree into two pieces of approximately equal
  757. X * total frequency.  This routine calls itself recursively in order to
  758. X * generate the bit strings for the entire code tree.
  759. X */
  760. X
  761. Xlocal
  762. XImpErr
  763. Xct_split (part, size, freq, prefix, preflen, minbits, maxbits)
  764. X    TRDATA *part;               /* start of partition */
  765. X    int     size;               /* # elements in partition */
  766. X    long    freq;               /* sum of frequencies in partition */
  767. X    int     prefix;             /* initial code bits for partition */
  768. X    int     preflen;            /* # bits in prefix */
  769. X    int     minbits;            /* minimum permissible bit length */
  770. X    int     maxbits;            /* maximum permissible bit length */
  771. X{   register TRDATA *ct;
  772. X    int topmaxbits, botmaxbits, localminbits;
  773. X    U_INT topmaxvals, botmaxvals;
  774. X    int topsize, botsize;
  775. X    long topfreq, botfreq, halffreq, onefreq;
  776. X    int n, m, leadzeros;
  777. X    int maxshort, minlong;
  778. X    ImpErr retcode;
  779. X    static maxarray[17] =
  780. X        { 8,8,8,8,12,12,14,14,16,16,16,16,16,16,16,16,16 };
  781. X
  782. X#ifdef VALIDATE
  783. X    if (part == NULL)           goto badarg;
  784. X    if (size < 1)               goto badarg;
  785. X    if (freq < 0)               goto badarg;
  786. X    if (preflen < 0)            goto badarg;
  787. X    if (preflen > maxbits)      goto badarg;
  788. X    if (minbits < preflen)      goto badarg;
  789. X    if (maxbits > 16)           goto badarg;
  790. X    if (maxbits < minbits)      goto badarg;
  791. X    /*
  792. X    putc ('\n', stderr);
  793. X    for (n = preflen; n > 0; n--) fprintf (stderr, "   ");
  794. X    fprintf (stderr, "ct_split (sz=%d, pr=%04x[%d], min=%d, max=%d)",
  795. X             size, prefix, preflen, minbits, maxbits);
  796. X    */
  797. X#endif /* VALIDATE */
  798. X
  799. X    /*
  800. X     * If there's only one element in this partition, we simply take
  801. X     * the "prefix" value as the code string for the single element.
  802. X     * We reverse the bits of the prefix for more efficient output.
  803. X     */
  804. X    if (size == 1)
  805. X    {   part->ct_code = bi_reverse(prefix, preflen);
  806. X        part->ct_len  = (U_CHAR)preflen;
  807. X        return IM_OK;
  808. X    }
  809. X
  810. X    /*
  811. X     * This partition will be divided into two parts.  The "top" part
  812. X     * will have a "1" bit appended to its "prefix" bit string; the
  813. X     * "bottom" part will have a "0" bit appended to its "prefix".
  814. X     *
  815. X     * We need to determine the maximum number of source values which
  816. X     * may be assigned to the two partitions.  The first issue to con-
  817. X     * sider is that PKUNZIP 1.10's tree-decoding shortcuts require a
  818. X     * certain number of leading "0" bits in each code string, depending
  819. X     * on its length.  Code strings of 9-12 bits must have at least 4
  820. X     * leading zeros; strings of 13 or 14 bits, at least 6 leading
  821. X     * zeros; and strings of 15 or 16 bits, at least 8 leading zeros.
  822. X     *
  823. X     * If the "prefix" is zero, the above limitation is used to restrict
  824. X     * the maximum size of the top half of the partition.  The bottom
  825. X     * half does not need to be restricted in this way, since it can be
  826. X     * extended as far as needed along the path where the "prefix" grows
  827. X     * in length but remains all zero.
  828. X     */
  829. X    botmaxbits = maxbits;
  830. X    if (prefix != 0) topmaxbits = maxbits;
  831. X    else
  832. X    {   for (n = 0, leadzeros = 0x8000;
  833. X             n < preflen && (prefix & leadzeros) == 0;
  834. X             n++, leadzeros >>= 1) ;
  835. X        topmaxbits = maxarray[n];
  836. X        if (topmaxbits > maxbits) topmaxbits = maxbits;
  837. X    }
  838. X    if (topmaxbits < minbits)
  839. X    {   fprintf (stderr, "\nError in ct_split: ");
  840. X        fprintf (stderr, "topmaxbits(%d) < minbits(%d)",
  841. X                 topmaxbits, minbits);
  842. X        goto oops;
  843. X    }
  844. X    if (botmaxbits < minbits)
  845. X    {   fprintf (stderr, "\nError in ct_split: ");
  846. X        fprintf (stderr, "botmaxbits(%d) < minbits(%d)",
  847. X                 botmaxbits, minbits);
  848. X        goto oops;
  849. X    }
  850. X    topmaxvals = 1 << (topmaxbits - preflen - 1);
  851. X    n = size >> 1; if (topmaxvals > n) topmaxvals = n;
  852. X    botmaxvals = 1 << (botmaxbits - preflen - 1);
  853. X    n = size - 1;  if (botmaxvals > n) botmaxvals = n;
  854. X    if (topmaxvals + botmaxvals < size)
  855. X    {   fprintf (stderr, "\nError in ct_split: ");
  856. X        fprintf (stderr, "topmaxvals(%d) + botmaxvals(%d) ",
  857. X                 topmaxvals, botmaxvals);
  858. X        fprintf (stderr, "< size(%d)", size);
  859. X        goto oops;
  860. X    }
  861. X
  862. X    /*
  863. X     * We now split the current partition into two halves of as close
  864. X     * to equal frequency as possible.  If the total of all frequencies
  865. X     * in the partition is zero, split into two halves of equal size.
  866. X     */
  867. X    if (freq == 0)
  868. X    {   topsize = size >> 1;
  869. X        ct = part + topsize;
  870. X        topfreq = 0;
  871. X    }
  872. X    else
  873. X    {   halffreq = freq >> 1;           /* half the total frequency */
  874. X        m = size >> 1;                  /* half the total elements, */
  875. X                                        /*    rounded down          */
  876. X        for (topsize = 0, topfreq = 0, ct = part;
  877. X             topsize < m && topfreq <= halffreq
  878. X                 && (onefreq = ct->ct_freq) > 0;
  879. X             topsize++, ct++)
  880. X            topfreq += onefreq;
  881. X        if (topsize >= 2)
  882. X        {   /*
  883. X             * If moving one element from the top to the bottom parti-
  884. X             * tion would make the two more closely equal in frequency,
  885. X             * do it.
  886. X             */
  887. X            onefreq = (ct-1)->ct_freq;
  888. X            if ((topfreq - halffreq) > (halffreq - (topfreq - onefreq)))
  889. X                ct--, topsize--, topfreq -= onefreq;
  890. X    }   }
  891. X    botsize = size - topsize;
  892. X    botfreq = freq - topfreq;
  893. X    /* "ct" points to first element in bottom half */
  894. X
  895. X    /*
  896. X     * The above first-cut attempt to split the partition may not work
  897. X     * for one of two reasons.  First, one or the other half may contain
  898. X     * too many values (more than "topmaxvals" or "botmaxvals").
  899. X     */
  900. X    while (topsize > topmaxvals)
  901. X    {   onefreq = (--ct)->ct_freq;
  902. X        topsize--; topfreq -= onefreq;
  903. X        botsize++; botfreq += onefreq;
  904. X    }
  905. X    while (botsize > botmaxvals)
  906. X    {   onefreq = (ct++)->ct_freq;
  907. X        topsize++; topfreq += onefreq;
  908. X        botsize--; botfreq -= onefreq;
  909. X    }
  910. X
  911. X    /*
  912. X     * Second, the number of bits required to represent the values in
  913. X     * each half may violate PKZIP's requirement (implicit in the way
  914. X     * trees are compressed in an imploded file) that no code string in
  915. X     * the top half may be longer than any code string in the bottom
  916. X     * half.
  917. X     */
  918. X    localminbits = preflen + 1;
  919. X    if (localminbits < minbits) localminbits = minbits;
  920. X    for (;;)
  921. X    {   for (maxshort = preflen + 1, n = 1;
  922. X             n < botsize;
  923. X             maxshort++, n <<= 1) ;
  924. X        if (n > botsize) maxshort--;
  925. X        if (maxshort < localminbits) maxshort = localminbits;
  926. X        if (maxshort > topmaxbits) maxshort = topmaxbits;
  927. X        for (minlong = preflen + 1, n = 1;
  928. X             n < topsize;
  929. X             minlong++, n <<= 1) ;
  930. X        if (minlong <= maxshort) break;
  931. X        onefreq = (--ct)->ct_freq;
  932. X        topsize--; topfreq -= onefreq;
  933. X        botsize++; botfreq += onefreq;
  934. X    }
  935. X
  936. X    /*
  937. X     * Third, the number of elements in the top half must be enough to
  938. X     * result in each string having at least "minbits" bits in all.
  939. X     */
  940. X    n = 1 << (minbits - preflen - 1);
  941. X    while (topsize < n)
  942. X    {   onefreq = (ct++)->ct_freq;
  943. X        topsize++; topfreq += onefreq;
  944. X        botsize--; botfreq -= onefreq;
  945. X    }
  946. X
  947. X    /*
  948. X     * Now that the sizes of the two halves of the partition have been
  949. X     * finalized, process the top and bottom halves via recursion.
  950. X     */
  951. X    retcode = ct_split (part, topsize, topfreq,
  952. X                        prefix | (1 << (15-preflen)),
  953. X                        preflen + 1, localminbits, maxshort);
  954. X    if (retcode != IM_OK) return retcode;
  955. X    ct = part + topsize;
  956. X    retcode = ct_split (ct, botsize, botfreq,
  957. X                        prefix, preflen + 1, (int)ct[-1].ct_len, maxbits);
  958. X    if (retcode != IM_OK) return retcode;
  959. X
  960. X    /* That's all. */
  961. X    return IM_OK;
  962. X
  963. X#ifdef VALIDATE
  964. Xbadarg:
  965. X    fprintf (stderr, "\nError in ct_split: bad argument(s)");
  966. X    putchar ('\n'); fflush (stdout); fflush (stderr);
  967. X    /* abort (); */
  968. X    return IM_BADARG;
  969. X#endif /* VALIDATE */
  970. X
  971. Xoops:
  972. X#ifdef VALIDATE
  973. X    putchar ('\n'); fflush (stdout); fflush (stderr);
  974. X    /* abort (); */
  975. X#endif /* VALIDATE */
  976. X    return IM_LOGICERR;
  977. X}
  978. X
  979. X
  980. X/***********************************************************************
  981. X *
  982. X * Sorting function -- descending order by source value frequency.
  983. X *
  984. X * This sorting function is used at the start of the code tree con-
  985. X * struction process, before the bit string values are assigned.
  986. X * To ensure consistent behaviour on all machines, we use the source
  987. X * values as secondary sort key, but this is not mandatory.
  988. X */
  989. X
  990. Xlocal
  991. Xint
  992. Xct_fsort (tr1, tr2)
  993. X    TRDATA *tr1, *tr2;
  994. X{   long d;
  995. X    int v;
  996. X
  997. X    d = (long) tr1->ct_freq - (long) tr2->ct_freq;
  998. X    if (d < 0) return 1;
  999. X    if (d > 0) return -1;
  1000. X    v = (int) tr1->ct_val - (int) tr2->ct_val;
  1001. X    if (v < 0) return 1;
  1002. X    if (v > 0) return -1;
  1003. X    return 0;
  1004. X}
  1005. X
  1006. X
  1007. X/***********************************************************************
  1008. X *
  1009. X * Sorting function -- ascending order by bit string length; if lengths
  1010. X * are the same, ascending order by source value.
  1011. X *
  1012. X * This sorting function is used after the bit string values have been
  1013. X * assigned.  
  1014. X */
  1015. X
  1016. Xlocal
  1017. Xint
  1018. Xct_rsort (cr1, cr2)
  1019. X    RESORT *cr1, *cr2;
  1020. X{   int d;
  1021. X
  1022. X    d = (int) cr1->ct_rlen - (int) cr2->ct_rlen;
  1023. X    if (d > 0) return 1;
  1024. X    if (d < 0) return -1;
  1025. X    d = (int) cr1->ct_rval - (int) cr2->ct_rval;
  1026. X    if (d > 0) return 1;
  1027. X    if (d < 0) return -1;
  1028. X    return 0;
  1029. X}
  1030. X
  1031. X
  1032. X/***********************************************************************
  1033. X *
  1034. X * Allocate the code trees.
  1035. X */
  1036. X
  1037. XImpErr
  1038. Xct_init ()
  1039. X{   ImpErr retcode;
  1040. X    int i;
  1041. X
  1042. X#ifdef DEBUG
  1043. X    if (256*sizeof(TRDATA) > MA_BUFSIZE*sizeof(MATCH)) return IM_LOGICERR;
  1044. X#endif /* DEBUG */
  1045. X
  1046. X    retcode = ct_windup ();
  1047. X        if (retcode != IM_OK) return retcode;
  1048. X
  1049. X    ct_litc_num = 0;
  1050. X    ct_lit2_num = 0;
  1051. X    ct_strg_num = 0;
  1052. X
  1053. X    for (i = 255; i >= 0;  i--)
  1054. X        ct_litc_freq[i] = 0;
  1055. X    for (i = 63; i >= 0; i--)
  1056. X        ct_len2_freq[i] = 0, ct_len3_freq[i] = 0,
  1057. X        ct_dst2_freq[i] = 0, ct_dst3_freq[i] = 0;
  1058. X
  1059. X    retcode = ct_alloc (256, &ct_litc_tree);
  1060. X    if (retcode != IM_OK) return retcode;
  1061. X    retcode = ct_alloc  (64, &ct_len2_tree);
  1062. X    if (retcode != IM_OK) return retcode;
  1063. X    retcode = ct_alloc  (64, &ct_len3_tree);
  1064. X    if (retcode != IM_OK) return retcode;
  1065. X    retcode = ct_alloc  (64, &ct_dst2_tree);
  1066. X    if (retcode != IM_OK) return retcode;
  1067. X    retcode = ct_alloc  (64, &ct_dst3_tree);
  1068. X    if (retcode != IM_OK) return retcode;
  1069. X
  1070. X    return IM_OK;
  1071. X}
  1072. X
  1073. X
  1074. X/***********************************************************************
  1075. X *
  1076. X * Tally a "string match" data set.  The tally results will be used to
  1077. X * determine how large the imploded result will be.
  1078. X */
  1079. X
  1080. XImpErr
  1081. Xct_tally (ma)
  1082. X         MATCH *ma;             /* match data to write out */
  1083. X{   register int ch;
  1084. X    int dist = ma->ma_dist;
  1085. X
  1086. X    /* Tally up the latest data. */
  1087. X    if (dist == 0) {                 /* literal character */
  1088. X            ct_litc_num++;
  1089. X            ch = ma->l.ma_litc[0];
  1090. X                ct_litc_freq[ch]++;
  1091. X
  1092. X    } else if (dist < 0) {           /* 2-character match */
  1093. X            ct_lit2_num++;
  1094. X            ch = ma->l.ma_litc[0];
  1095. X                ct_litc_freq[ch]++;
  1096. X            ch = ma->l.ma_litc[1];
  1097. X                ct_litc_freq[ch]++;
  1098. X            ch = ((-dist-1) >> fd.fd_nbits) & 0x3f;
  1099. X                ct_dst2_freq[ch]++;
  1100. X            ct_len2_freq[0]++;
  1101. X
  1102. X     } else {                        /* 3-char or longer match */
  1103. X            ct_strg_num++;
  1104. X            ch = ((dist-1) >> fd.fd_nbits) & 0x3f;
  1105. X                ct_dst3_freq[ch]++;
  1106. X         /* We defer the update of ct_dst2_freq and ct_len2_freq until
  1107. X          * ct_mktrees:
  1108. X          *     ct_dst2_freq[ch]++;
  1109. X          * ch = ma->l.ma_length - 2;
  1110. X          *     if (ch > 63) ch = 63;
  1111. X          *     ct_len2_freq[ch]++;
  1112. X          */
  1113. X            ch = ma->l.ma_length - 3;
  1114. X                if (ch > 63) ch = 63;
  1115. X                ct_len3_freq[ch]++;
  1116. X    }
  1117. X
  1118. X    /* That's all. */
  1119. X    return IM_OK;
  1120. X}
  1121. X
  1122. X
  1123. X/***********************************************************************
  1124. X *
  1125. X * Construct all code trees, and then determine how big the imploded
  1126. X * file will be under both "literal tree" and "no literal tree" con-
  1127. X * ditions.  Choose the best option.
  1128. X */
  1129. X
  1130. XImpErr
  1131. Xct_mktrees ()
  1132. X{   U_CHAR *c;
  1133. X    ImpErr retcode;
  1134. X    register long sum;
  1135. X    long len2, len3;
  1136. X    int n;
  1137. X
  1138. X    /* ct_tally did not update ct_dst2_freq and ct_len2_freq for matches of
  1139. X     * length > 2, so correct this now.
  1140. X     */
  1141. X    for (n = 62; n >= 0; n--) {
  1142. X        ct_dst2_freq[n] += ct_dst3_freq[n];
  1143. X        ct_len2_freq[n+1] += ct_len3_freq[n];
  1144. X    }
  1145. X    ct_dst2_freq[63] += ct_dst3_freq[63];
  1146. X    ct_len2_freq[63] += ct_len3_freq[63];
  1147. X
  1148. X    /*
  1149. X     * Construct the code trees and see how much space each will save.
  1150. X     *
  1151. X     * It is conceivable that a tree could result in a negative savings
  1152. X     * if its compressed form is sufficiently long.
  1153. X     *
  1154. X     * We need to construct the ZIP-file compressed representation of
  1155. X     * each tree in order to figure out how much space it will take.
  1156. X     * However, we don't save these tree representations now; rather,
  1157. X     * we'll wait until later and reconstruct the representations for
  1158. X     * whichever two (or three) trees we really need for the output.
  1159. X     */
  1160. X#ifdef IMPDEBUG
  1161. X    treename = (char *)NULL;
  1162. X#endif /* IMPDEBUG */
  1163. X
  1164. X    /* literal code tree */
  1165. X    retcode = ct_loadf    (ct_litc_tree,  ct_litc_freq);
  1166. X        if (retcode != IM_OK) return retcode;
  1167. X    retcode = ct_gencodes (ct_litc_tree, 1, 16, &ct_litc_saved);
  1168. X        if (retcode != IM_OK) return retcode;
  1169. X    retcode = ct_ziprep   (ct_litc_tree, &c);
  1170. X        if (retcode != IM_OK) return retcode;
  1171. X    ct_litc_saved -= (int) (c[0]+2) * 8;
  1172. X
  1173. X    /* length code tree (2) */
  1174. X    retcode = ct_loadf    (ct_len2_tree,  ct_len2_freq);
  1175. X        if (retcode != IM_OK) return retcode;
  1176. X    retcode = ct_gencodes (ct_len2_tree, 1, 16, &ct_len2_saved);
  1177. X        if (retcode != IM_OK) return retcode;
  1178. X    retcode = ct_ziprep   (ct_len2_tree, &c);
  1179. X        if (retcode != IM_OK) return retcode;
  1180. X    ct_len2_saved -= (int) (c[0]+2) * 8;
  1181. X
  1182. X    /* length code tree (3) */
  1183. X    retcode = ct_loadf    (ct_len3_tree,  ct_len3_freq);
  1184. X        if (retcode != IM_OK) return retcode;
  1185. X    retcode = ct_gencodes (ct_len3_tree, 1, 16, &ct_len3_saved);
  1186. X        if (retcode != IM_OK) return retcode;
  1187. X    retcode = ct_ziprep   (ct_len3_tree, &c);
  1188. X        if (retcode != IM_OK) return retcode;
  1189. X    ct_len3_saved -= (int) (c[0]+2) * 8;
  1190. X
  1191. X    /* distance code tree (2) */
  1192. X    retcode = ct_loadf    (ct_dst2_tree,  ct_dst2_freq);
  1193. X        if (retcode != IM_OK) return retcode;
  1194. X    retcode = ct_gencodes (ct_dst2_tree, 1,  8, &ct_dst2_saved);
  1195. X        if (retcode != IM_OK) return retcode;
  1196. X    retcode = ct_ziprep   (ct_dst2_tree, &c);
  1197. X        if (retcode != IM_OK) return retcode;
  1198. X    ct_dst2_saved -= (int) (c[0]+2) * 8;
  1199. X
  1200. X    /* distance code tree (3) */
  1201. X    retcode = ct_loadf    (ct_dst3_tree,  ct_dst3_freq);
  1202. X        if (retcode != IM_OK) return retcode;
  1203. X    retcode = ct_gencodes (ct_dst3_tree, 1,  8, &ct_dst3_saved);
  1204. X        if (retcode != IM_OK) return retcode;
  1205. X    retcode = ct_ziprep   (ct_dst3_tree, &c);
  1206. X        if (retcode != IM_OK) return retcode;
  1207. X    ct_dst3_saved -= (int) (c[0]+2) * 8;
  1208. X
  1209. X    /*
  1210. X     * Determine how big the compressed file will be
  1211. X     * with, and without, a literal character tree.
  1212. X     */
  1213. X
  1214. X    /* compressed length (no literal tree) */
  1215. X    sum  = ct_litc_num + ct_lit2_num + ct_strg_num;    /* initial bit */
  1216. X    sum += ct_litc_num * 8;                          /* literal bytes */
  1217. X    sum += (ct_lit2_num+ct_strg_num) * 6 - ct_len2_saved;  /* lengths */
  1218. X    sum += 8 * ct_len2_freq[63];                  /* oversize lengths */
  1219. X    sum += (ct_lit2_num+ct_strg_num) * (fd.fd_nbits+6)
  1220. X            - ct_dst2_saved;                             /* distances */
  1221. X    len2 = (sum+7) / 8;                           /* convert to bytes */
  1222. X
  1223. X    /* compressed length (with literal tree) */
  1224. X    sum  = ct_litc_num + 2*ct_lit2_num + ct_strg_num;  /* initial bit */
  1225. X    sum += (ct_litc_num+2*ct_lit2_num)*8 - ct_litc_saved;/* lit bytes */
  1226. X    sum += ct_strg_num * 6 - ct_len3_saved;                /* lengths */
  1227. X    sum += 8 * ct_len3_freq[63];                  /* oversize lengths */
  1228. X    sum += ct_strg_num * (fd.fd_nbits+6) - ct_dst3_saved;   /* dist's */
  1229. X    len3 = (sum+7) / 8;                           /* convert to bytes */
  1230. X
  1231. X    /*
  1232. X     * PKUNZIP 1.10 requires that the source value 255 in a "literal"
  1233. X     * tree must be represented by a bit string of length >= 10.  The
  1234. X     * literal tree was already adjusted to ensure that the value 255
  1235. X     * was given a bit string of length 10 or greater if possible.  If
  1236. X     * this did not succeed -- which would only happen if the longest
  1237. X     * bit string in the literal tree were of length 8 or 9 -- then the
  1238. X     * literal tree cannot be used.  In such a case, not much would be
  1239. X     * gained by using it anyway, so there's little reason to be upset.
  1240. X     */
  1241. X    if (ct_table[ct_litc_tree].ct_array[255].ct_len < 10)
  1242. X        len3 = len2;
  1243. X
  1244. X    /*
  1245. X     * Choose the method of compression which will use the least space
  1246. X     * for this particular file.  The possibilities are:  use a literal
  1247. X     * character tree; or, don't use a literal character tree.
  1248. X     */
  1249. X    if (len2 <= len3)
  1250. X    {   fd.fd_method = NO_LITERAL_TREE;
  1251. X        fd.fd_clen   = len2;
  1252. X        lit_tree     = -1;
  1253. X        len_tree     = ct_len2_tree;
  1254. X        dst_tree     = ct_dst2_tree;
  1255. X        retcode = ct_free (ct_litc_tree);
  1256. X            if (retcode != IM_OK) return retcode;
  1257. X        retcode = ct_free (ct_dst3_tree);
  1258. X            if (retcode != IM_OK) return retcode;
  1259. X        retcode = ct_free (ct_len3_tree);
  1260. X            if (retcode != IM_OK) return retcode;
  1261. X    }
  1262. X    else
  1263. X    {   fd.fd_method = LITERAL_TREE;
  1264. X        fd.fd_clen   = len3;
  1265. X        lit_tree     = ct_litc_tree;
  1266. X        len_tree     = ct_len3_tree;
  1267. X        dst_tree     = ct_dst3_tree;
  1268. X        retcode = ct_free (ct_dst2_tree);
  1269. X            if (retcode != IM_OK) return retcode;
  1270. X        retcode = ct_free (ct_len2_tree);
  1271. X            if (retcode != IM_OK) return retcode;
  1272. X    }
  1273. X
  1274. X    /* That's all. */
  1275. X    return IM_OK;
  1276. X}
  1277. X
  1278. X
  1279. X/***********************************************************************
  1280. X *
  1281. X * Output the code trees.
  1282. X */
  1283. X
  1284. XImpErr
  1285. Xct_wrtrees (outfp)
  1286. X    FILE *outfp;                        /* output file */
  1287. X{   ImpErr retcode;
  1288. X    U_CHAR *c;
  1289. X
  1290. X    /* Output the literal tree, if any. */
  1291. X#ifdef IMPDEBUG
  1292. X    treename = "Literal";
  1293. X#endif /* IMPDEBUG */
  1294. X    if (lit_tree >= 0)
  1295. X    {   retcode = ct_ziprep (lit_tree, &c);
  1296. X            if (retcode != IM_OK) return retcode;
  1297. X        if (zfwrite ((char *) c, (int) (c[0]+2), 1, outfp) != 1)
  1298. X            return IM_IOERR;
  1299. X    }
  1300. X
  1301. X    /* Output the length tree. */
  1302. X#ifdef IMPDEBUG
  1303. X    treename = "Length";
  1304. X#endif /* IMPDEBUG */
  1305. X    retcode = ct_ziprep (len_tree, &c);
  1306. X        if (retcode != IM_OK) return retcode;
  1307. X    if (zfwrite ((char *) c, (int) (c[0]+2), 1, outfp) != 1)
  1308. X        return IM_IOERR;
  1309. X
  1310. X    /* Output the distance tree. */
  1311. X#ifdef IMPDEBUG
  1312. X    treename = "Distance";
  1313. X#endif /* IMPDEBUG */
  1314. X    retcode = ct_ziprep (dst_tree, &c);
  1315. X        if (retcode != IM_OK) return retcode;
  1316. X    if (zfwrite ((char *) c, (int) (c[0]+2), 1, outfp) != 1)
  1317. X        return IM_IOERR;
  1318. X
  1319. X    return IM_OK;
  1320. X}
  1321. X
  1322. X/* Macros for outputting bit string. */
  1323. X
  1324. X#define OUTBITS(value,length) \
  1325. X        {   retcode = bi_rlout ((int) (value), (int) (length)); \
  1326. X                if (retcode != IM_OK) return retcode; \
  1327. X        }
  1328. X#define OUTCODE(value,tree) \
  1329. X        {   ct_lookup (tree, value, bitstring, bitlength); \
  1330. X            retcode = bi_rlout (bitstring, bitlength); \
  1331. X                if (retcode != IM_OK) return retcode; \
  1332. X        }
  1333. X
  1334. X/***********************************************************************
  1335. X *
  1336. X * Output the body of the file in imploded form.
  1337. X */
  1338. XImpErr
  1339. Xct_wrdata (outfp)
  1340. X         FILE *outfp;                   /* output (ZIP) file */
  1341. X{   MATCH *ma;
  1342. X    ImpErr retcode;
  1343. X    register int minmatch;
  1344. X    int bitstring, bitlength;
  1345. X    int bitmask = (1 << (fd.fd_nbits+1))-1;
  1346. X    /* Used to select the bottom 6 or 7 bits of a distance, which are
  1347. X     * output literally, plus 1 bit marking a distance
  1348. X     */
  1349. X    int matches;
  1350. X#ifdef  IMPDEBUG
  1351. X    long srcpos;
  1352. X#endif  /* IMPDEBUG */
  1353. X
  1354. X    /* Determine the minimum match length. */
  1355. X    minmatch = (lit_tree >= 0) ? 3 : 2;
  1356. X
  1357. X    /* Prepare the I/O. */
  1358. X    if (tflush (fd.fd_temp) != 0) return IM_IOERR;
  1359. X    trewind (fd.fd_temp);
  1360. X    retcode = bi_init (outfp);
  1361. X        if (retcode != IM_OK) return retcode;
  1362. X
  1363. X#ifdef  IMPDEBUG
  1364. X        srcpos = 0;
  1365. X        fprintf (stderr, "\nImploded output:\n");
  1366. X#endif  /* IMPDEBUG */
  1367. X
  1368. X    /* Read and process data from the temporary file. */
  1369. X    while ((matches =
  1370. X       tread ((char *) ma_buf, sizeof(MATCH), MA_BUFSIZE, fd.fd_temp)) > 0)
  1371. X       for (ma = ma_buf; matches > 0; ma++, matches--)
  1372. X    {
  1373. X        int dist = ma->ma_dist;
  1374. X        int len = 0;
  1375. X
  1376. X#ifdef  IMPDEBUG
  1377. X        fprintf (stderr, "%8ld: ", srcpos);
  1378. X#endif  /* IMPDEBUG */
  1379. X
  1380. X        if (dist < 0) {
  1381. X            dist = -dist, len = 2;
  1382. X        } else if (dist > 0) {
  1383. X            len = ma->l.ma_length;
  1384. X        }
  1385. X
  1386. X        /* Output distance and length if enough characters match. */
  1387. X        if (len >= minmatch)
  1388. X        {   /* "matched string" header bit (0) */
  1389. X#ifdef  IMPDEBUG
  1390. X            fprintf (stderr, "str (dst=%d,len=%d)  ",
  1391. X                     dist, len);
  1392. X            srcpos += len;
  1393. X#endif  /* IMPDEBUG */
  1394. X
  1395. X            /* ouput one zero bit then the distance */
  1396. X            dist--;
  1397. X            OUTBITS ((dist << 1) & bitmask, fd.fd_nbits + 1);
  1398. X            OUTCODE (dist >> fd.fd_nbits, dst_tree);
  1399. X
  1400. X            /* length -- depends on how it compares to maximum */
  1401. X            len -= minmatch;
  1402. X            if (len >= 63)
  1403. X            {   /* big length -- output code for 63, then surplus */
  1404. X                OUTCODE (63, len_tree);
  1405. X                OUTBITS ((len - 63), 8);
  1406. X            }
  1407. X            else
  1408. X            {   /* small length -- output code */
  1409. X                OUTCODE (len, len_tree);
  1410. X        }   }
  1411. X        else if (lit_tree >= 0)
  1412. X        {   /* first or single literal -- header bit (1) plus char */
  1413. X#ifdef  IMPDEBUG
  1414. X            fprintf (stderr, "lit (val=%02x)  ",
  1415. X                     ma->l.ma_litc[0] & 0xff);
  1416. X            srcpos++;
  1417. X#endif  /* IMPDEBUG */
  1418. X            OUTBITS (1, 1);
  1419. X            OUTCODE (ma->l.ma_litc[0], lit_tree);
  1420. X            if (len == 2)
  1421. X            {   /* second literal -- header bit (1) plus char */
  1422. X#ifdef  IMPDEBUG
  1423. X                fprintf (stderr, "\n%8ld: lit (val=%02x)  ",
  1424. X                         srcpos, ma->l.ma_litc[1] & 0xff);
  1425. X                srcpos++;
  1426. X#endif  /* IMPDEBUG */
  1427. X                OUTBITS (1, 1);
  1428. X                OUTCODE (ma->l.ma_litc[1], lit_tree);
  1429. X        }   }
  1430. X        else
  1431. X        {   /* single literal -- header bit (1) plus char */
  1432. X#ifdef  IMPDEBUG
  1433. X            fprintf (stderr, "lit (val=%02x)  ",
  1434. X                     ma->l.ma_litc[0] & 0xff);
  1435. X            srcpos++;
  1436. X#endif  /* IMPDEBUG */
  1437. X            OUTBITS ((ma->l.ma_litc[0] << 1) + 1, 9);
  1438. X        }
  1439. X#ifdef  IMPDEBUG
  1440. X        putc ('\n', stderr);
  1441. X#endif  /* IMPDEBUG */
  1442. X    }
  1443. X
  1444. X    /* Make sure we hit EOF on input without an error. */
  1445. X    if (terror (fd.fd_temp)
  1446. X#ifndef MINIX
  1447. X#ifndef __TURBOC__      /* TurboC 2.0 does not set the EOF flag (?) */
  1448. X        || !teof (fd.fd_temp)
  1449. X#endif /* !__TURBOC__ */
  1450. X#endif /* !MINIX */
  1451. X       )
  1452. X      return IM_IOERR;
  1453. X    retcode = bi_windup ();
  1454. X        if (retcode != IM_OK) return retcode;
  1455. X
  1456. X    /* That's all. */
  1457. X    return IM_OK;
  1458. X}
  1459. X
  1460. X#undef  OUTBITS
  1461. X#undef  OUTCODE
  1462. X
  1463. X
  1464. X/***********************************************************************
  1465. X *
  1466. X * Deallocate all code trees.
  1467. X */
  1468. X
  1469. XImpErr
  1470. Xct_windup ()
  1471. X{   int n;
  1472. X    static windup_already_called = 0;
  1473. X    ImpErr retcode;
  1474. X
  1475. X    if (windup_already_called)
  1476. X    {   /* Discard any old code trees. */
  1477. X        for (n = 0; n < MAXTREES; n++)
  1478. X        {   if (ct_table[n].ct_array != NULL)
  1479. X            {   retcode = ct_free (n);
  1480. X                if (retcode != IM_OK) return retcode;
  1481. X    }   }   }
  1482. X    else
  1483. X    {   /* Initialize the list of active code trees. */
  1484. X        for (n = 0; n < MAXTREES; n++)
  1485. X        {   ct_table[n].ct_array = NULL;
  1486. X            ct_table[n].ct_size  = 0;
  1487. X        }
  1488. X        windup_already_called = 1;
  1489. X    }
  1490. X
  1491. X    /* That's all. */
  1492. X    return IM_OK;
  1493. X}
  1494. X
  1495. X
  1496. X/**********************************************************************/
  1497. END_OF_FILE
  1498.   if test 45523 -ne `wc -c <'im_ctree.c'`; then
  1499.     echo shar: \"'im_ctree.c'\" unpacked with wrong size!
  1500.   fi
  1501.   # end of 'im_ctree.c'
  1502. fi
  1503. if test -f 'makevms.com' -a "${1}" != "-c" ; then 
  1504.   echo shar: Will not clobber existing file \"'makevms.com'\"
  1505. else
  1506.   echo shar: Extracting \"'makevms.com'\" \(2470 characters\)
  1507.   sed "s/^X//" >'makevms.com' <<'END_OF_FILE'
  1508. X$ !
  1509. X$ !     "Makefile" for VMS versions of Zip, ZipNote,
  1510. X$ !      ZipSplit, Ship and UnShip (stolen from Unzip)
  1511. X$ !
  1512. X$ set verify    ! like "echo on", eh?
  1513. X$ !
  1514. X$ !------------------------------- Zip section --------------------------------
  1515. X$ !
  1516. X$ cc /def=EXPORT zip,zipfile,zipup,fileio,util,tempf,shrink,globals,implode,im_lmat,im_ctree,im_bits
  1517. X$ link zip,zipfile,zipup,fileio,util,tempf,shrink,globals,implode,im_lmat,im_ctree,im_bits,sys$input:/opt
  1518. Xsys$share:vaxcrtl.exe/shareable
  1519. X$ !
  1520. X$ ! If you have problems with implode, compile with /define=noimplode
  1521. X$ ! and remove all the im* files from the above lines.
  1522. X$ !
  1523. X$ !-------------------------- Zip utilities section ---------------------------
  1524. X$ !
  1525. X$ ren zipfile.c zipfile_.c;*
  1526. X$ ren zipup.c zipup_.c;*
  1527. X$ ren fileio.c fileio_.c;*
  1528. X$ ren util.c util_.c;*
  1529. X$ cc /def=EXPORT zipnote, zipsplit
  1530. X$ cc /def=EXPORT /def=UTIL zipfile_, zipup_, fileio_, util_
  1531. X$ ren zipfile_.c zipfile.c;*
  1532. X$ ren zipup_.c zipup.c;*
  1533. X$ ren fileio_.c fileio.c;*
  1534. X$ ren util_.c util.c;*
  1535. X$ link zipnote, zipfile_, zipup_, fileio_, globals, sys$input:/opt
  1536. Xsys$share:vaxcrtl.exe/shareable
  1537. X$ link zipsplit, zipfile_, zipup_, fileio_, globals, sys$input:/opt
  1538. Xsys$share:vaxcrtl.exe/shareable
  1539. X$ !
  1540. X$ !--------------------------- Ship/UnShip section ----------------------------
  1541. X$ !
  1542. X$ cc ship
  1543. X$ link ship,sys$input:/opt
  1544. Xsys$share:vaxcrtl.exe/shareable
  1545. X$ !
  1546. X$ ! Create a hard link.  (To remove both files, delete the copy FIRST, then
  1547. X$ ! the original.  Otherwise, if original deleted first [copy says "no such
  1548. X$ ! file"], must use "set file/remove unship.exe;#" to get rid of the copy.
  1549. X$ ! Unlike in Unix, deleting the original ALWAYS destroys the data--but not
  1550. X$ ! the directory entry of the copy.)  Using a hard link saves disk space, by
  1551. X$ ! the way.  Note, however, that copying a hard link copies the data, not
  1552. X$ ! just the link.  Therefore, set up the link in the directory in which the
  1553. X$ ! executable is to reside, or else rename (move) the executables into the
  1554. X$ ! directory.
  1555. X$ !
  1556. X$ set file/enter=unship.exe ship.exe
  1557. X$ !
  1558. X$ !----------------------------- Symbols section ------------------------------
  1559. X$ !
  1560. X$ ! Set up symbols for the various executables.  Edit the example below,
  1561. X$ ! changing "pc" to "disk:[directory]" as appropriate, and uncomment
  1562. X$ ! (remove the exclamation marks).
  1563. X$ !
  1564. X$ ! zip        == "$pc:zip.exe"
  1565. X$ ! zipnote    == "$pc:zipnote.exe"
  1566. X$ ! zipsplit    == "$pc:zipsplit.exe"
  1567. X$ ! ship        == "$pc:ship.exe"
  1568. X$ ! unship    == "$pc:unship.exe"
  1569. X$ !
  1570. X$ set noverify
  1571. END_OF_FILE
  1572.   if test 2470 -ne `wc -c <'makevms.com'`; then
  1573.     echo shar: \"'makevms.com'\" unpacked with wrong size!
  1574.   fi
  1575.   # end of 'makevms.com'
  1576. fi
  1577. echo shar: End of archive 1 \(of 9\).
  1578. cp /dev/null ark1isdone
  1579. MISSING=""
  1580. for I in 1 2 3 4 5 6 7 8 9 ; do
  1581.     if test ! -f ark${I}isdone ; then
  1582.     MISSING="${MISSING} ${I}"
  1583.     fi
  1584. done
  1585. if test "${MISSING}" = "" ; then
  1586.     echo You have unpacked all 9 archives.
  1587.     rm -f ark[1-9]isdone ark[1-9][0-9]isdone
  1588. else
  1589.     echo You still must unpack the following archives:
  1590.     echo "        " ${MISSING}
  1591. fi
  1592. exit 0
  1593. exit 0 # Just in case...
  1594. -- 
  1595. Kent Landfield                   INTERNET: kent@sparky.IMD.Sterling.COM
  1596. Sterling Software, IMD           UUCP:     uunet!sparky!kent
  1597. Phone:    (402) 291-8300         FAX:      (402) 291-4362
  1598. Please send comp.sources.misc-related mail to kent@uunet.uu.net.
  1599.