home *** CD-ROM | disk | FTP | other *** search
/ The Fred Fish Collection 1.5 / ffcollection-1-5-1992-11.iso / ff_progs / compress / compress.lzh / COMPRESS / COMPRESS.C < prev    next >
Encoding:
C/C++ Source or Header  |  1991-08-16  |  39.6 KB  |  1,554 lines

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