home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 9 Archive / 09-Archive.zip / COMPR412.ZIP / compress.c next >
C/C++ Source or Header  |  1992-07-18  |  46KB  |  1,685 lines

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