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