home *** CD-ROM | disk | FTP | other *** search
/ The World of Computer Software / World_Of_Computer_Software-02-387-Vol-3of3.iso / d / djdev108.zip / SAMPLES / COMPRESS / COMPRESS.C < prev    next >
C/C++ Source or Header  |  1992-03-22  |  43KB  |  1,555 lines

  1. /*
  2.  * Copyright (c) 1985, 1986 The Regents of the University of California.
  3.  * All rights reserved.
  4.  *
  5.  * This code is derived from software contributed to Berkeley by
  6.  * James A. Woods, derived from original work by Spencer Thomas
  7.  * and Joseph Orost.
  8.  *
  9.  * Redistribution and use in source and binary forms are permitted
  10.  * provided that: (1) source distributions retain this entire copyright
  11.  * notice and comment, and (2) distributions including binaries display
  12.  * the following acknowledgement:  ``This product includes software
  13.  * developed by the University of California, Berkeley and its contributors''
  14.  * in the documentation or other materials provided with the distribution
  15.  * and in all advertising materials mentioning features or use of this
  16.  * software. Neither the name of the University nor the names of its
  17.  * contributors may be used to endorse or promote products derived
  18.  * from this software without specific prior written permission.
  19.  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
  20.  * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
  21.  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
  22.  */
  23.  
  24. #ifndef lint
  25. char copyright[] =
  26. "@(#) Copyright (c) 1985, 1986 The Regents of the University of California.\n\
  27.  All rights reserved.\n";
  28. #endif /* not lint */
  29.  
  30. #ifndef lint
  31. static char sccsid[] = "@(#)compress.c    5.12 (Berkeley) 6/1/90";
  32. #endif /* not lint */
  33.  
  34. /* 
  35.  * Compress - data compression program 
  36.  */
  37. #define    min(a,b)    ((a>b) ? b : a)
  38.  
  39. /*
  40.  * machine variants which require cc -Dmachine:  pdp11, z8000, pcxt
  41.  */
  42.  
  43. /*
  44.  * Set USERMEM to the maximum amount of physical user memory available
  45.  * in bytes.  USERMEM is used to determine the maximum BITS that can be used
  46.  * for compression.
  47.  *
  48.  * SACREDMEM is the amount of physical memory saved for others; compress
  49.  * will hog the rest.
  50.  */
  51. #ifndef SACREDMEM
  52. #define SACREDMEM    0
  53. #endif
  54.  
  55. #ifndef USERMEM
  56. # define USERMEM     450000    /* default user memory */
  57. #endif
  58.  
  59. #ifdef interdata        /* (Perkin-Elmer) */
  60. #define SIGNED_COMPARE_SLOW    /* signed compare is slower than unsigned */
  61. #endif
  62.  
  63. #ifdef pdp11
  64. # define BITS     12    /* max bits/code for 16-bit machine */
  65. # define NO_UCHAR    /* also if "unsigned char" functions as signed char */
  66. # undef USERMEM 
  67. #endif /* pdp11 */    /* don't forget to compile with -i */
  68.  
  69. #ifdef z8000
  70. # define BITS     12
  71. # undef vax        /* weird preprocessor */
  72. # undef USERMEM 
  73. #endif /* z8000 */
  74.  
  75. #ifdef pcxt
  76. # define BITS   12
  77. # undef USERMEM
  78. #endif /* pcxt */
  79.  
  80. #ifdef USERMEM
  81. # if USERMEM >= (433484+SACREDMEM)
  82. #  define PBITS    16
  83. # else
  84. #  if USERMEM >= (229600+SACREDMEM)
  85. #   define PBITS    15
  86. #  else
  87. #   if USERMEM >= (127536+SACREDMEM)
  88. #    define PBITS    14
  89. #   else
  90. #    if USERMEM >= (73464+SACREDMEM)
  91. #     define PBITS    13
  92. #    else
  93. #     define PBITS    12
  94. #    endif
  95. #   endif
  96. #  endif
  97. # endif
  98. # undef USERMEM
  99. #endif /* USERMEM */
  100.  
  101. #ifdef PBITS        /* Preferred BITS for this memory size */
  102. # ifndef BITS
  103. #  define BITS PBITS
  104. # endif BITS
  105. #endif /* PBITS */
  106.  
  107. #if BITS == 16
  108. # define HSIZE    69001        /* 95% occupancy */
  109. #endif
  110. #if BITS == 15
  111. # define HSIZE    35023        /* 94% occupancy */
  112. #endif
  113. #if BITS == 14
  114. # define HSIZE    18013        /* 91% occupancy */
  115. #endif
  116. #if BITS == 13
  117. # define HSIZE    9001        /* 91% occupancy */
  118. #endif
  119. #if BITS <= 12
  120. # define HSIZE    5003        /* 80% occupancy */
  121. #endif
  122.  
  123. #ifdef M_XENIX            /* Stupid compiler can't handle arrays with */
  124. # if BITS == 16            /* more than 65535 bytes - so we fake it */
  125. #  define XENIX_16
  126. # else
  127. #  if BITS > 13            /* Code only handles BITS = 12, 13, or 16 */
  128. #   define BITS    13
  129. #  endif
  130. # endif
  131. #endif
  132.  
  133. /*
  134.  * a code_int must be able to hold 2**BITS values of type int, and also -1
  135.  */
  136. #if BITS > 15
  137. typedef long int    code_int;
  138. #else
  139. typedef int        code_int;
  140. #endif
  141.  
  142. #ifdef SIGNED_COMPARE_SLOW
  143. typedef unsigned long int count_int;
  144. typedef unsigned short int count_short;
  145. #else
  146. typedef long int      count_int;
  147. #endif
  148.  
  149. #ifdef NO_UCHAR
  150.  typedef char    char_type;
  151. #else
  152.  typedef    unsigned char    char_type;
  153. #endif /* UCHAR */
  154. char_type magic_header[] = { "\037\235" };    /* 1F 9D */
  155.  
  156. /* Defines for third byte of header */
  157. #define BIT_MASK    0x1f
  158. #define BLOCK_MASK    0x80
  159. /* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
  160.    a fourth header byte (for expansion).
  161. */
  162. #define INIT_BITS 9            /* initial number of bits/code */
  163.  
  164. /*
  165.  * compress.c - File compression ala IEEE Computer, June 1984.
  166.  *
  167.  * Authors:    Spencer W. Thomas    (decvax!utah-cs!thomas)
  168.  *        Jim McKie        (decvax!mcvax!jim)
  169.  *        Steve Davies        (decvax!vax135!petsd!peora!srd)
  170.  *        Ken Turkowski        (decvax!decwrl!turtlevax!ken)
  171.  *        James A. Woods        (decvax!ihnp4!ames!jaw)
  172.  *        Joe Orost        (decvax!vax135!petsd!joe)
  173.  *
  174.  * $Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $
  175.  * $Log:    compress.c,v $
  176.  * Revision 4.0  85/07/30  12:50:00  joe
  177.  * Removed ferror() calls in output routine on every output except first.
  178.  * Prepared for release to the world.
  179.  * 
  180.  * Revision 3.6  85/07/04  01:22:21  joe
  181.  * Remove much wasted storage by overlaying hash table with the tables
  182.  * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
  183.  * computations.  Fixed dump_tab() DEBUG routine.
  184.  *
  185.  * Revision 3.5  85/06/30  20:47:21  jaw
  186.  * Change hash function to use exclusive-or.  Rip out hash cache.  These
  187.  * speedups render the megamemory version defunct, for now.  Make decoder
  188.  * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
  189.  *
  190.  * Revision 3.4  85/06/27  12:00:00  ken
  191.  * Get rid of all floating-point calculations by doing all compression ratio
  192.  * calculations in fixed point.
  193.  *
  194.  * Revision 3.3  85/06/24  21:53:24  joe
  195.  * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
  196.  * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
  197.  *
  198.  * Revision 3.2  85/06/06  21:53:24  jaw
  199.  * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
  200.  * Default to "quiet" output (no compression statistics).
  201.  *
  202.  * Revision 3.1  85/05/12  18:56:13  jaw
  203.  * Integrate decompress() stack speedups (from early pointer mods by McKie).
  204.  * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
  205.  * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase 
  206.  * output byte count by magic number size.
  207.  * 
  208.  * Revision 3.0   84/11/27  11:50:00  petsd!joe
  209.  * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
  210.  * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
  211.  * unsigned compares on Perkin-Elmer.  Fixed foreground check.
  212.  *
  213.  * Revision 2.7   84/11/16  19:35:39  ames!jaw
  214.  * Cache common hash codes based on input statistics; this improves
  215.  * performance for low-density raster images.  Pass on #ifdef bundle
  216.  * from Turkowski.
  217.  *
  218.  * Revision 2.6   84/11/05  19:18:21  ames!jaw
  219.  * Vary size of hash tables to reduce time for small files.
  220.  * Tune PDP-11 hash function.
  221.  *
  222.  * Revision 2.5   84/10/30  20:15:14  ames!jaw
  223.  * Junk chaining; replace with the simpler (and, on the VAX, faster)
  224.  * double hashing, discussed within.  Make block compression standard.
  225.  *
  226.  * Revision 2.4   84/10/16  11:11:11  ames!jaw
  227.  * Introduce adaptive reset for block compression, to boost the rate
  228.  * another several percent.  (See mailing list notes.)
  229.  *
  230.  * Revision 2.3   84/09/22  22:00:00  petsd!joe
  231.  * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
  232.  * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
  233.  *
  234.  * Revision 2.2   84/09/18  14:12:21  ames!jaw
  235.  * Fold in news changes, small machine typedef from thomas,
  236.  * #ifdef interdata from joe.
  237.  *
  238.  * Revision 2.1   84/09/10  12:34:56  ames!jaw
  239.  * Configured fast table lookup for 32-bit machines.
  240.  * This cuts user time in half for b <= FBITS, and is useful for news batching
  241.  * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
  242.  * added signal catcher [plus beef in writeerr()] to delete effluvia.
  243.  *
  244.  * Revision 2.0   84/08/28  22:00:00  petsd!joe
  245.  * Add check for foreground before prompting user.  Insert maxbits into
  246.  * compressed file.  Force file being uncompressed to end with ".Z".
  247.  * Added "-c" flag and "zcat".  Prepared for release.
  248.  *
  249.  * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
  250.  * Will only compress regular files (no directories), added a magic number
  251.  * header (plus an undocumented -n flag to handle old files without headers),
  252.  * added -f flag to force overwriting of possibly existing destination file,
  253.  * otherwise the user is prompted for a response.  Will tack on a .Z to a
  254.  * filename if it doesn't have one when decompressing.  Will only replace
  255.  * file if it was compressed.
  256.  *
  257.  * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
  258.  * Removed scanargs(), getopt(), added .Z extension and unlimited number of
  259.  * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
  260.  * (-D -d -v -b 12), or combination thereof.  Modes and other status is
  261.  * copied with copystat().  -O bug for 4.2 seems to have disappeared with
  262.  * 1.8.
  263.  *
  264.  * Revision 1.8  84/08/09  23:15:00  joe
  265.  * Made it compatible with vax version, installed jim's fixes/enhancements
  266.  *
  267.  * Revision 1.6  84/08/01  22:08:00  joe
  268.  * Sped up algorithm significantly by sorting the compress chain.
  269.  *
  270.  * Revision 1.5  84/07/13  13:11:00  srd
  271.  * Added C version of vax asm routines.  Changed structure to arrays to
  272.  * save much memory.  Do unsigned compares where possible (faster on
  273.  * Perkin-Elmer)
  274.  *
  275.  * Revision 1.4  84/07/05  03:11:11  thomas
  276.  * Clean up the code a little and lint it.  (Lint complains about all
  277.  * the regs used in the asm, but I'm not going to "fix" this.)
  278.  *
  279.  * Revision 1.3  84/07/05  02:06:54  thomas
  280.  * Minor fixes.
  281.  *
  282.  * Revision 1.2  84/07/05  00:27:27  thomas
  283.  * Add variable bit length output.
  284.  *
  285.  */
  286. static char rcs_ident[] = "$Header: compress.c,v 4.0 85/07/30 12:50:00 joe Release $";
  287.  
  288. #include <stdio.h>
  289. #include <ctype.h>
  290. #include <signal.h>
  291. #include <fcntl.h>
  292. #include <sys/types.h>
  293. #include <sys/stat.h>
  294. #ifdef notdef
  295. #include <sys/ioctl.h>
  296. #endif
  297.  
  298. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  299.  
  300. int n_bits;                /* number of bits/code */
  301. int maxbits = BITS;            /* user settable max # bits/code */
  302. code_int maxcode;            /* maximum code, given n_bits */
  303. code_int maxmaxcode = 1 << BITS;    /* should NEVER generate this code */
  304. #ifdef COMPATIBLE        /* But wrong! */
  305. # define MAXCODE(n_bits)    (1 << (n_bits) - 1)
  306. #else
  307. # define MAXCODE(n_bits)    ((1 << (n_bits)) - 1)
  308. #endif /* COMPATIBLE */
  309.  
  310. #ifdef XENIX_16
  311. count_int htab0[8192];
  312. count_int htab1[8192];
  313. count_int htab2[8192];
  314. count_int htab3[8192];
  315. count_int htab4[8192];
  316. count_int htab5[8192];
  317. count_int htab6[8192];
  318. count_int htab7[8192];
  319. count_int htab8[HSIZE-65536];
  320. count_int * htab[9] = {
  321.     htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
  322.  
  323. #define htabof(i)    (htab[(i) >> 13][(i) & 0x1fff])
  324. unsigned short code0tab[16384];
  325. unsigned short code1tab[16384];
  326. unsigned short code2tab[16384];
  327. unsigned short code3tab[16384];
  328. unsigned short code4tab[16384];
  329. unsigned short * codetab[5] = {
  330.     code0tab, code1tab, code2tab, code3tab, code4tab };
  331.  
  332. #define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
  333.  
  334. #else    /* Normal machine */
  335.  
  336. #ifdef sel    /* gould base register braindamage */
  337. /*NOBASE*/
  338. count_int htab [HSIZE];
  339. unsigned short codetab [HSIZE];
  340. /*NOBASE*/
  341. #else
  342. count_int htab [HSIZE];
  343. unsigned short codetab [HSIZE];
  344. #endif sel
  345.  
  346. #define htabof(i)    htab[i]
  347. #define codetabof(i)    codetab[i]
  348. #endif    /* XENIX_16 */
  349. code_int hsize = HSIZE;            /* for dynamic table sizing */
  350. count_int fsize;
  351.  
  352. /*
  353.  * To save much memory, we overlay the table used by compress() with those
  354.  * used by decompress().  The tab_prefix table is the same size and type
  355.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  356.  * get this from the beginning of htab.  The output stack uses the rest
  357.  * of htab, and contains characters.  There is plenty of room for any
  358.  * possible stack (stack used to be 8000 characters).
  359.  */
  360.  
  361. #define tab_prefixof(i)    codetabof(i)
  362. #ifdef XENIX_16
  363. # define tab_suffixof(i)    ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
  364. # define de_stack        ((char_type *)(htab2))
  365. #else    /* Normal machine */
  366. # define tab_suffixof(i)    ((char_type *)(htab))[i]
  367. # define de_stack        ((char_type *)&tab_suffixof(1<<BITS))
  368. #endif    /* XENIX_16 */
  369.  
  370. code_int free_ent = 0;            /* first unused entry */
  371. int exit_stat = 0;            /* per-file status */
  372. int perm_stat = 0;            /* permanent status */
  373.  
  374. code_int getcode();
  375.  
  376. Usage() {
  377. #ifdef DEBUG
  378. fprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  379. }
  380. int debug = 0;
  381. #else
  382. fprintf(stderr,"Usage: compress [-fvc] [-b maxbits] [file ...]\n");
  383. }
  384. #endif /* DEBUG */
  385. int nomagic = 0;    /* Use a 3-byte magic number header, unless old file */
  386. int zcat_flg = 0;    /* Write output on stdout, suppress messages */
  387. int precious = 1;    /* Don't unlink output file on interrupt */
  388. int quiet = 1;        /* don't tell me about compression */
  389.  
  390. /*
  391.  * block compression parameters -- after all codes are used up,
  392.  * and compression rate changes, start over.
  393.  */
  394. int block_compress = BLOCK_MASK;
  395. int clear_flg = 0;
  396. long int ratio = 0;
  397. #define CHECK_GAP 10000    /* ratio check interval */
  398. count_int checkpoint = CHECK_GAP;
  399. /*
  400.  * the next two codes should not be changed lightly, as they must not
  401.  * lie within the contiguous general code space.
  402.  */ 
  403. #define FIRST    257    /* first free entry */
  404. #define    CLEAR    256    /* table clear output code */
  405.  
  406. int force = 0;
  407. char ofname [100];
  408. #ifdef DEBUG
  409. int verbose = 0;
  410. #endif /* DEBUG */
  411. #if 0
  412. sig_t oldint;
  413. #endif
  414. int bgnd_flag=0;
  415.  
  416. int do_decomp = 0;
  417.  
  418. /*****************************************************************
  419.  * TAG( main )
  420.  *
  421.  * Algorithm from "A Technique for High Performance Data Compression",
  422.  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  423.  *
  424.  * Usage: compress [-dfvc] [-b bits] [file ...]
  425.  * Inputs:
  426.  *    -d:        If given, decompression is done instead.
  427.  *
  428.  *      -c:         Write output on stdout, don't remove original.
  429.  *
  430.  *      -b:         Parameter limits the max number of bits/code.
  431.  *
  432.  *    -f:        Forces output file to be generated, even if one already
  433.  *            exists, and even if no space is saved by compressing.
  434.  *            If -f is not used, the user will be prompted if stdin is
  435.  *            a tty, otherwise, the output file will not be overwritten.
  436.  *
  437.  *      -v:        Write compression statistics
  438.  *
  439.  *     file ...:   Files to be compressed.  If none specified, stdin
  440.  *            is used.
  441.  * Outputs:
  442.  *    file.Z:        Compressed form of file with same mode, owner, and utimes
  443.  *     or stdout   (if stdin used as input)
  444.  *
  445.  * Assumptions:
  446.  *    When filenames are given, replaces with the compressed version
  447.  *    (.Z suffix) only if the file decreases in size.
  448.  * Algorithm:
  449.  *     Modified Lempel-Ziv method (LZW).  Basically finds common
  450.  * substrings and replaces them with a variable size code.  This is
  451.  * deterministic, and can be done on the fly.  Thus, the decompression
  452.  * procedure needs no input table, but tracks the way the table was built.
  453.  */
  454.  
  455. main( argc, argv )
  456. register int argc; char **argv;
  457. {
  458.     int overwrite = 0;    /* Do not overwrite unless given -f flag */
  459.     char tempname[100];
  460.     char **filelist, **fileptr;
  461.     char *cp, *rindex(), *malloc();
  462.     struct stat statbuf;
  463.     void onintr(), oops();
  464.  
  465.     setmode(0,O_BINARY);
  466.     setmode(1,O_BINARY);
  467.  
  468.     /* This bg check only works for sh. */
  469. #if 0
  470.     if ( (oldint = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  471.     signal ( SIGINT, onintr );
  472.     signal ( SIGSEGV, oops );
  473.     }
  474.     bgnd_flag = oldint != SIG_DFL;
  475. #endif
  476. #ifdef notdef     /* This works for csh but we don't want it. */
  477.     { int tgrp;
  478.     if (bgnd_flag == 0 && ioctl(2, TIOCGPGRP, (char *)&tgrp) == 0 &&
  479.       getpgrp(0) != tgrp)
  480.     bgnd_flag = 1;
  481.     }
  482. #endif
  483.     
  484. #ifdef COMPATIBLE
  485.     nomagic = 1;    /* Original didn't have a magic number */
  486. #endif /* COMPATIBLE */
  487.  
  488.     filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  489.     *filelist = NULL;
  490.  
  491.     if((cp = rindex(argv[0], '/')) != 0) {
  492.     cp++;
  493.     } else {
  494.     cp = argv[0];
  495.     }
  496.     if(strcmp(cp, "uncompress") == 0) {
  497.     do_decomp = 1;
  498.     } else if(strcmp(cp, "zcat") == 0) {
  499.     do_decomp = 1;
  500.     zcat_flg = 1;
  501.     }
  502.  
  503. #ifdef BSD4_2
  504.     /* 4.2BSD dependent - take it out if not */
  505.     setlinebuf( stderr );
  506. #endif /* BSD4_2 */
  507.  
  508.     /* Argument Processing
  509.      * All flags are optional.
  510.      * -D => debug
  511.      * -V => print Version; debug verbose
  512.      * -d => do_decomp
  513.      * -v => unquiet
  514.      * -f => force overwrite of output file
  515.      * -n => no header: useful to uncompress old files
  516.      * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  517.      *        given also.
  518.      * -c => cat all output to stdout
  519.      * -C => generate output compatible with compress 2.0.
  520.      * if a string is left, must be an input filename.
  521.      */
  522.     for (argc--, argv++; argc > 0; argc--, argv++) {
  523.     if (**argv == '-') {    /* A flag argument */
  524.         while (*++(*argv)) {    /* Process all flags in this arg */
  525.         switch (**argv) {
  526. #ifdef DEBUG
  527.             case 'D':
  528.             debug = 1;
  529.             break;
  530.             case 'V':
  531.             verbose = 1;
  532.             version();
  533.             break;
  534. #else
  535.             case 'V':
  536.             version();
  537.             break;
  538. #endif /* DEBUG */
  539.             case 'v':
  540.             quiet = 0;
  541.             break;
  542.             case 'd':
  543.             do_decomp = 1;
  544.             break;
  545.             case 'f':
  546.             case 'F':
  547.             overwrite = 1;
  548.             force = 1;
  549.             break;
  550.             case 'n':
  551.             nomagic = 1;
  552.             break;
  553.             case 'C':
  554.             block_compress = 0;
  555.             break;
  556.             case 'b':
  557.             if (!ARGVAL()) {
  558.                 fprintf(stderr, "Missing maxbits\n");
  559.                 Usage();
  560.                 exit(1);
  561.             }
  562.             maxbits = atoi(*argv);
  563.             goto nextarg;
  564.             case 'c':
  565.             zcat_flg = 1;
  566.             break;
  567.             case 'q':
  568.             quiet = 1;
  569.             break;
  570.             default:
  571.             fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  572.             Usage();
  573.             exit(1);
  574.         }
  575.         }
  576.     }
  577.     else {        /* Input file name */
  578.         *fileptr++ = *argv;    /* Build input file list */
  579.         *fileptr = NULL;
  580.         /* process nextarg; */
  581.     }
  582.     nextarg: continue;
  583.     }
  584.  
  585.     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  586.     if (maxbits > BITS) maxbits = BITS;
  587.     maxmaxcode = 1 << maxbits;
  588.  
  589.     if (*filelist != NULL) {
  590.     for (fileptr = filelist; *fileptr; fileptr++) {
  591.         exit_stat = 0;
  592.         if (do_decomp) {            /* DECOMPRESSION */
  593.         /* Check for .Z suffix */
  594.         if (strcmp(*fileptr + strlen(*fileptr) - 1, "Z") != 0) {
  595.             /* No .Z: tack one on */
  596.             strcpy(tempname, *fileptr);
  597.             strcat(tempname, "Z");
  598.             *fileptr = tempname;
  599.         }
  600.         /* Open input file */
  601.         if ((freopen(*fileptr, "rb", stdin)) == NULL) {
  602.             perror(*fileptr);
  603.             perm_stat = 1;
  604.             continue;
  605.         }
  606.         /* Check the magic number */
  607.         if (nomagic == 0) {
  608.             if ((getchar() != (magic_header[0] & 0xFF))
  609.              || (getchar() != (magic_header[1] & 0xFF))) {
  610.             fprintf(stderr, "%s: not in compressed format\n",
  611.                 *fileptr);
  612.             continue;
  613.             }
  614.             maxbits = getchar();    /* set -b from file */
  615.             block_compress = maxbits & BLOCK_MASK;
  616.             maxbits &= BIT_MASK;
  617.             maxmaxcode = 1 << maxbits;
  618.             if(maxbits > BITS) {
  619.             fprintf(stderr,
  620.             "%s: compressed with %d bits, can only handle %d bits\n",
  621.             *fileptr, maxbits, BITS);
  622.             continue;
  623.             }
  624.         }
  625.         /* Generate output filename */
  626.         strcpy(ofname, *fileptr);
  627.         ofname[strlen(*fileptr) - 1] = '\0';  /* Strip off .Z */
  628.         } else {                    /* COMPRESSION */
  629.         if (strcmp(*fileptr + strlen(*fileptr) - 1, "Z") == 0) {
  630.                 fprintf(stderr, "%s: already has Z suffix -- no change\n",
  631.                 *fileptr);
  632.             continue;
  633.         }
  634.         /* Open input file */
  635.         if ((freopen(*fileptr, "rb", stdin)) == NULL) {
  636.             perror(*fileptr);
  637.             perm_stat = 1;
  638.             continue;
  639.         }
  640.         stat ( *fileptr, &statbuf );
  641.         fsize = (long) statbuf.st_size;
  642.         /*
  643.          * tune hash table size for small files -- ad hoc,
  644.          * but the sizes match earlier #defines, which
  645.          * serve as upper bounds on the number of output codes. 
  646.          */
  647.         hsize = HSIZE;
  648.         if ( fsize < (1 << 12) )
  649.             hsize = min ( 5003, HSIZE );
  650.         else if ( fsize < (1 << 13) )
  651.             hsize = min ( 9001, HSIZE );
  652.         else if ( fsize < (1 << 14) )
  653.             hsize = min ( 18013, HSIZE );
  654.         else if ( fsize < (1 << 15) )
  655.             hsize = min ( 35023, HSIZE );
  656.         else if ( fsize < 47000 )
  657.             hsize = min ( 50021, HSIZE );
  658.  
  659.         /* Generate output filename */
  660.         strcpy(ofname, *fileptr);
  661. #ifndef BSD4_2        /* Short filenames */
  662.         if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  663.         else                    cp = ofname;
  664.         if (strlen(cp) > 12) {
  665.             fprintf(stderr,"%s: filename too long to tack on Z\n",cp);
  666.             continue;
  667.         }
  668. #endif  /* BSD4_2        Long filenames allowed */
  669.         strcat(ofname, "Z");
  670.         }
  671.         /* Check for overwrite of existing file */
  672.         if (overwrite == 0 && zcat_flg == 0) {
  673.         if (stat(ofname, &statbuf) == 0) {
  674.             char response[2];
  675.             response[0] = 'n';
  676.             fprintf(stderr, "%s already exists;", ofname);
  677.             if (bgnd_flag == 0 && isatty(2)) {
  678.             fprintf(stderr, " do you wish to overwrite %s (y or n)? ",
  679.             ofname);
  680.             fflush(stderr);
  681.             read(2, response, 2);
  682.             while (response[1] != '\n') {
  683.                 if (read(2, response+1, 1) < 0) {    /* Ack! */
  684.                 perror("stderr"); break;
  685.                 }
  686.             }
  687.             }
  688.             if (response[0] != 'y') {
  689.             fprintf(stderr, "\tnot overwritten\n");
  690.             continue;
  691.             }
  692.         }
  693.         }
  694.         if(zcat_flg == 0) {        /* Open output file */
  695.         if (freopen(ofname, "wb", stdout) == NULL) {
  696.             perror(ofname);
  697.             perm_stat = 1;
  698.             continue;
  699.         }
  700.         precious = 0;
  701.         if(!quiet)
  702.             fprintf(stderr, "%s: ", *fileptr);
  703.         }
  704.  
  705.         /* Actually do the compression/decompression */
  706.         if (do_decomp == 0)    compress();
  707. #ifndef DEBUG
  708.         else            decompress();
  709. #else
  710.         else if (debug == 0)    decompress();
  711.         else            printcodes();
  712.         if (verbose)        dump_tab();
  713. #endif /* DEBUG */
  714.         if(zcat_flg == 0) {
  715.         copystat(*fileptr, ofname);    /* Copy stats */
  716.         precious = 1;
  717.         if((exit_stat == 1) || (!quiet))
  718.             putc('\n', stderr);
  719.         }
  720.     }
  721.     } else {        /* Standard input */
  722.     if (do_decomp == 0) {
  723.         compress();
  724. #ifdef DEBUG
  725.         if(verbose)        dump_tab();
  726. #endif /* DEBUG */
  727.         if(!quiet)
  728.             putc('\n', stderr);
  729.     } else {
  730.         /* Check the magic number */
  731.         if (nomagic == 0) {
  732.         if ((getchar()!=(magic_header[0] & 0xFF))
  733.          || (getchar()!=(magic_header[1] & 0xFF))) {
  734.             fprintf(stderr, "stdin: not in compressed format\n");
  735.             exit(1);
  736.         }
  737.         maxbits = getchar();    /* set -b from file */
  738.         block_compress = maxbits & BLOCK_MASK;
  739.         maxbits &= BIT_MASK;
  740.         maxmaxcode = 1 << maxbits;
  741.         fsize = 100000;        /* assume stdin large for USERMEM */
  742.         if(maxbits > BITS) {
  743.             fprintf(stderr,
  744.             "stdin: compressed with %d bits, can only handle %d bits\n",
  745.             maxbits, BITS);
  746.             exit(1);
  747.         }
  748.         }
  749. #ifndef DEBUG
  750.         decompress();
  751. #else
  752.         if (debug == 0)    decompress();
  753.         else        printcodes();
  754.         if (verbose)    dump_tab();
  755. #endif /* DEBUG */
  756.     }
  757.     }
  758.     exit(perm_stat ? perm_stat : exit_stat);
  759. }
  760.  
  761. static int offset;
  762. long int in_count = 1;            /* length of input */
  763. long int bytes_out;            /* length of compressed output */
  764. long int out_count = 0;            /* # of codes output (for debugging) */
  765.  
  766. /*
  767.  * compress stdin to stdout
  768.  *
  769.  * Algorithm:  use open addressing double hashing (no chaining) on the 
  770.  * prefix code / next character combination.  We do a variant of Knuth's
  771.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  772.  * secondary probe.  Here, the modular division first probe is gives way
  773.  * to a faster exclusive-or manipulation.  Also do block compression with
  774.  * an adaptive reset, whereby the code table is cleared when the compression
  775.  * ratio decreases, but after the table fills.  The variable-length output
  776.  * codes are re-sized at this point, and a special CLEAR code is generated
  777.  * for the decompressor.  Late addition:  construct the table according to
  778.  * file size for noticeable speed improvement on small files.  Please direct
  779.  * questions about this implementation to ames!jaw.
  780.  */
  781.  
  782. compress() {
  783.     register long fcode;
  784.     register code_int i = 0;
  785.     register int c;
  786.     register code_int ent;
  787. #ifdef XENIX_16
  788.     register code_int disp;
  789. #else    /* Normal machine */
  790.     register int disp;
  791. #endif
  792.     register code_int hsize_reg;
  793.     register int hshift;
  794.  
  795. #ifndef COMPATIBLE
  796.     if (nomagic == 0) {
  797.     putchar(magic_header[0]); putchar(magic_header[1]);
  798.     putchar((char)(maxbits | block_compress));
  799.     if(ferror(stdout))
  800.         writeerr();
  801.     }
  802. #endif /* COMPATIBLE */
  803.  
  804.     offset = 0;
  805.     bytes_out = 3;        /* includes 3-byte header mojo */
  806.     out_count = 0;
  807.     clear_flg = 0;
  808.     ratio = 0;
  809.     in_count = 1;
  810.     checkpoint = CHECK_GAP;
  811.     maxcode = MAXCODE(n_bits = INIT_BITS);
  812.     free_ent = ((block_compress) ? FIRST : 256 );
  813.  
  814.     ent = getchar ();
  815.  
  816.     hshift = 0;
  817.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  818.         hshift++;
  819.     hshift = 8 - hshift;        /* set hash code range bound */
  820.  
  821.     hsize_reg = hsize;
  822.     cl_hash( (count_int) hsize_reg);        /* clear hash table */
  823.  
  824. #ifdef SIGNED_COMPARE_SLOW
  825.     while ( (c = getchar()) != (unsigned) EOF ) {
  826. #else
  827.     while ( (c = getchar()) != EOF ) {
  828. #endif
  829.     in_count++;
  830.     fcode = (long) (((long) c << maxbits) + ent);
  831.      i = ((c << hshift) ^ ent);    /* xor hashing */
  832.  
  833.     if ( htabof (i) == fcode ) {
  834.         ent = codetabof (i);
  835.         continue;
  836.     } else if ( (long)htabof (i) < 0 )    /* empty slot */
  837.         goto nomatch;
  838.      disp = hsize_reg - i;        /* secondary hash (after G. Knott) */
  839.     if ( i == 0 )
  840.         disp = 1;
  841. probe:
  842.     if ( (i -= disp) < 0 )
  843.         i += hsize_reg;
  844.  
  845.     if ( htabof (i) == fcode ) {
  846.         ent = codetabof (i);
  847.         continue;
  848.     }
  849.     if ( (long)htabof (i) > 0 ) 
  850.         goto probe;
  851. nomatch:
  852.     output ( (code_int) ent );
  853.     out_count++;
  854.      ent = c;
  855. #ifdef SIGNED_COMPARE_SLOW
  856.     if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  857. #else
  858.     if ( free_ent < maxmaxcode ) {
  859. #endif
  860.          codetabof (i) = free_ent++;    /* code -> hashtable */
  861.         htabof (i) = fcode;
  862.     }
  863.     else if ( (count_int)in_count >= checkpoint && block_compress )
  864.         cl_block ();
  865.     }
  866.     /*
  867.      * Put out the final code.
  868.      */
  869.     output( (code_int)ent );
  870.     out_count++;
  871.     output( (code_int)-1 );
  872.  
  873.     /*
  874.      * Print out stats on stderr
  875.      */
  876.     if(zcat_flg == 0 && !quiet) {
  877. #ifdef DEBUG
  878.     fprintf( stderr,
  879.         "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  880.         in_count, out_count, bytes_out );
  881.     prratio( stderr, in_count, bytes_out );
  882.     fprintf( stderr, "\n");
  883.     fprintf( stderr, "\tCompression as in compact: " );
  884.     prratio( stderr, in_count-bytes_out, in_count );
  885.     fprintf( stderr, "\n");
  886.     fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  887.         free_ent - 1, n_bits );
  888. #else /* !DEBUG */
  889.     fprintf( stderr, "Compression: " );
  890.     prratio( stderr, in_count-bytes_out, in_count );
  891. #endif /* DEBUG */
  892.     }
  893.     if(bytes_out > in_count)    /* exit(2) if no savings */
  894.     exit_stat = 2;
  895.     return;
  896. }
  897.  
  898. /*****************************************************************
  899.  * TAG( output )
  900.  *
  901.  * Output the given code.
  902.  * Inputs:
  903.  *     code:    A n_bits-bit integer.  If == -1, then EOF.  This assumes
  904.  *        that n_bits =< (long)wordsize - 1.
  905.  * Outputs:
  906.  *     Outputs code to the file.
  907.  * Assumptions:
  908.  *    Chars are 8 bits long.
  909.  * Algorithm:
  910.  *     Maintain a BITS character long buffer (so that 8 codes will
  911.  * fit in it exactly).  Use the VAX insv instruction to insert each
  912.  * code in turn.  When the buffer fills up empty it and start over.
  913.  */
  914.  
  915. static char buf[BITS];
  916.  
  917. #ifndef vax
  918. char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  919. char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  920. #endif /* vax */
  921.  
  922. output( code )
  923. code_int  code;
  924. {
  925. #ifdef DEBUG
  926.     static int col = 0;
  927. #endif /* DEBUG */
  928.  
  929.     /*
  930.      * On the VAX, it is important to have the register declarations
  931.      * in exactly the order given, or the asm will break.
  932.      */
  933.     register int r_off = offset, bits= n_bits;
  934.     register char * bp = buf;
  935.  
  936. #ifdef DEBUG
  937.     if ( verbose )
  938.         fprintf( stderr, "%5d%c", code,
  939.             (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  940. #endif /* DEBUG */
  941.     if ( code >= 0 ) {
  942. #ifdef vax
  943.     /* VAX DEPENDENT!! Implementation on other machines is below.
  944.      *
  945.      * Translation: Insert BITS bits from the argument starting at
  946.      * offset bits from the beginning of buf.
  947.      */
  948.     0;    /* Work around for pcc -O bug with asm and if stmt */
  949.     asm( "insv    4(ap),r11,r10,(r9)" );
  950. #else /* not a vax */
  951. /* 
  952.  * byte/bit numbering on the VAX is simulated by the following code
  953.  */
  954.     /*
  955.      * Get to the first byte.
  956.      */
  957.     bp += (r_off >> 3);
  958.     r_off &= 7;
  959.     /*
  960.      * Since code is always >= 8 bits, only need to mask the first
  961.      * hunk on the left.
  962.      */
  963.     *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  964.     bp++;
  965.     bits -= (8 - r_off);
  966.     code >>= 8 - r_off;
  967.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  968.     if ( bits >= 8 ) {
  969.         *bp++ = code;
  970.         code >>= 8;
  971.         bits -= 8;
  972.     }
  973.     /* Last bits. */
  974.     if(bits)
  975.         *bp = code;
  976. #endif /* vax */
  977.     offset += n_bits;
  978.     if ( offset == (n_bits << 3) ) {
  979.         bp = buf;
  980.         bits = n_bits;
  981.         bytes_out += bits;
  982.         do
  983.         putchar(*bp++);
  984.         while(--bits);
  985.         offset = 0;
  986.     }
  987.  
  988.     /*
  989.      * If the next entry is going to be too big for the code size,
  990.      * then increase it, if possible.
  991.      */
  992.     if ( free_ent > maxcode || (clear_flg > 0))
  993.     {
  994.         /*
  995.          * Write the whole buffer, because the input side won't
  996.          * discover the size increase until after it has read it.
  997.          */
  998.         if ( offset > 0 ) {
  999.         if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  1000.             writeerr();
  1001.         bytes_out += n_bits;
  1002.         }
  1003.         offset = 0;
  1004.  
  1005.         if ( clear_flg ) {
  1006.                 maxcode = MAXCODE (n_bits = INIT_BITS);
  1007.             clear_flg = 0;
  1008.         }
  1009.         else {
  1010.             n_bits++;
  1011.             if ( n_bits == maxbits )
  1012.             maxcode = maxmaxcode;
  1013.             else
  1014.             maxcode = MAXCODE(n_bits);
  1015.         }
  1016. #ifdef DEBUG
  1017.         if ( debug ) {
  1018.         fprintf( stderr, "\nChange to %d bits\n", n_bits );
  1019.         col = 0;
  1020.         }
  1021. #endif /* DEBUG */
  1022.     }
  1023.     } else {
  1024.     /*
  1025.      * At EOF, write the rest of the buffer.
  1026.      */
  1027.     if ( offset > 0 )
  1028.         fwrite( buf, 1, (offset + 7) / 8, stdout );
  1029.     bytes_out += (offset + 7) / 8;
  1030.     offset = 0;
  1031.     fflush( stdout );
  1032. #ifdef DEBUG
  1033.     if ( verbose )
  1034.         fprintf( stderr, "\n" );
  1035. #endif /* DEBUG */
  1036.     if( ferror( stdout ) )
  1037.         writeerr();
  1038.     }
  1039. }
  1040.  
  1041. /*
  1042.  * Decompress stdin to stdout.  This routine adapts to the codes in the
  1043.  * file building the "string" table on-the-fly; requiring no table to
  1044.  * be stored in the compressed file.  The tables used herein are shared
  1045.  * with those of the compress() routine.  See the definitions above.
  1046.  */
  1047.  
  1048. decompress() {
  1049.     register char_type *stackp;
  1050.     register int finchar;
  1051.     register code_int code, oldcode, incode;
  1052.  
  1053.     /*
  1054.      * As above, initialize the first 256 entries in the table.
  1055.      */
  1056.     maxcode = MAXCODE(n_bits = INIT_BITS);
  1057.     for ( code = 255; code >= 0; code-- ) {
  1058.     tab_prefixof(code) = 0;
  1059.     tab_suffixof(code) = (char_type)code;
  1060.     }
  1061.     free_ent = ((block_compress) ? FIRST : 256 );
  1062.  
  1063.     finchar = oldcode = getcode();
  1064.     if(oldcode == -1)    /* EOF already? */
  1065.     return;            /* Get out of here */
  1066.     putchar( (char)finchar );        /* first code must be 8 bits = char */
  1067.     if(ferror(stdout))        /* Crash if can't write */
  1068.     writeerr();
  1069.     stackp = de_stack;
  1070.  
  1071.     while ( (code = getcode()) > -1 ) {
  1072.  
  1073.     if ( (code == CLEAR) && block_compress ) {
  1074.         for ( code = 255; code >= 0; code-- )
  1075.         tab_prefixof(code) = 0;
  1076.         clear_flg = 1;
  1077.         free_ent = FIRST - 1;
  1078.         if ( (code = getcode ()) == -1 )    /* O, untimely death! */
  1079.         break;
  1080.     }
  1081.     incode = code;
  1082.     /*
  1083.      * Special case for KwKwK string.
  1084.      */
  1085.     if ( code >= free_ent ) {
  1086.             *stackp++ = finchar;
  1087.         code = oldcode;
  1088.     }
  1089.  
  1090.     /*
  1091.      * Generate output characters in reverse order
  1092.      */
  1093. #ifdef SIGNED_COMPARE_SLOW
  1094.     while ( ((unsigned long)code) >= ((unsigned long)256) ) {
  1095. #else
  1096.     while ( code >= 256 ) {
  1097. #endif
  1098.         *stackp++ = tab_suffixof(code);
  1099.         code = tab_prefixof(code);
  1100.     }
  1101.     *stackp++ = finchar = tab_suffixof(code);
  1102.  
  1103.     /*
  1104.      * And put them out in forward order
  1105.      */
  1106.     do
  1107.         putchar ( *--stackp );
  1108.     while ( stackp > de_stack );
  1109.  
  1110.     /*
  1111.      * Generate the new entry.
  1112.      */
  1113.     if ( (code=free_ent) < maxmaxcode ) {
  1114.         tab_prefixof(code) = (unsigned short)oldcode;
  1115.         tab_suffixof(code) = finchar;
  1116.         free_ent = code+1;
  1117.     } 
  1118.     /*
  1119.      * Remember previous code.
  1120.      */
  1121.     oldcode = incode;
  1122.     }
  1123.     fflush( stdout );
  1124.     if(ferror(stdout))
  1125.     writeerr();
  1126. }
  1127.  
  1128. /*****************************************************************
  1129.  * TAG( getcode )
  1130.  *
  1131.  * Read one code from the standard input.  If EOF, return -1.
  1132.  * Inputs:
  1133.  *     stdin
  1134.  * Outputs:
  1135.  *     code or -1 is returned.
  1136.  */
  1137.  
  1138. code_int
  1139. getcode() {
  1140.     /*
  1141.      * On the VAX, it is important to have the register declarations
  1142.      * in exactly the order given, or the asm will break.
  1143.      */
  1144.     register code_int code;
  1145.     static int offset = 0, size = 0;
  1146.     static char_type buf[BITS];
  1147.     register int r_off, bits;
  1148.     register char_type *bp = buf;
  1149.  
  1150.     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1151.     /*
  1152.      * If the next entry will be too big for the current code
  1153.      * size, then we must increase the size.  This implies reading
  1154.      * a new buffer full, too.
  1155.      */
  1156.     if ( free_ent > maxcode ) {
  1157.         n_bits++;
  1158.         if ( n_bits == maxbits )
  1159.         maxcode = maxmaxcode;    /* won't get any bigger now */
  1160.         else
  1161.         maxcode = MAXCODE(n_bits);
  1162.     }
  1163.     if ( clear_flg > 0) {
  1164.             maxcode = MAXCODE (n_bits = INIT_BITS);
  1165.         clear_flg = 0;
  1166.     }
  1167.     size = fread( buf, 1, n_bits, stdin );
  1168.     if ( size <= 0 )
  1169.         return -1;            /* end of file */
  1170.     offset = 0;
  1171.     /* Round size down to integral number of codes */
  1172.     size = (size << 3) - (n_bits - 1);
  1173.     }
  1174.     r_off = offset;
  1175.     bits = n_bits;
  1176. #ifdef vax
  1177.     asm( "extzv   r10,r9,(r8),r11" );
  1178. #else /* not a vax */
  1179.     /*
  1180.      * Get to the first byte.
  1181.      */
  1182.     bp += (r_off >> 3);
  1183.     r_off &= 7;
  1184.     /* Get first part (low order bits) */
  1185. #ifdef NO_UCHAR
  1186.     code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1187. #else
  1188.     code = (*bp++ >> r_off);
  1189. #endif /* NO_UCHAR */
  1190.     bits -= (8 - r_off);
  1191.     r_off = 8 - r_off;        /* now, offset into code word */
  1192.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1193.     if ( bits >= 8 ) {
  1194. #ifdef NO_UCHAR
  1195.         code |= (*bp++ & 0xff) << r_off;
  1196. #else
  1197.         code |= *bp++ << r_off;
  1198. #endif /* NO_UCHAR */
  1199.         r_off += 8;
  1200.         bits -= 8;
  1201.     }
  1202.     /* high order bits. */
  1203.     code |= (*bp & rmask[bits]) << r_off;
  1204. #endif /* vax */
  1205.     offset += n_bits;
  1206.  
  1207.     return code;
  1208. }
  1209.  
  1210. #ifndef __GO32__
  1211. char *
  1212. rindex(s, c)        /* For those who don't have it in libc.a */
  1213. register char *s, c;
  1214. {
  1215.     char *p;
  1216.     for (p = NULL; *s; s++)
  1217.         if (*s == c)
  1218.         p = s;
  1219.     return(p);
  1220. }
  1221. #endif
  1222.  
  1223. #ifdef DEBUG
  1224. printcodes()
  1225. {
  1226.     /*
  1227.      * Just print out codes from input file.  For debugging.
  1228.      */
  1229.     code_int code;
  1230.     int col = 0, bits;
  1231.  
  1232.     bits = n_bits = INIT_BITS;
  1233.     maxcode = MAXCODE(n_bits);
  1234.     free_ent = ((block_compress) ? FIRST : 256 );
  1235.     while ( ( code = getcode() ) >= 0 ) {
  1236.     if ( (code == CLEAR) && block_compress ) {
  1237.            free_ent = FIRST - 1;
  1238.            clear_flg = 1;
  1239.     }
  1240.     else if ( free_ent < maxmaxcode )
  1241.         free_ent++;
  1242.     if ( bits != n_bits ) {
  1243.         fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1244.         bits = n_bits;
  1245.         col = 0;
  1246.     }
  1247.     fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1248.     }
  1249.     putc( '\n', stderr );
  1250.     exit( 0 );
  1251. }
  1252.  
  1253. code_int sorttab[1<<BITS];    /* sorted pointers into htab */
  1254.  
  1255. dump_tab()    /* dump string table */
  1256. {
  1257.     register int i, first;
  1258.     register ent;
  1259. #define STACK_SIZE    15000
  1260.     int stack_top = STACK_SIZE;
  1261.     register c;
  1262.  
  1263.     if(do_decomp == 0) {    /* compressing */
  1264.     register int flag = 1;
  1265.  
  1266.     for(i=0; i<hsize; i++) {    /* build sort pointers */
  1267.         if((long)htabof(i) >= 0) {
  1268.             sorttab[codetabof(i)] = i;
  1269.         }
  1270.     }
  1271.     first = block_compress ? FIRST : 256;
  1272.     for(i = first; i < free_ent; i++) {
  1273.         fprintf(stderr, "%5d: \"", i);
  1274.         de_stack[--stack_top] = '\n';
  1275.         de_stack[--stack_top] = '"';
  1276.         stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff, 
  1277.                                      stack_top);
  1278.         for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  1279.             ent > 256;
  1280.             ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  1281.             stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1282.                         stack_top);
  1283.         }
  1284.         stack_top = in_stack(ent, stack_top);
  1285.         fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1286.            stack_top = STACK_SIZE;
  1287.     }
  1288.    } else if(!debug) {    /* decompressing */
  1289.  
  1290.        for ( i = 0; i < free_ent; i++ ) {
  1291.        ent = i;
  1292.        c = tab_suffixof(ent);
  1293.        if ( isascii(c) && isprint(c) )
  1294.            fprintf( stderr, "%5d: %5d/'%c'  \"",
  1295.                ent, tab_prefixof(ent), c );
  1296.        else
  1297.            fprintf( stderr, "%5d: %5d/\\%03o \"",
  1298.                ent, tab_prefixof(ent), c );
  1299.        de_stack[--stack_top] = '\n';
  1300.        de_stack[--stack_top] = '"';
  1301.        for ( ; ent != NULL;
  1302.            ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  1303.            stack_top = in_stack(tab_suffixof(ent), stack_top);
  1304.        }
  1305.        fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1306.        stack_top = STACK_SIZE;
  1307.        }
  1308.     }
  1309. }
  1310.  
  1311. int
  1312. in_stack(c, stack_top)
  1313.     register c, stack_top;
  1314. {
  1315.     if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1316.         de_stack[--stack_top] = c;
  1317.     } else {
  1318.         switch( c ) {
  1319.         case '\n': de_stack[--stack_top] = 'n'; break;
  1320.         case '\t': de_stack[--stack_top] = 't'; break;
  1321.         case '\b': de_stack[--stack_top] = 'b'; break;
  1322.         case '\f': de_stack[--stack_top] = 'f'; break;
  1323.         case '\r': de_stack[--stack_top] = 'r'; break;
  1324.         case '\\': de_stack[--stack_top] = '\\'; break;
  1325.         default:
  1326.          de_stack[--stack_top] = '0' + c % 8;
  1327.          de_stack[--stack_top] = '0' + (c / 8) % 8;
  1328.          de_stack[--stack_top] = '0' + c / 64;
  1329.          break;
  1330.         }
  1331.         de_stack[--stack_top] = '\\';
  1332.     }
  1333.     return stack_top;
  1334. }
  1335. #endif /* DEBUG */
  1336.  
  1337. writeerr()
  1338. {
  1339.     perror ( ofname );
  1340.     unlink ( ofname );
  1341.     exit ( 1 );
  1342. }
  1343.  
  1344. copystat(ifname, ofname)
  1345. char *ifname, *ofname;
  1346. {
  1347.     struct stat statbuf;
  1348.     int mode;
  1349.     time_t timep[2];
  1350.  
  1351.     fclose(stdout);
  1352.     if (stat(ifname, &statbuf)) {        /* Get stat on input file */
  1353.     perror(ifname);
  1354.     return;
  1355.     }
  1356.     if ((statbuf.st_mode & S_IFMT/*0170000*/) != S_IFREG/*0100000*/) {
  1357.     if(quiet)
  1358.             fprintf(stderr, "%s: ", ifname);
  1359.     fprintf(stderr, " -- not a regular file: unchanged");
  1360.     exit_stat = 1;
  1361.     perm_stat = 1;
  1362.     } else if (statbuf.st_nlink > 1) {
  1363.     if(quiet)
  1364.             fprintf(stderr, "%s: ", ifname);
  1365.     fprintf(stderr, " -- has %d other links: unchanged",
  1366.         statbuf.st_nlink - 1);
  1367.     exit_stat = 1;
  1368.     perm_stat = 1;
  1369.     } else if (exit_stat == 2 && (!force)) { /* No compression: remove file.Z */
  1370.     if(!quiet)
  1371.         fprintf(stderr, " -- file unchanged");
  1372.     } else {            /* ***** Successful Compression ***** */
  1373.     exit_stat = 0;
  1374.     mode = statbuf.st_mode & 07777;
  1375. #if 0
  1376.     if (chmod(ofname, mode))        /* Copy modes */
  1377.         perror(ofname);
  1378. #endif
  1379.     chown(ofname, statbuf.st_uid, statbuf.st_gid);    /* Copy ownership */
  1380.     timep[0] = statbuf.st_atime;
  1381.     timep[1] = statbuf.st_mtime;
  1382.     utime(ofname, timep);    /* Update last accessed and modified times */
  1383. #if 0
  1384.     if (unlink(ifname))    /* Remove input file */
  1385.         perror(ifname);
  1386. #else
  1387.     unlink(ifname);
  1388. #endif
  1389.     if(!quiet)
  1390.         fprintf(stderr, " -- replaced with %s", ofname);
  1391.     return;        /* Successful return */
  1392.     }
  1393.  
  1394.     /* Unsuccessful return -- one of the tests failed */
  1395.     if (unlink(ofname))
  1396.     perror(ofname);
  1397. }
  1398.  
  1399. void
  1400. onintr ( )
  1401. {
  1402.     if (!precious)
  1403.     unlink ( ofname );
  1404.     exit ( 1 );
  1405. }
  1406.  
  1407. void
  1408. oops ( )    /* wild pointer -- assume bad input */
  1409. {
  1410.     if ( do_decomp ) 
  1411.         fprintf ( stderr, "uncompress: corrupt input\n" );
  1412.     unlink ( ofname );
  1413.     exit ( 1 );
  1414. }
  1415.  
  1416. cl_block ()        /* table clear for block compress */
  1417. {
  1418.     register long int rat;
  1419.  
  1420.     checkpoint = in_count + CHECK_GAP;
  1421. #ifdef DEBUG
  1422.     if ( debug ) {
  1423.             fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1424.              prratio ( stderr, in_count, bytes_out );
  1425.         fprintf ( stderr, "\n");
  1426.     }
  1427. #endif /* DEBUG */
  1428.  
  1429.     if(in_count > 0x007fffff) {    /* shift will overflow */
  1430.     rat = bytes_out >> 8;
  1431.     if(rat == 0) {        /* Don't divide by zero */
  1432.         rat = 0x7fffffff;
  1433.     } else {
  1434.         rat = in_count / rat;
  1435.     }
  1436.     } else {
  1437.     rat = (in_count << 8) / bytes_out;    /* 8 fractional bits */
  1438.     }
  1439.     if ( rat > ratio ) {
  1440.     ratio = rat;
  1441.     } else {
  1442.     ratio = 0;
  1443. #ifdef DEBUG
  1444.     if(verbose)
  1445.         dump_tab();    /* dump string table */
  1446. #endif
  1447.      cl_hash ( (count_int) hsize );
  1448.     free_ent = FIRST;
  1449.     clear_flg = 1;
  1450.     output ( (code_int) CLEAR );
  1451. #ifdef DEBUG
  1452.     if(debug)
  1453.             fprintf ( stderr, "clear\n" );
  1454. #endif /* DEBUG */
  1455.     }
  1456. }
  1457.  
  1458. cl_hash(hsize)        /* reset code table */
  1459.     register count_int hsize;
  1460. {
  1461. #ifndef XENIX_16    /* Normal machine */
  1462.     register count_int *htab_p = htab+hsize;
  1463. #else
  1464.     register j;
  1465.     register long k = hsize;
  1466.     register count_int *htab_p;
  1467. #endif
  1468.     register long i;
  1469.     register long m1 = -1;
  1470.  
  1471. #ifdef XENIX_16
  1472.     for(j=0; j<=8 && k>=0; j++,k-=8192) {
  1473.     i = 8192;
  1474.     if(k < 8192) {
  1475.         i = k;
  1476.     }
  1477.     htab_p = &(htab[j][i]);
  1478.     i -= 16;
  1479.     if(i > 0) {
  1480. #else
  1481.     i = hsize - 16;
  1482. #endif
  1483.      do {                /* might use Sys V memset(3) here */
  1484.         *(htab_p-16) = m1;
  1485.         *(htab_p-15) = m1;
  1486.         *(htab_p-14) = m1;
  1487.         *(htab_p-13) = m1;
  1488.         *(htab_p-12) = m1;
  1489.         *(htab_p-11) = m1;
  1490.         *(htab_p-10) = m1;
  1491.         *(htab_p-9) = m1;
  1492.         *(htab_p-8) = m1;
  1493.         *(htab_p-7) = m1;
  1494.         *(htab_p-6) = m1;
  1495.         *(htab_p-5) = m1;
  1496.         *(htab_p-4) = m1;
  1497.         *(htab_p-3) = m1;
  1498.         *(htab_p-2) = m1;
  1499.         *(htab_p-1) = m1;
  1500.         htab_p -= 16;
  1501.     } while ((i -= 16) >= 0);
  1502. #ifdef XENIX_16
  1503.     }
  1504.     }
  1505. #endif
  1506.         for ( i += 16; i > 0; i-- )
  1507.         *--htab_p = m1;
  1508. }
  1509.  
  1510. prratio(stream, num, den)
  1511. FILE *stream;
  1512. long int num, den;
  1513. {
  1514.     register int q;            /* Doesn't need to be long */
  1515.  
  1516.     if(num > 214748L) {        /* 2147483647/10000 */
  1517.         q = num / (den / 10000L);
  1518.     } else {
  1519.         q = 10000L * num / den;        /* Long calculations, though */
  1520.     }
  1521.     if (q < 0) {
  1522.         putc('-', stream);
  1523.         q = -q;
  1524.     }
  1525.     fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1526. }
  1527.  
  1528. version()
  1529. {
  1530.     fprintf(stderr, "%s, Berkeley 5.12 6/1/90\n", rcs_ident);
  1531.     fprintf(stderr, "Options: ");
  1532. #ifdef vax
  1533.     fprintf(stderr, "vax, ");
  1534. #endif
  1535. #ifdef NO_UCHAR
  1536.     fprintf(stderr, "NO_UCHAR, ");
  1537. #endif
  1538. #ifdef SIGNED_COMPARE_SLOW
  1539.     fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1540. #endif
  1541. #ifdef XENIX_16
  1542.     fprintf(stderr, "XENIX_16, ");
  1543. #endif
  1544. #ifdef COMPATIBLE
  1545.     fprintf(stderr, "COMPATIBLE, ");
  1546. #endif
  1547. #ifdef DEBUG
  1548.     fprintf(stderr, "DEBUG, ");
  1549. #endif
  1550. #ifdef BSD4_2
  1551.     fprintf(stderr, "BSD4_2, ");
  1552. #endif
  1553.     fprintf(stderr, "BITS = %d\n", BITS);
  1554. }
  1555.