home *** CD-ROM | disk | FTP | other *** search
/ Boston 2 / boston-2.iso / DOS / HILFEN / SYSTEM / RECONFI2 / COMPRESS.C < prev    next >
C/C++ Source or Header  |  1993-12-01  |  55KB  |  1,719 lines

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