home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / ae / AEC / Tests / compress.c < prev    next >
Encoding:
C/C++ Source or Header  |  1990-02-28  |  39.4 KB  |  1,511 lines

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