home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume20 / compress / part01 / compress.c next >
Encoding:
C/C++ Source or Header  |  1991-06-26  |  41.6 KB  |  1,632 lines

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