home *** CD-ROM | disk | FTP | other *** search
/ C/C++ Users Group Library 1996 July / C-C++ Users Group Library July 1996.iso / vol_300 / 359_10 / patch4.001 / SAMPLES / COMPRESS / COMPRESS.C < prev    next >
Encoding:
C/C++ Source or Header  |  1991-07-21  |  42.2 KB  |  1,549 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 <sys/types.h>
  292. #include <sys/stat.h>
  293. #ifdef notdef
  294. #include <sys/ioctl.h>
  295. #endif
  296.  
  297. #define ARGVAL() (*++(*argv) || (--argc && *++argv))
  298.  
  299. int n_bits;                /* number of bits/code */
  300. int maxbits = BITS;            /* user settable max # bits/code */
  301. code_int maxcode;            /* maximum code, given n_bits */
  302. code_int maxmaxcode = 1 << BITS;    /* should NEVER generate this code */
  303. #ifdef COMPATIBLE        /* But wrong! */
  304. # define MAXCODE(n_bits)    (1 << (n_bits) - 1)
  305. #else
  306. # define MAXCODE(n_bits)    ((1 << (n_bits)) - 1)
  307. #endif /* COMPATIBLE */
  308.  
  309. #ifdef XENIX_16
  310. count_int htab0[8192];
  311. count_int htab1[8192];
  312. count_int htab2[8192];
  313. count_int htab3[8192];
  314. count_int htab4[8192];
  315. count_int htab5[8192];
  316. count_int htab6[8192];
  317. count_int htab7[8192];
  318. count_int htab8[HSIZE-65536];
  319. count_int * htab[9] = {
  320.     htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
  321.  
  322. #define htabof(i)    (htab[(i) >> 13][(i) & 0x1fff])
  323. unsigned short code0tab[16384];
  324. unsigned short code1tab[16384];
  325. unsigned short code2tab[16384];
  326. unsigned short code3tab[16384];
  327. unsigned short code4tab[16384];
  328. unsigned short * codetab[5] = {
  329.     code0tab, code1tab, code2tab, code3tab, code4tab };
  330.  
  331. #define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
  332.  
  333. #else    /* Normal machine */
  334.  
  335. #ifdef sel    /* gould base register braindamage */
  336. /*NOBASE*/
  337. count_int htab [HSIZE];
  338. unsigned short codetab [HSIZE];
  339. /*NOBASE*/
  340. #else
  341. count_int htab [HSIZE];
  342. unsigned short codetab [HSIZE];
  343. #endif sel
  344.  
  345. #define htabof(i)    htab[i]
  346. #define codetabof(i)    codetab[i]
  347. #endif    /* XENIX_16 */
  348. code_int hsize = HSIZE;            /* for dynamic table sizing */
  349. count_int fsize;
  350.  
  351. /*
  352.  * To save much memory, we overlay the table used by compress() with those
  353.  * used by decompress().  The tab_prefix table is the same size and type
  354.  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
  355.  * get this from the beginning of htab.  The output stack uses the rest
  356.  * of htab, and contains characters.  There is plenty of room for any
  357.  * possible stack (stack used to be 8000 characters).
  358.  */
  359.  
  360. #define tab_prefixof(i)    codetabof(i)
  361. #ifdef XENIX_16
  362. # define tab_suffixof(i)    ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
  363. # define de_stack        ((char_type *)(htab2))
  364. #else    /* Normal machine */
  365. # define tab_suffixof(i)    ((char_type *)(htab))[i]
  366. # define de_stack        ((char_type *)&tab_suffixof(1<<BITS))
  367. #endif    /* XENIX_16 */
  368.  
  369. code_int free_ent = 0;            /* first unused entry */
  370. int exit_stat = 0;            /* per-file status */
  371. int perm_stat = 0;            /* permanent status */
  372.  
  373. code_int getcode();
  374.  
  375. Usage() {
  376. #ifdef DEBUG
  377. fprintf(stderr,"Usage: compress [-dDVfc] [-b maxbits] [file ...]\n");
  378. }
  379. int debug = 0;
  380. #else
  381. fprintf(stderr,"Usage: compress [-fvc] [-b maxbits] [file ...]\n");
  382. }
  383. #endif /* DEBUG */
  384. int nomagic = 0;    /* Use a 3-byte magic number header, unless old file */
  385. int zcat_flg = 0;    /* Write output on stdout, suppress messages */
  386. int precious = 1;    /* Don't unlink output file on interrupt */
  387. int quiet = 1;        /* don't tell me about compression */
  388.  
  389. /*
  390.  * block compression parameters -- after all codes are used up,
  391.  * and compression rate changes, start over.
  392.  */
  393. int block_compress = BLOCK_MASK;
  394. int clear_flg = 0;
  395. long int ratio = 0;
  396. #define CHECK_GAP 10000    /* ratio check interval */
  397. count_int checkpoint = CHECK_GAP;
  398. /*
  399.  * the next two codes should not be changed lightly, as they must not
  400.  * lie within the contiguous general code space.
  401.  */ 
  402. #define FIRST    257    /* first free entry */
  403. #define    CLEAR    256    /* table clear output code */
  404.  
  405. int force = 0;
  406. char ofname [100];
  407. #ifdef DEBUG
  408. int verbose = 0;
  409. #endif /* DEBUG */
  410. #if 0
  411. sig_t oldint;
  412. #endif
  413. int bgnd_flag=0;
  414.  
  415. int do_decomp = 0;
  416.  
  417. /*****************************************************************
  418.  * TAG( main )
  419.  *
  420.  * Algorithm from "A Technique for High Performance Data Compression",
  421.  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
  422.  *
  423.  * Usage: compress [-dfvc] [-b bits] [file ...]
  424.  * Inputs:
  425.  *    -d:        If given, decompression is done instead.
  426.  *
  427.  *      -c:         Write output on stdout, don't remove original.
  428.  *
  429.  *      -b:         Parameter limits the max number of bits/code.
  430.  *
  431.  *    -f:        Forces output file to be generated, even if one already
  432.  *            exists, and even if no space is saved by compressing.
  433.  *            If -f is not used, the user will be prompted if stdin is
  434.  *            a tty, otherwise, the output file will not be overwritten.
  435.  *
  436.  *      -v:        Write compression statistics
  437.  *
  438.  *     file ...:   Files to be compressed.  If none specified, stdin
  439.  *            is used.
  440.  * Outputs:
  441.  *    file.Z:        Compressed form of file with same mode, owner, and utimes
  442.  *     or stdout   (if stdin used as input)
  443.  *
  444.  * Assumptions:
  445.  *    When filenames are given, replaces with the compressed version
  446.  *    (.Z suffix) only if the file decreases in size.
  447.  * Algorithm:
  448.  *     Modified Lempel-Ziv method (LZW).  Basically finds common
  449.  * substrings and replaces them with a variable size code.  This is
  450.  * deterministic, and can be done on the fly.  Thus, the decompression
  451.  * procedure needs no input table, but tracks the way the table was built.
  452.  */
  453.  
  454. main( argc, argv )
  455. register int argc; char **argv;
  456. {
  457.     int overwrite = 0;    /* Do not overwrite unless given -f flag */
  458.     char tempname[100];
  459.     char **filelist, **fileptr;
  460.     char *cp, *rindex(), *malloc();
  461.     struct stat statbuf;
  462.     void onintr(), oops();
  463.  
  464.     /* This bg check only works for sh. */
  465. #if 0
  466.     if ( (oldint = signal ( SIGINT, SIG_IGN )) != SIG_IGN ) {
  467.     signal ( SIGINT, onintr );
  468.     signal ( SIGSEGV, oops );
  469.     }
  470.     bgnd_flag = oldint != SIG_DFL;
  471. #endif
  472. #ifdef notdef     /* This works for csh but we don't want it. */
  473.     { int tgrp;
  474.     if (bgnd_flag == 0 && ioctl(2, TIOCGPGRP, (char *)&tgrp) == 0 &&
  475.       getpgrp(0) != tgrp)
  476.     bgnd_flag = 1;
  477.     }
  478. #endif
  479.     
  480. #ifdef COMPATIBLE
  481.     nomagic = 1;    /* Original didn't have a magic number */
  482. #endif /* COMPATIBLE */
  483.  
  484.     filelist = fileptr = (char **)(malloc(argc * sizeof(*argv)));
  485.     *filelist = NULL;
  486.  
  487.     if((cp = rindex(argv[0], '/')) != 0) {
  488.     cp++;
  489.     } else {
  490.     cp = argv[0];
  491.     }
  492.     if(strcmp(cp, "uncompress") == 0) {
  493.     do_decomp = 1;
  494.     } else if(strcmp(cp, "zcat") == 0) {
  495.     do_decomp = 1;
  496.     zcat_flg = 1;
  497.     }
  498.  
  499. #ifdef BSD4_2
  500.     /* 4.2BSD dependent - take it out if not */
  501.     setlinebuf( stderr );
  502. #endif /* BSD4_2 */
  503.  
  504.     /* Argument Processing
  505.      * All flags are optional.
  506.      * -D => debug
  507.      * -V => print Version; debug verbose
  508.      * -d => do_decomp
  509.      * -v => unquiet
  510.      * -f => force overwrite of output file
  511.      * -n => no header: useful to uncompress old files
  512.      * -b maxbits => maxbits.  If -b is specified, then maxbits MUST be
  513.      *        given also.
  514.      * -c => cat all output to stdout
  515.      * -C => generate output compatible with compress 2.0.
  516.      * if a string is left, must be an input filename.
  517.      */
  518.     for (argc--, argv++; argc > 0; argc--, argv++) {
  519.     if (**argv == '-') {    /* A flag argument */
  520.         while (*++(*argv)) {    /* Process all flags in this arg */
  521.         switch (**argv) {
  522. #ifdef DEBUG
  523.             case 'D':
  524.             debug = 1;
  525.             break;
  526.             case 'V':
  527.             verbose = 1;
  528.             version();
  529.             break;
  530. #else
  531.             case 'V':
  532.             version();
  533.             break;
  534. #endif /* DEBUG */
  535.             case 'v':
  536.             quiet = 0;
  537.             break;
  538.             case 'd':
  539.             do_decomp = 1;
  540.             break;
  541.             case 'f':
  542.             case 'F':
  543.             overwrite = 1;
  544.             force = 1;
  545.             break;
  546.             case 'n':
  547.             nomagic = 1;
  548.             break;
  549.             case 'C':
  550.             block_compress = 0;
  551.             break;
  552.             case 'b':
  553.             if (!ARGVAL()) {
  554.                 fprintf(stderr, "Missing maxbits\n");
  555.                 Usage();
  556.                 exit(1);
  557.             }
  558.             maxbits = atoi(*argv);
  559.             goto nextarg;
  560.             case 'c':
  561.             zcat_flg = 1;
  562.             break;
  563.             case 'q':
  564.             quiet = 1;
  565.             break;
  566.             default:
  567.             fprintf(stderr, "Unknown flag: '%c'; ", **argv);
  568.             Usage();
  569.             exit(1);
  570.         }
  571.         }
  572.     }
  573.     else {        /* Input file name */
  574.         *fileptr++ = *argv;    /* Build input file list */
  575.         *fileptr = NULL;
  576.         /* process nextarg; */
  577.     }
  578.     nextarg: continue;
  579.     }
  580.  
  581.     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
  582.     if (maxbits > BITS) maxbits = BITS;
  583.     maxmaxcode = 1 << maxbits;
  584.  
  585.     if (*filelist != NULL) {
  586.     for (fileptr = filelist; *fileptr; fileptr++) {
  587.         exit_stat = 0;
  588.         if (do_decomp) {            /* DECOMPRESSION */
  589.         /* Check for .Z suffix */
  590.         if (strcmp(*fileptr + strlen(*fileptr) - 1, "Z") != 0) {
  591.             /* No .Z: tack one on */
  592.             strcpy(tempname, *fileptr);
  593.             strcat(tempname, "Z");
  594.             *fileptr = tempname;
  595.         }
  596.         /* Open input file */
  597.         if ((freopen(*fileptr, "rb", stdin)) == NULL) {
  598.             perror(*fileptr);
  599.             perm_stat = 1;
  600.             continue;
  601.         }
  602.         /* Check the magic number */
  603.         if (nomagic == 0) {
  604.             if ((getchar() != (magic_header[0] & 0xFF))
  605.              || (getchar() != (magic_header[1] & 0xFF))) {
  606.             fprintf(stderr, "%s: not in compressed format\n",
  607.                 *fileptr);
  608.             continue;
  609.             }
  610.             maxbits = getchar();    /* set -b from file */
  611.             block_compress = maxbits & BLOCK_MASK;
  612.             maxbits &= BIT_MASK;
  613.             maxmaxcode = 1 << maxbits;
  614.             if(maxbits > BITS) {
  615.             fprintf(stderr,
  616.             "%s: compressed with %d bits, can only handle %d bits\n",
  617.             *fileptr, maxbits, BITS);
  618.             continue;
  619.             }
  620.         }
  621.         /* Generate output filename */
  622.         strcpy(ofname, *fileptr);
  623.         ofname[strlen(*fileptr) - 1] = '\0';  /* Strip off .Z */
  624.         } else {                    /* COMPRESSION */
  625.         if (strcmp(*fileptr + strlen(*fileptr) - 1, "Z") == 0) {
  626.                 fprintf(stderr, "%s: already has Z suffix -- no change\n",
  627.                 *fileptr);
  628.             continue;
  629.         }
  630.         /* Open input file */
  631.         if ((freopen(*fileptr, "rb", stdin)) == NULL) {
  632.             perror(*fileptr);
  633.             perm_stat = 1;
  634.             continue;
  635.         }
  636.         stat ( *fileptr, &statbuf );
  637.         fsize = (long) statbuf.st_size;
  638.         /*
  639.          * tune hash table size for small files -- ad hoc,
  640.          * but the sizes match earlier #defines, which
  641.          * serve as upper bounds on the number of output codes. 
  642.          */
  643.         hsize = HSIZE;
  644.         if ( fsize < (1 << 12) )
  645.             hsize = min ( 5003, HSIZE );
  646.         else if ( fsize < (1 << 13) )
  647.             hsize = min ( 9001, HSIZE );
  648.         else if ( fsize < (1 << 14) )
  649.             hsize = min ( 18013, HSIZE );
  650.         else if ( fsize < (1 << 15) )
  651.             hsize = min ( 35023, HSIZE );
  652.         else if ( fsize < 47000 )
  653.             hsize = min ( 50021, HSIZE );
  654.  
  655.         /* Generate output filename */
  656.         strcpy(ofname, *fileptr);
  657. #ifndef BSD4_2        /* Short filenames */
  658.         if ((cp=rindex(ofname,'/')) != NULL)    cp++;
  659.         else                    cp = ofname;
  660.         if (strlen(cp) > 12) {
  661.             fprintf(stderr,"%s: filename too long to tack on Z\n",cp);
  662.             continue;
  663.         }
  664. #endif  /* BSD4_2        Long filenames allowed */
  665.         strcat(ofname, "Z");
  666.         }
  667.         /* Check for overwrite of existing file */
  668.         if (overwrite == 0 && zcat_flg == 0) {
  669.         if (stat(ofname, &statbuf) == 0) {
  670.             char response[2];
  671.             response[0] = 'n';
  672.             fprintf(stderr, "%s already exists;", ofname);
  673.             if (bgnd_flag == 0 && isatty(2)) {
  674.             fprintf(stderr, " do you wish to overwrite %s (y or n)? ",
  675.             ofname);
  676.             fflush(stderr);
  677.             read(2, response, 2);
  678.             while (response[1] != '\n') {
  679.                 if (read(2, response+1, 1) < 0) {    /* Ack! */
  680.                 perror("stderr"); break;
  681.                 }
  682.             }
  683.             }
  684.             if (response[0] != 'y') {
  685.             fprintf(stderr, "\tnot overwritten\n");
  686.             continue;
  687.             }
  688.         }
  689.         }
  690.         if(zcat_flg == 0) {        /* Open output file */
  691.         if (freopen(ofname, "wb", stdout) == NULL) {
  692.             perror(ofname);
  693.             perm_stat = 1;
  694.             continue;
  695.         }
  696.         precious = 0;
  697.         if(!quiet)
  698.             fprintf(stderr, "%s: ", *fileptr);
  699.         }
  700.  
  701.         /* Actually do the compression/decompression */
  702.         if (do_decomp == 0)    compress();
  703. #ifndef DEBUG
  704.         else            decompress();
  705. #else
  706.         else if (debug == 0)    decompress();
  707.         else            printcodes();
  708.         if (verbose)        dump_tab();
  709. #endif /* DEBUG */
  710.         if(zcat_flg == 0) {
  711.         copystat(*fileptr, ofname);    /* Copy stats */
  712.         precious = 1;
  713.         if((exit_stat == 1) || (!quiet))
  714.             putc('\n', stderr);
  715.         }
  716.     }
  717.     } else {        /* Standard input */
  718.     if (do_decomp == 0) {
  719.         compress();
  720. #ifdef DEBUG
  721.         if(verbose)        dump_tab();
  722. #endif /* DEBUG */
  723.         if(!quiet)
  724.             putc('\n', stderr);
  725.     } else {
  726.         /* Check the magic number */
  727.         if (nomagic == 0) {
  728.         if ((getchar()!=(magic_header[0] & 0xFF))
  729.          || (getchar()!=(magic_header[1] & 0xFF))) {
  730.             fprintf(stderr, "stdin: not in compressed format\n");
  731.             exit(1);
  732.         }
  733.         maxbits = getchar();    /* set -b from file */
  734.         block_compress = maxbits & BLOCK_MASK;
  735.         maxbits &= BIT_MASK;
  736.         maxmaxcode = 1 << maxbits;
  737.         fsize = 100000;        /* assume stdin large for USERMEM */
  738.         if(maxbits > BITS) {
  739.             fprintf(stderr,
  740.             "stdin: compressed with %d bits, can only handle %d bits\n",
  741.             maxbits, BITS);
  742.             exit(1);
  743.         }
  744.         }
  745. #ifndef DEBUG
  746.         decompress();
  747. #else
  748.         if (debug == 0)    decompress();
  749.         else        printcodes();
  750.         if (verbose)    dump_tab();
  751. #endif /* DEBUG */
  752.     }
  753.     }
  754.     exit(perm_stat ? perm_stat : exit_stat);
  755. }
  756.  
  757. static int offset;
  758. long int in_count = 1;            /* length of input */
  759. long int bytes_out;            /* length of compressed output */
  760. long int out_count = 0;            /* # of codes output (for debugging) */
  761.  
  762. /*
  763.  * compress stdin to stdout
  764.  *
  765.  * Algorithm:  use open addressing double hashing (no chaining) on the 
  766.  * prefix code / next character combination.  We do a variant of Knuth's
  767.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  768.  * secondary probe.  Here, the modular division first probe is gives way
  769.  * to a faster exclusive-or manipulation.  Also do block compression with
  770.  * an adaptive reset, whereby the code table is cleared when the compression
  771.  * ratio decreases, but after the table fills.  The variable-length output
  772.  * codes are re-sized at this point, and a special CLEAR code is generated
  773.  * for the decompressor.  Late addition:  construct the table according to
  774.  * file size for noticeable speed improvement on small files.  Please direct
  775.  * questions about this implementation to ames!jaw.
  776.  */
  777.  
  778. compress() {
  779.     register long fcode;
  780.     register code_int i = 0;
  781.     register int c;
  782.     register code_int ent;
  783. #ifdef XENIX_16
  784.     register code_int disp;
  785. #else    /* Normal machine */
  786.     register int disp;
  787. #endif
  788.     register code_int hsize_reg;
  789.     register int hshift;
  790.  
  791. #ifndef COMPATIBLE
  792.     if (nomagic == 0) {
  793.     putchar(magic_header[0]); putchar(magic_header[1]);
  794.     putchar((char)(maxbits | block_compress));
  795.     if(ferror(stdout))
  796.         writeerr();
  797.     }
  798. #endif /* COMPATIBLE */
  799.  
  800.     offset = 0;
  801.     bytes_out = 3;        /* includes 3-byte header mojo */
  802.     out_count = 0;
  803.     clear_flg = 0;
  804.     ratio = 0;
  805.     in_count = 1;
  806.     checkpoint = CHECK_GAP;
  807.     maxcode = MAXCODE(n_bits = INIT_BITS);
  808.     free_ent = ((block_compress) ? FIRST : 256 );
  809.  
  810.     ent = getchar ();
  811.  
  812.     hshift = 0;
  813.     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
  814.         hshift++;
  815.     hshift = 8 - hshift;        /* set hash code range bound */
  816.  
  817.     hsize_reg = hsize;
  818.     cl_hash( (count_int) hsize_reg);        /* clear hash table */
  819.  
  820. #ifdef SIGNED_COMPARE_SLOW
  821.     while ( (c = getchar()) != (unsigned) EOF ) {
  822. #else
  823.     while ( (c = getchar()) != EOF ) {
  824. #endif
  825.     in_count++;
  826.     fcode = (long) (((long) c << maxbits) + ent);
  827.      i = ((c << hshift) ^ ent);    /* xor hashing */
  828.  
  829.     if ( htabof (i) == fcode ) {
  830.         ent = codetabof (i);
  831.         continue;
  832.     } else if ( (long)htabof (i) < 0 )    /* empty slot */
  833.         goto nomatch;
  834.      disp = hsize_reg - i;        /* secondary hash (after G. Knott) */
  835.     if ( i == 0 )
  836.         disp = 1;
  837. probe:
  838.     if ( (i -= disp) < 0 )
  839.         i += hsize_reg;
  840.  
  841.     if ( htabof (i) == fcode ) {
  842.         ent = codetabof (i);
  843.         continue;
  844.     }
  845.     if ( (long)htabof (i) > 0 ) 
  846.         goto probe;
  847. nomatch:
  848.     output ( (code_int) ent );
  849.     out_count++;
  850.      ent = c;
  851. #ifdef SIGNED_COMPARE_SLOW
  852.     if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
  853. #else
  854.     if ( free_ent < maxmaxcode ) {
  855. #endif
  856.          codetabof (i) = free_ent++;    /* code -> hashtable */
  857.         htabof (i) = fcode;
  858.     }
  859.     else if ( (count_int)in_count >= checkpoint && block_compress )
  860.         cl_block ();
  861.     }
  862.     /*
  863.      * Put out the final code.
  864.      */
  865.     output( (code_int)ent );
  866.     out_count++;
  867.     output( (code_int)-1 );
  868.  
  869.     /*
  870.      * Print out stats on stderr
  871.      */
  872.     if(zcat_flg == 0 && !quiet) {
  873. #ifdef DEBUG
  874.     fprintf( stderr,
  875.         "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
  876.         in_count, out_count, bytes_out );
  877.     prratio( stderr, in_count, bytes_out );
  878.     fprintf( stderr, "\n");
  879.     fprintf( stderr, "\tCompression as in compact: " );
  880.     prratio( stderr, in_count-bytes_out, in_count );
  881.     fprintf( stderr, "\n");
  882.     fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
  883.         free_ent - 1, n_bits );
  884. #else /* !DEBUG */
  885.     fprintf( stderr, "Compression: " );
  886.     prratio( stderr, in_count-bytes_out, in_count );
  887. #endif /* DEBUG */
  888.     }
  889.     if(bytes_out > in_count)    /* exit(2) if no savings */
  890.     exit_stat = 2;
  891.     return;
  892. }
  893.  
  894. /*****************************************************************
  895.  * TAG( output )
  896.  *
  897.  * Output the given code.
  898.  * Inputs:
  899.  *     code:    A n_bits-bit integer.  If == -1, then EOF.  This assumes
  900.  *        that n_bits =< (long)wordsize - 1.
  901.  * Outputs:
  902.  *     Outputs code to the file.
  903.  * Assumptions:
  904.  *    Chars are 8 bits long.
  905.  * Algorithm:
  906.  *     Maintain a BITS character long buffer (so that 8 codes will
  907.  * fit in it exactly).  Use the VAX insv instruction to insert each
  908.  * code in turn.  When the buffer fills up empty it and start over.
  909.  */
  910.  
  911. static char buf[BITS];
  912.  
  913. #ifndef vax
  914. char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
  915. char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
  916. #endif /* vax */
  917.  
  918. output( code )
  919. code_int  code;
  920. {
  921. #ifdef DEBUG
  922.     static int col = 0;
  923. #endif /* DEBUG */
  924.  
  925.     /*
  926.      * On the VAX, it is important to have the register declarations
  927.      * in exactly the order given, or the asm will break.
  928.      */
  929.     register int r_off = offset, bits= n_bits;
  930.     register char * bp = buf;
  931.  
  932. #ifdef DEBUG
  933.     if ( verbose )
  934.         fprintf( stderr, "%5d%c", code,
  935.             (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  936. #endif /* DEBUG */
  937.     if ( code >= 0 ) {
  938. #ifdef vax
  939.     /* VAX DEPENDENT!! Implementation on other machines is below.
  940.      *
  941.      * Translation: Insert BITS bits from the argument starting at
  942.      * offset bits from the beginning of buf.
  943.      */
  944.     0;    /* Work around for pcc -O bug with asm and if stmt */
  945.     asm( "insv    4(ap),r11,r10,(r9)" );
  946. #else /* not a vax */
  947. /* 
  948.  * byte/bit numbering on the VAX is simulated by the following code
  949.  */
  950.     /*
  951.      * Get to the first byte.
  952.      */
  953.     bp += (r_off >> 3);
  954.     r_off &= 7;
  955.     /*
  956.      * Since code is always >= 8 bits, only need to mask the first
  957.      * hunk on the left.
  958.      */
  959.     *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
  960.     bp++;
  961.     bits -= (8 - r_off);
  962.     code >>= 8 - r_off;
  963.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  964.     if ( bits >= 8 ) {
  965.         *bp++ = code;
  966.         code >>= 8;
  967.         bits -= 8;
  968.     }
  969.     /* Last bits. */
  970.     if(bits)
  971.         *bp = code;
  972. #endif /* vax */
  973.     offset += n_bits;
  974.     if ( offset == (n_bits << 3) ) {
  975.         bp = buf;
  976.         bits = n_bits;
  977.         bytes_out += bits;
  978.         do
  979.         putchar(*bp++);
  980.         while(--bits);
  981.         offset = 0;
  982.     }
  983.  
  984.     /*
  985.      * If the next entry is going to be too big for the code size,
  986.      * then increase it, if possible.
  987.      */
  988.     if ( free_ent > maxcode || (clear_flg > 0))
  989.     {
  990.         /*
  991.          * Write the whole buffer, because the input side won't
  992.          * discover the size increase until after it has read it.
  993.          */
  994.         if ( offset > 0 ) {
  995.         if( fwrite( buf, 1, n_bits, stdout ) != n_bits)
  996.             writeerr();
  997.         bytes_out += n_bits;
  998.         }
  999.         offset = 0;
  1000.  
  1001.         if ( clear_flg ) {
  1002.                 maxcode = MAXCODE (n_bits = INIT_BITS);
  1003.             clear_flg = 0;
  1004.         }
  1005.         else {
  1006.             n_bits++;
  1007.             if ( n_bits == maxbits )
  1008.             maxcode = maxmaxcode;
  1009.             else
  1010.             maxcode = MAXCODE(n_bits);
  1011.         }
  1012. #ifdef DEBUG
  1013.         if ( debug ) {
  1014.         fprintf( stderr, "\nChange to %d bits\n", n_bits );
  1015.         col = 0;
  1016.         }
  1017. #endif /* DEBUG */
  1018.     }
  1019.     } else {
  1020.     /*
  1021.      * At EOF, write the rest of the buffer.
  1022.      */
  1023.     if ( offset > 0 )
  1024.         fwrite( buf, 1, (offset + 7) / 8, stdout );
  1025.     bytes_out += (offset + 7) / 8;
  1026.     offset = 0;
  1027.     fflush( stdout );
  1028. #ifdef DEBUG
  1029.     if ( verbose )
  1030.         fprintf( stderr, "\n" );
  1031. #endif /* DEBUG */
  1032.     if( ferror( stdout ) )
  1033.         writeerr();
  1034.     }
  1035. }
  1036.  
  1037. /*
  1038.  * Decompress stdin to stdout.  This routine adapts to the codes in the
  1039.  * file building the "string" table on-the-fly; requiring no table to
  1040.  * be stored in the compressed file.  The tables used herein are shared
  1041.  * with those of the compress() routine.  See the definitions above.
  1042.  */
  1043.  
  1044. decompress() {
  1045.     register char_type *stackp;
  1046.     register int finchar;
  1047.     register code_int code, oldcode, incode;
  1048.  
  1049.     /*
  1050.      * As above, initialize the first 256 entries in the table.
  1051.      */
  1052.     maxcode = MAXCODE(n_bits = INIT_BITS);
  1053.     for ( code = 255; code >= 0; code-- ) {
  1054.     tab_prefixof(code) = 0;
  1055.     tab_suffixof(code) = (char_type)code;
  1056.     }
  1057.     free_ent = ((block_compress) ? FIRST : 256 );
  1058.  
  1059.     finchar = oldcode = getcode();
  1060.     if(oldcode == -1)    /* EOF already? */
  1061.     return;            /* Get out of here */
  1062.     putchar( (char)finchar );        /* first code must be 8 bits = char */
  1063.     if(ferror(stdout))        /* Crash if can't write */
  1064.     writeerr();
  1065.     stackp = de_stack;
  1066.  
  1067.     while ( (code = getcode()) > -1 ) {
  1068.  
  1069.     if ( (code == CLEAR) && block_compress ) {
  1070.         for ( code = 255; code >= 0; code-- )
  1071.         tab_prefixof(code) = 0;
  1072.         clear_flg = 1;
  1073.         free_ent = FIRST - 1;
  1074.         if ( (code = getcode ()) == -1 )    /* O, untimely death! */
  1075.         break;
  1076.     }
  1077.     incode = code;
  1078.     /*
  1079.      * Special case for KwKwK string.
  1080.      */
  1081.     if ( code >= free_ent ) {
  1082.             *stackp++ = finchar;
  1083.         code = oldcode;
  1084.     }
  1085.  
  1086.     /*
  1087.      * Generate output characters in reverse order
  1088.      */
  1089. #ifdef SIGNED_COMPARE_SLOW
  1090.     while ( ((unsigned long)code) >= ((unsigned long)256) ) {
  1091. #else
  1092.     while ( code >= 256 ) {
  1093. #endif
  1094.         *stackp++ = tab_suffixof(code);
  1095.         code = tab_prefixof(code);
  1096.     }
  1097.     *stackp++ = finchar = tab_suffixof(code);
  1098.  
  1099.     /*
  1100.      * And put them out in forward order
  1101.      */
  1102.     do
  1103.         putchar ( *--stackp );
  1104.     while ( stackp > de_stack );
  1105.  
  1106.     /*
  1107.      * Generate the new entry.
  1108.      */
  1109.     if ( (code=free_ent) < maxmaxcode ) {
  1110.         tab_prefixof(code) = (unsigned short)oldcode;
  1111.         tab_suffixof(code) = finchar;
  1112.         free_ent = code+1;
  1113.     } 
  1114.     /*
  1115.      * Remember previous code.
  1116.      */
  1117.     oldcode = incode;
  1118.     }
  1119.     fflush( stdout );
  1120.     if(ferror(stdout))
  1121.     writeerr();
  1122. }
  1123.  
  1124. /*****************************************************************
  1125.  * TAG( getcode )
  1126.  *
  1127.  * Read one code from the standard input.  If EOF, return -1.
  1128.  * Inputs:
  1129.  *     stdin
  1130.  * Outputs:
  1131.  *     code or -1 is returned.
  1132.  */
  1133.  
  1134. code_int
  1135. getcode() {
  1136.     /*
  1137.      * On the VAX, it is important to have the register declarations
  1138.      * in exactly the order given, or the asm will break.
  1139.      */
  1140.     register code_int code;
  1141.     static int offset = 0, size = 0;
  1142.     static char_type buf[BITS];
  1143.     register int r_off, bits;
  1144.     register char_type *bp = buf;
  1145.  
  1146.     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
  1147.     /*
  1148.      * If the next entry will be too big for the current code
  1149.      * size, then we must increase the size.  This implies reading
  1150.      * a new buffer full, too.
  1151.      */
  1152.     if ( free_ent > maxcode ) {
  1153.         n_bits++;
  1154.         if ( n_bits == maxbits )
  1155.         maxcode = maxmaxcode;    /* won't get any bigger now */
  1156.         else
  1157.         maxcode = MAXCODE(n_bits);
  1158.     }
  1159.     if ( clear_flg > 0) {
  1160.             maxcode = MAXCODE (n_bits = INIT_BITS);
  1161.         clear_flg = 0;
  1162.     }
  1163.     size = fread( buf, 1, n_bits, stdin );
  1164.     if ( size <= 0 )
  1165.         return -1;            /* end of file */
  1166.     offset = 0;
  1167.     /* Round size down to integral number of codes */
  1168.     size = (size << 3) - (n_bits - 1);
  1169.     }
  1170.     r_off = offset;
  1171.     bits = n_bits;
  1172. #ifdef vax
  1173.     asm( "extzv   r10,r9,(r8),r11" );
  1174. #else /* not a vax */
  1175.     /*
  1176.      * Get to the first byte.
  1177.      */
  1178.     bp += (r_off >> 3);
  1179.     r_off &= 7;
  1180.     /* Get first part (low order bits) */
  1181. #ifdef NO_UCHAR
  1182.     code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
  1183. #else
  1184.     code = (*bp++ >> r_off);
  1185. #endif /* NO_UCHAR */
  1186.     bits -= (8 - r_off);
  1187.     r_off = 8 - r_off;        /* now, offset into code word */
  1188.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  1189.     if ( bits >= 8 ) {
  1190. #ifdef NO_UCHAR
  1191.         code |= (*bp++ & 0xff) << r_off;
  1192. #else
  1193.         code |= *bp++ << r_off;
  1194. #endif /* NO_UCHAR */
  1195.         r_off += 8;
  1196.         bits -= 8;
  1197.     }
  1198.     /* high order bits. */
  1199.     code |= (*bp & rmask[bits]) << r_off;
  1200. #endif /* vax */
  1201.     offset += n_bits;
  1202.  
  1203.     return code;
  1204. }
  1205.  
  1206. char *
  1207. rindex(s, c)        /* For those who don't have it in libc.a */
  1208. register char *s, c;
  1209. {
  1210.     char *p;
  1211.     for (p = NULL; *s; s++)
  1212.         if (*s == c)
  1213.         p = s;
  1214.     return(p);
  1215. }
  1216.  
  1217. #ifdef DEBUG
  1218. printcodes()
  1219. {
  1220.     /*
  1221.      * Just print out codes from input file.  For debugging.
  1222.      */
  1223.     code_int code;
  1224.     int col = 0, bits;
  1225.  
  1226.     bits = n_bits = INIT_BITS;
  1227.     maxcode = MAXCODE(n_bits);
  1228.     free_ent = ((block_compress) ? FIRST : 256 );
  1229.     while ( ( code = getcode() ) >= 0 ) {
  1230.     if ( (code == CLEAR) && block_compress ) {
  1231.            free_ent = FIRST - 1;
  1232.            clear_flg = 1;
  1233.     }
  1234.     else if ( free_ent < maxmaxcode )
  1235.         free_ent++;
  1236.     if ( bits != n_bits ) {
  1237.         fprintf(stderr, "\nChange to %d bits\n", n_bits );
  1238.         bits = n_bits;
  1239.         col = 0;
  1240.     }
  1241.     fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
  1242.     }
  1243.     putc( '\n', stderr );
  1244.     exit( 0 );
  1245. }
  1246.  
  1247. code_int sorttab[1<<BITS];    /* sorted pointers into htab */
  1248.  
  1249. dump_tab()    /* dump string table */
  1250. {
  1251.     register int i, first;
  1252.     register ent;
  1253. #define STACK_SIZE    15000
  1254.     int stack_top = STACK_SIZE;
  1255.     register c;
  1256.  
  1257.     if(do_decomp == 0) {    /* compressing */
  1258.     register int flag = 1;
  1259.  
  1260.     for(i=0; i<hsize; i++) {    /* build sort pointers */
  1261.         if((long)htabof(i) >= 0) {
  1262.             sorttab[codetabof(i)] = i;
  1263.         }
  1264.     }
  1265.     first = block_compress ? FIRST : 256;
  1266.     for(i = first; i < free_ent; i++) {
  1267.         fprintf(stderr, "%5d: \"", i);
  1268.         de_stack[--stack_top] = '\n';
  1269.         de_stack[--stack_top] = '"';
  1270.         stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff, 
  1271.                                      stack_top);
  1272.         for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
  1273.             ent > 256;
  1274.             ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
  1275.             stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
  1276.                         stack_top);
  1277.         }
  1278.         stack_top = in_stack(ent, stack_top);
  1279.         fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
  1280.            stack_top = STACK_SIZE;
  1281.     }
  1282.    } else if(!debug) {    /* decompressing */
  1283.  
  1284.        for ( i = 0; i < free_ent; i++ ) {
  1285.        ent = i;
  1286.        c = tab_suffixof(ent);
  1287.        if ( isascii(c) && isprint(c) )
  1288.            fprintf( stderr, "%5d: %5d/'%c'  \"",
  1289.                ent, tab_prefixof(ent), c );
  1290.        else
  1291.            fprintf( stderr, "%5d: %5d/\\%03o \"",
  1292.                ent, tab_prefixof(ent), c );
  1293.        de_stack[--stack_top] = '\n';
  1294.        de_stack[--stack_top] = '"';
  1295.        for ( ; ent != NULL;
  1296.            ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
  1297.            stack_top = in_stack(tab_suffixof(ent), stack_top);
  1298.        }
  1299.        fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
  1300.        stack_top = STACK_SIZE;
  1301.        }
  1302.     }
  1303. }
  1304.  
  1305. int
  1306. in_stack(c, stack_top)
  1307.     register c, stack_top;
  1308. {
  1309.     if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
  1310.         de_stack[--stack_top] = c;
  1311.     } else {
  1312.         switch( c ) {
  1313.         case '\n': de_stack[--stack_top] = 'n'; break;
  1314.         case '\t': de_stack[--stack_top] = 't'; break;
  1315.         case '\b': de_stack[--stack_top] = 'b'; break;
  1316.         case '\f': de_stack[--stack_top] = 'f'; break;
  1317.         case '\r': de_stack[--stack_top] = 'r'; break;
  1318.         case '\\': de_stack[--stack_top] = '\\'; break;
  1319.         default:
  1320.          de_stack[--stack_top] = '0' + c % 8;
  1321.          de_stack[--stack_top] = '0' + (c / 8) % 8;
  1322.          de_stack[--stack_top] = '0' + c / 64;
  1323.          break;
  1324.         }
  1325.         de_stack[--stack_top] = '\\';
  1326.     }
  1327.     return stack_top;
  1328. }
  1329. #endif /* DEBUG */
  1330.  
  1331. writeerr()
  1332. {
  1333.     perror ( ofname );
  1334.     unlink ( ofname );
  1335.     exit ( 1 );
  1336. }
  1337.  
  1338. copystat(ifname, ofname)
  1339. char *ifname, *ofname;
  1340. {
  1341.     struct stat statbuf;
  1342.     int mode;
  1343.     time_t timep[2];
  1344.  
  1345.     fclose(stdout);
  1346.     if (stat(ifname, &statbuf)) {        /* Get stat on input file */
  1347.     perror(ifname);
  1348.     return;
  1349.     }
  1350.     if ((statbuf.st_mode & S_IFMT/*0170000*/) != S_IFREG/*0100000*/) {
  1351.     if(quiet)
  1352.             fprintf(stderr, "%s: ", ifname);
  1353.     fprintf(stderr, " -- not a regular file: unchanged");
  1354.     exit_stat = 1;
  1355.     perm_stat = 1;
  1356.     } else if (statbuf.st_nlink > 1) {
  1357.     if(quiet)
  1358.             fprintf(stderr, "%s: ", ifname);
  1359.     fprintf(stderr, " -- has %d other links: unchanged",
  1360.         statbuf.st_nlink - 1);
  1361.     exit_stat = 1;
  1362.     perm_stat = 1;
  1363.     } else if (exit_stat == 2 && (!force)) { /* No compression: remove file.Z */
  1364.     if(!quiet)
  1365.         fprintf(stderr, " -- file unchanged");
  1366.     } else {            /* ***** Successful Compression ***** */
  1367.     exit_stat = 0;
  1368.     mode = statbuf.st_mode & 07777;
  1369. #if 0
  1370.     if (chmod(ofname, mode))        /* Copy modes */
  1371.         perror(ofname);
  1372. #endif
  1373.     chown(ofname, statbuf.st_uid, statbuf.st_gid);    /* Copy ownership */
  1374.     timep[0] = statbuf.st_atime;
  1375.     timep[1] = statbuf.st_mtime;
  1376.     utime(ofname, timep);    /* Update last accessed and modified times */
  1377. #if 0
  1378.     if (unlink(ifname))    /* Remove input file */
  1379.         perror(ifname);
  1380. #else
  1381.     unlink(ifname);
  1382. #endif
  1383.     if(!quiet)
  1384.         fprintf(stderr, " -- replaced with %s", ofname);
  1385.     return;        /* Successful return */
  1386.     }
  1387.  
  1388.     /* Unsuccessful return -- one of the tests failed */
  1389.     if (unlink(ofname))
  1390.     perror(ofname);
  1391. }
  1392.  
  1393. void
  1394. onintr ( )
  1395. {
  1396.     if (!precious)
  1397.     unlink ( ofname );
  1398.     exit ( 1 );
  1399. }
  1400.  
  1401. void
  1402. oops ( )    /* wild pointer -- assume bad input */
  1403. {
  1404.     if ( do_decomp ) 
  1405.         fprintf ( stderr, "uncompress: corrupt input\n" );
  1406.     unlink ( ofname );
  1407.     exit ( 1 );
  1408. }
  1409.  
  1410. cl_block ()        /* table clear for block compress */
  1411. {
  1412.     register long int rat;
  1413.  
  1414.     checkpoint = in_count + CHECK_GAP;
  1415. #ifdef DEBUG
  1416.     if ( debug ) {
  1417.             fprintf ( stderr, "count: %ld, ratio: ", in_count );
  1418.              prratio ( stderr, in_count, bytes_out );
  1419.         fprintf ( stderr, "\n");
  1420.     }
  1421. #endif /* DEBUG */
  1422.  
  1423.     if(in_count > 0x007fffff) {    /* shift will overflow */
  1424.     rat = bytes_out >> 8;
  1425.     if(rat == 0) {        /* Don't divide by zero */
  1426.         rat = 0x7fffffff;
  1427.     } else {
  1428.         rat = in_count / rat;
  1429.     }
  1430.     } else {
  1431.     rat = (in_count << 8) / bytes_out;    /* 8 fractional bits */
  1432.     }
  1433.     if ( rat > ratio ) {
  1434.     ratio = rat;
  1435.     } else {
  1436.     ratio = 0;
  1437. #ifdef DEBUG
  1438.     if(verbose)
  1439.         dump_tab();    /* dump string table */
  1440. #endif
  1441.      cl_hash ( (count_int) hsize );
  1442.     free_ent = FIRST;
  1443.     clear_flg = 1;
  1444.     output ( (code_int) CLEAR );
  1445. #ifdef DEBUG
  1446.     if(debug)
  1447.             fprintf ( stderr, "clear\n" );
  1448. #endif /* DEBUG */
  1449.     }
  1450. }
  1451.  
  1452. cl_hash(hsize)        /* reset code table */
  1453.     register count_int hsize;
  1454. {
  1455. #ifndef XENIX_16    /* Normal machine */
  1456.     register count_int *htab_p = htab+hsize;
  1457. #else
  1458.     register j;
  1459.     register long k = hsize;
  1460.     register count_int *htab_p;
  1461. #endif
  1462.     register long i;
  1463.     register long m1 = -1;
  1464.  
  1465. #ifdef XENIX_16
  1466.     for(j=0; j<=8 && k>=0; j++,k-=8192) {
  1467.     i = 8192;
  1468.     if(k < 8192) {
  1469.         i = k;
  1470.     }
  1471.     htab_p = &(htab[j][i]);
  1472.     i -= 16;
  1473.     if(i > 0) {
  1474. #else
  1475.     i = hsize - 16;
  1476. #endif
  1477.      do {                /* might use Sys V memset(3) here */
  1478.         *(htab_p-16) = m1;
  1479.         *(htab_p-15) = m1;
  1480.         *(htab_p-14) = m1;
  1481.         *(htab_p-13) = m1;
  1482.         *(htab_p-12) = m1;
  1483.         *(htab_p-11) = m1;
  1484.         *(htab_p-10) = m1;
  1485.         *(htab_p-9) = m1;
  1486.         *(htab_p-8) = m1;
  1487.         *(htab_p-7) = m1;
  1488.         *(htab_p-6) = m1;
  1489.         *(htab_p-5) = m1;
  1490.         *(htab_p-4) = m1;
  1491.         *(htab_p-3) = m1;
  1492.         *(htab_p-2) = m1;
  1493.         *(htab_p-1) = m1;
  1494.         htab_p -= 16;
  1495.     } while ((i -= 16) >= 0);
  1496. #ifdef XENIX_16
  1497.     }
  1498.     }
  1499. #endif
  1500.         for ( i += 16; i > 0; i-- )
  1501.         *--htab_p = m1;
  1502. }
  1503.  
  1504. prratio(stream, num, den)
  1505. FILE *stream;
  1506. long int num, den;
  1507. {
  1508.     register int q;            /* Doesn't need to be long */
  1509.  
  1510.     if(num > 214748L) {        /* 2147483647/10000 */
  1511.         q = num / (den / 10000L);
  1512.     } else {
  1513.         q = 10000L * num / den;        /* Long calculations, though */
  1514.     }
  1515.     if (q < 0) {
  1516.         putc('-', stream);
  1517.         q = -q;
  1518.     }
  1519.     fprintf(stream, "%d.%02d%%", q / 100, q % 100);
  1520. }
  1521.  
  1522. version()
  1523. {
  1524.     fprintf(stderr, "%s, Berkeley 5.12 6/1/90\n", rcs_ident);
  1525.     fprintf(stderr, "Options: ");
  1526. #ifdef vax
  1527.     fprintf(stderr, "vax, ");
  1528. #endif
  1529. #ifdef NO_UCHAR
  1530.     fprintf(stderr, "NO_UCHAR, ");
  1531. #endif
  1532. #ifdef SIGNED_COMPARE_SLOW
  1533.     fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
  1534. #endif
  1535. #ifdef XENIX_16
  1536.     fprintf(stderr, "XENIX_16, ");
  1537. #endif
  1538. #ifdef COMPATIBLE
  1539.     fprintf(stderr, "COMPATIBLE, ");
  1540. #endif
  1541. #ifdef DEBUG
  1542.     fprintf(stderr, "DEBUG, ");
  1543. #endif
  1544. #ifdef BSD4_2
  1545.     fprintf(stderr, "BSD4_2, ");
  1546. #endif
  1547.     fprintf(stderr, "BITS = %d\n", BITS);
  1548. }
  1549.