home *** CD-ROM | disk | FTP | other *** search
/ Usenet 1994 January / usenetsourcesnewsgroupsinfomagicjanuary1994.iso / sources / misc / volume6 / compress.cms / compress.c
Encoding:
C/C++ Source or Header  |  1989-04-08  |  40.8 KB  |  1,569 lines

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