Add some Processor specific instruction selections
[libfirm] / ir / be / test / compress95.c
1 /*
2  * Compress - data compression program
3  */
4 #define min(a,b)        ((a>b) ? b : a)
5
6
7 /*
8  * Set USERMEM to the maximum amount of physical user memory available
9  * in bytes.  USERMEM is used to determine the maximum BITS that can be used
10  * for compression.
11  *
12  * SACREDMEM is the amount of physical memory saved for others; compress
13  * will hog the rest.
14  */
15 /* For SPEC95 use, SACREDMEM automatically set to 0.
16         Jeff Reilly, 1/15/95                            */
17
18 #define SACREDMEM       0
19
20 /* For SPEC95 use, USERMEM automatically set to 450000.
21         Jeff Reilly, 1/15/95                            */
22 # define USERMEM        450000  /* default user memory */
23
24 #ifdef interdata                /* (Perkin-Elmer) */
25 #define SIGNED_COMPARE_SLOW     /* signed compare is slower than unsigned */
26 #endif
27
28 /* For SPEC95 use, PBITS and BITS automatically set to 16.
29         Jeff Reilyy, 1/15/95                            */
30 #define PBITS   16
31 #define BITS 16
32 #define HSIZE   69001           /* 95% occupancy */
33
34
35 /*
36  * a code_int must be able to hold 2**BITS values of type int, and also -1
37  */
38 #if BITS > 15
39 typedef long int        code_int;
40 #else
41 typedef int             code_int;
42 #endif
43
44 #ifdef SIGNED_COMPARE_SLOW
45 typedef unsigned long int count_int;
46 typedef unsigned short int count_short;
47 #else
48 typedef long int          count_int;
49 #endif
50
51 #ifdef NO_UCHAR
52  typedef char   char_type;
53 #else
54  typedef        unsigned char   char_type;
55 #endif /* UCHAR */
56 char_type magic_header[] = { "\037\235" };      /* 1F 9D */
57
58 /* Defines for third byte of header */
59 #define BIT_MASK        0x1f
60 #define BLOCK_MASK      0x80
61 /* Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
62    a fourth header byte (for expansion).
63 */
64 #define INIT_BITS 9                     /* initial number of bits/code */
65
66 /* SPEC95, Original comments left  - Jeff Reilly, 1/18/95 */
67 /*
68  * compress.c - File compression ala IEEE Computer, June 1984.
69  *
70  * Authors:     Spencer W. Thomas       (decvax!harpo!utah-cs!utah-gr!thomas)
71  *              Jim McKie               (decvax!mcvax!jim)
72  *              Steve Davies            (decvax!vax135!petsd!peora!srd)
73  *              Ken Turkowski           (decvax!decwrl!turtlevax!ken)
74  *              James A. Woods          (decvax!ihnp4!ames!jaw)
75  *              Joe Orost               (decvax!vax135!petsd!joe)
76  *
77  * $Header$
78  * $Log$
79  * Revision 1.3  90/07/18  20:22:34  mips
80  * a few small changes for VMS, all of the ifdef VAX is gone.
81  *
82  * Revision 1.1  90/07/12  10:58:29  10:58:29  root ()
83  * Initial revision
84  *
85  * Revision 4.0  85/07/30  12:50:00  joe
86  * Removed ferror() calls in output routine on every output except first.
87  * Prepared for release to the world.
88  *
89  * Revision 3.6  85/07/04  01:22:21  joe
90  * Remove much wasted storage by overlaying hash table with the tables
91  * used by decompress: tab_suffix[1<<BITS], stack[8000].  Updated USERMEM
92  * computations.  Fixed dump_tab() DEBUG routine.
93  *
94  * Revision 3.5  85/06/30  20:47:21  jaw
95  * Change hash function to use exclusive-or.  Rip out hash cache.  These
96  * speedups render the megamemory version defunct, for now.  Make decoder
97  * stack global.  Parts of the RCS trunks 2.7, 2.6, and 2.1 no longer apply.
98  *
99  * Revision 3.4  85/06/27  12:00:00  ken
100  * Get rid of all floating-point calculations by doing all compression ratio
101  * calculations in fixed point.
102  *
103  * Revision 3.3  85/06/24  21:53:24  joe
104  * Incorporate portability suggestion for M_XENIX.  Got rid of text on #else
105  * and #endif lines.  Cleaned up #ifdefs for vax and interdata.
106  *
107  * Revision 3.2  85/06/06  21:53:24  jaw
108  * Incorporate portability suggestions for Z8000, IBM PC/XT from mailing list.
109  * Default to "quiet" output (no compression statistics).
110  *
111  * Revision 3.1  85/05/12  18:56:13  jaw
112  * Integrate decompress() stack speedups (from early pointer mods by McKie).
113  * Repair multi-file USERMEM gaffe.  Unify 'force' flags to mimic semantics
114  * of SVR2 'pack'.  Streamline block-compress table clear logic.  Increase
115  * output byte count by magic number size.
116  *
117  * Revision 3.0   84/11/27  11:50:00  petsd!joe
118  * Set HSIZE depending on BITS.  Set BITS depending on USERMEM.  Unrolled
119  * loops in clear routines.  Added "-C" flag for 2.0 compatibility.  Used
120  * unsigned compares on Perkin-Elmer.  Fixed foreground check.
121  *
122  * Revision 2.7   84/11/16  19:35:39  ames!jaw
123  * Cache common hash codes based on input statistics; this improves
124  * performance for low-density raster images.  Pass on #ifdef bundle
125  * from Turkowski.
126  *
127  * Revision 2.6   84/11/05  19:18:21  ames!jaw
128  * Vary size of hash tables to reduce time for small files.
129  * Tune PDP-11 hash function.
130  *
131  * Revision 2.5   84/10/30  20:15:14  ames!jaw
132  * Junk chaining; replace with the simpler (and, on the VAX, faster)
133  * double hashing, discussed within.  Make block compression standard.
134  *
135  * Revision 2.4   84/10/16  11:11:11  ames!jaw
136  * Introduce adaptive reset for block compression, to boost the rate
137  * another several percent.  (See mailing list notes.)
138  *
139  * Revision 2.3   84/09/22  22:00:00  petsd!joe
140  * Implemented "-B" block compress.  Implemented REVERSE sorting of tab_next.
141  * Bug fix for last bits.  Changed fwrite to putchar loop everywhere.
142  *
143  * Revision 2.2   84/09/18  14:12:21  ames!jaw
144  * Fold in news changes, small machine typedef from thomas,
145  * #ifdef interdata from joe.
146  *
147  * Revision 2.1   84/09/10  12:34:56  ames!jaw
148  * Configured fast table lookup for 32-bit machines.
149  * This cuts user time in half for b <= FBITS, and is useful for news batching
150  * from VAX to PDP sites.  Also sped up decompress() [fwrite->putc] and
151  * added signal catcher [plus beef in writeerr()] to delete effluvia.
152  *
153  * Revision 2.0   84/08/28  22:00:00  petsd!joe
154  * Add check for foreground before prompting user.  Insert maxbits into
155  * compressed file.  Force file being uncompressed to end with ".Z".
156  * Added "-c" flag and "zcat".  Prepared for release.
157  *
158  * Revision 1.10  84/08/24  18:28:00  turtlevax!ken
159  * Will only compress regular files (no directories), added a magic number
160  * header (plus an undocumented -n flag to handle old files without headers),
161  * added -f flag to force overwriting of possibly existing destination file,
162  * otherwise the user is prompted for a response.  Will tack on a .Z to a
163  * filename if it doesn't have one when decompressing.  Will only replace
164  * file if it was compressed.
165  *
166  * Revision 1.9  84/08/16  17:28:00  turtlevax!ken
167  * Removed scanargs(), getopt(), added .Z extension and unlimited number of
168  * filenames to compress.  Flags may be clustered (-Ddvb12) or separated
169  * (-D -d -v -b 12), or combination thereof.  Modes and other status is
170  * copied with copystat().  -O bug for 4.2 seems to have disappeared with
171  * 1.8.
172  *
173  * Revision 1.8  84/08/09  23:15:00  joe
174  * Made it compatible with vax version, installed jim's fixes/enhancements
175  *
176  * Revision 1.6  84/08/01  22:08:00  joe
177  * Sped up algorithm significantly by sorting the compress chain.
178  *
179  * Revision 1.5  84/07/13  13:11:00  srd
180  * Added C version of vax asm routines.  Changed structure to arrays to
181  * save much memory.  Do unsigned compares where possible (faster on
182  * Perkin-Elmer)
183  *
184  * Revision 1.4  84/07/05  03:11:11  thomas
185  * Clean up the code a little and lint it.  (Lint complains about all
186  * the regs used in the asm, but I'm not going to "fix" this.)
187  *
188  * Revision 1.3  84/07/05  02:06:54  thomas
189  * Minor fixes.
190  *
191  * Revision 1.2  84/07/05  00:27:27  thomas
192  * Add variable bit length output.
193  *
194  */
195 static char rcs_ident[] = "$Header$";
196
197 #include <stdio.h>
198 #include <ctype.h>
199 #ifdef VMS
200 #include <types.h>
201 #include <stat.h>
202 #define unlink delete
203 #else
204 #include <sys/types.h>
205 #include <sys/stat.h>
206 #endif  /* VMS  */
207
208 #define ARGVAL() (*++(*argv) || (--argc && *++argv))
209
210 int n_bits;                             /* number of bits/code */
211 int maxbits = BITS;                     /* user settable max # bits/code */
212 code_int maxcode;                       /* maximum code, given n_bits */
213 code_int maxmaxcode = 1 << BITS;        /* should NEVER generate this code */
214 #ifdef COMPATIBLE               /* But wrong! */
215 # define MAXCODE(n_bits)        (1 << (n_bits) - 1)
216 #else
217 # define MAXCODE(n_bits)        ((1 << (n_bits)) - 1)
218 #endif /* COMPATIBLE */
219
220 #ifdef XENIX_16
221 count_int htab0[8192];
222 count_int htab1[8192];
223 count_int htab2[8192];
224 count_int htab3[8192];
225 count_int htab4[8192];
226 count_int htab5[8192];
227 count_int htab6[8192];
228 count_int htab7[8192];
229 count_int htab8[HSIZE-65536];
230 count_int * htab[9] = {
231         htab0, htab1, htab2, htab3, htab4, htab5, htab6, htab7, htab8 };
232
233 #define htabof(i)       (htab[(i) >> 13][(i) & 0x1fff])
234 unsigned short code0tab[16384];
235 unsigned short code1tab[16384];
236 unsigned short code2tab[16384];
237 unsigned short code3tab[16384];
238 unsigned short code4tab[16384];
239 unsigned short * codetab[5] = {
240         code0tab, code1tab, code2tab, code3tab, code4tab };
241
242 #define codetabof(i)    (codetab[(i) >> 14][(i) & 0x3fff])
243
244 #else   /* Normal machine */
245 count_int htab [HSIZE];
246 unsigned short codetab [HSIZE];
247 #define htabof(i)       htab[i]
248 #define codetabof(i)    codetab[i]
249 #endif  /* XENIX_16 */
250 code_int hsize = HSIZE;                 /* for dynamic table sizing */
251 count_int fsize;
252
253 /*
254  * To save much memory, we overlay the table used by compress() with those
255  * used by decompress().  The tab_prefix table is the same size and type
256  * as the codetab.  The tab_suffix table needs 2**BITS characters.  We
257  * get this from the beginning of htab.  The output stack uses the rest
258  * of htab, and contains characters.  There is plenty of room for any
259  * possible stack (stack used to be 8000 characters).
260  */
261
262 #define tab_prefixof(i) codetabof(i)
263 #ifdef XENIX_16
264 # define tab_suffixof(i)        ((char_type *)htab[(i)>>15])[(i) & 0x7fff]
265 # define de_stack               ((char_type *)(htab2))
266 #else   /* Normal machine */
267 # define tab_suffixof(i)        ((char_type *)(htab))[i]
268 # define de_stack               ((char_type *)&tab_suffixof(1<<BITS))
269 #endif  /* XENIX_16 */
270
271 code_int free_ent = 0;                  /* first unused entry */
272 int exit_stat = 0;
273
274 code_int getcode();
275
276 int nomagic = 0;        /* Use a 3-byte magic number header, unless old file */
277 int zcat_flg = 0;       /* Write output on stdout, suppress messages */
278 int quiet = 1;          /* don't tell me about compression */
279
280 /*
281  * block compression parameters -- after all codes are used up,
282  * and compression rate changes, start over.
283  */
284 int block_compress = BLOCK_MASK;
285 int clear_flg = 0;
286 long int ratio = 0;
287 #define CHECK_GAP 10000 /* ratio check interval */
288 count_int checkpoint = CHECK_GAP;
289 /*
290  * the next two codes should not be changed lightly, as they must not
291  * lie within the contiguous general code space.
292  */
293 #define FIRST   257     /* first free entry */
294 #define CLEAR   256     /* table clear output code */
295
296 int force = 0;
297 char ofname [100];
298 #ifdef DEBUG
299 int verbose = 0;
300 #endif /* DEBUG */
301
302 int do_decomp = 0;
303
304
305 int InCnt;
306 unsigned char *InBuff;
307 unsigned char *OutBuff;
308
309 /*****************************************************************
310  * TAG( main )
311  *
312  * Algorithm from "A Technique for High Performance Data Compression",
313  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
314  *
315  * Usage: compress [-dfvc] [-b bits] [file ...]
316  * Inputs:
317  *      -d:         If given, decompression is done instead.
318  *
319  *      -c:         Write output on stdout, don't remove original.
320  *
321  *      -b:         Parameter limits the max number of bits/code.
322  *
323  *      -f:         Forces output file to be generated, even if one already
324  *                  exists, and even if no space is saved by compressing.
325  *                  If -f is not used, the user will be prompted if stdin is
326  *                  a tty, otherwise, the output file will not be overwritten.
327  *
328  *      -v:         Write compression statistics
329  *
330  *      file ...:   Files to be compressed.  If none specified, stdin
331  *                  is used.
332  * Outputs:
333  *      file.Z:     Compressed form of file with same mode, owner, and utimes
334  *      or stdout   (if stdin used as input)
335  *
336  * Assumptions:
337  *      When filenames are given, replaces with the compressed version
338  *      (.Z suffix) only if the file decreases in size.
339  * Algorithm:
340  *      Modified Lempel-Ziv method (LZW).  Basically finds common
341  * substrings and replaces them with a variable size code.  This is
342  * deterministic, and can be done on the fly.  Thus, the decompression
343  * procedure needs no input table, but tracks the way the table was built.
344  *
345  *
346  * Changed from main to spec_select_action,
347  *      Jeff Reilly -   1/15/95 SPEC
348  */
349
350 spec_select_action(char* from_buf, int from_count, int action, char* to_buf)
351 {
352     char *cp, *rindex(), *malloc();
353     struct stat statbuf;
354 #ifdef SYSV
355     void onintr(), oops();
356 #else
357     int onintr(), oops();
358 #endif  /* SYSV */
359
360
361
362 #ifdef COMPATIBLE
363     nomagic = 1;        /* Original didn't have a magic number */
364 #endif /* COMPATIBLE */
365
366
367     if(maxbits < INIT_BITS) maxbits = INIT_BITS;
368     if (maxbits > BITS) maxbits = BITS;
369     maxmaxcode = 1 << maxbits;
370
371     InCnt = from_count;
372     InBuff = (unsigned char *)from_buf;
373     OutBuff = (unsigned char *)to_buf;
374     do_decomp = action;
375
376         if (do_decomp == 0) {
377                 compress();
378 #ifdef DEBUG
379                 if(verbose)             dump_tab();
380 #endif /* DEBUG */
381         } else {
382             /* Check the magic number */
383             if (nomagic == 0) {
384                 if ((getbyte() != (magic_header[0] & 0xFF))
385                  || (getbyte() != (magic_header[1] & 0xFF))) {
386                     fprintf(stderr, "stdin: not in compressed format\n");
387                     exit(1);
388                 }
389                 maxbits = getbyte();    /* set -b from file */
390                 block_compress = maxbits & BLOCK_MASK;
391                 maxbits &= BIT_MASK;
392                 maxmaxcode = 1 << maxbits;
393                 fsize = 100000;         /* assume stdin large for USERMEM */
394                 if(maxbits > BITS) {
395                         fprintf(stderr,
396                         "stdin: compressed with %d bits, can only handle %d bits\n",
397                         maxbits, BITS);
398                         exit(1);
399                 }
400             }
401 #ifndef DEBUG
402             decompress();
403 #else
404             if (debug == 0)     decompress();
405             else                printcodes();
406             if (verbose)        dump_tab();
407 #endif /* DEBUG */
408         }
409
410     return( OutBuff - (unsigned char *)to_buf );
411 }
412
413 static int offset;
414 long int in_count = 1;                  /* length of input */
415 long int bytes_out;                     /* length of compressed output */
416 long int out_count = 0;                 /* # of codes output (for debugging) */
417
418 /*
419  * compress (Originally: stdin to stdout -- Changed by SPEC to: memory to memory)
420  *
421  * Algorithm:  use open addressing double hashing (no chaining) on the
422  * prefix code / next character combination.  We do a variant of Knuth's
423  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
424  * secondary probe.  Here, the modular division first probe is gives way
425  * to a faster exclusive-or manipulation.  Also do block compression with
426  * an adaptive reset, whereby the code table is cleared when the compression
427  * ratio decreases, but after the table fills.  The variable-length output
428  * codes are re-sized at this point, and a special CLEAR code is generated
429  * for the decompressor.  Late addition:  construct the table according to
430  * file size for noticeable speed improvement on small files.  Please direct
431  * questions about this implementation to ames!jaw.
432  */
433
434 compress() {
435     register long fcode;
436     register code_int i = 0;
437     register int c;
438     register code_int ent;
439 #ifdef XENIX_16
440     register code_int disp;
441 #else   /* Normal machine */
442     register int disp;
443 #endif
444     register code_int hsize_reg;
445     register int hshift;
446
447 #ifndef COMPATIBLE
448     if (nomagic == 0) {
449         putbyte(magic_header[0]); putbyte(magic_header[1]);
450         putbyte((char)(maxbits | block_compress));
451     }
452 #endif /* COMPATIBLE */
453
454     offset = 0;
455     bytes_out = 3;              /* includes 3-byte header mojo */
456     out_count = 0;
457     clear_flg = 0;
458     ratio = 0;
459     in_count = 1;
460     checkpoint = CHECK_GAP;
461     maxcode = MAXCODE(n_bits = INIT_BITS);
462     free_ent = ((block_compress) ? FIRST : 256 );
463
464     ent = getbyte ();
465
466     hshift = 0;
467     for ( fcode = (long) hsize;  fcode < 65536L; fcode *= 2L )
468         hshift++;
469     hshift = 8 - hshift;                /* set hash code range bound */
470
471     hsize_reg = hsize;
472     cl_hash( (count_int) hsize_reg);            /* clear hash table */
473
474 #ifdef SIGNED_COMPARE_SLOW
475     while ( (c = getbyte()) != (unsigned) EOF ) {
476 #else
477     while ( (c = getbyte()) != EOF ) {
478 #endif
479         in_count++;
480         fcode = (long) (((long) c << maxbits) + ent);
481         i = ((c << hshift) ^ ent);      /* xor hashing */
482
483         if ( htabof (i) == fcode ) {
484             ent = codetabof (i);
485             continue;
486         } else if ( (long)htabof (i) < 0 )      /* empty slot */
487             goto nomatch;
488         disp = hsize_reg - i;           /* secondary hash (after G. Knott) */
489         if ( i == 0 )
490             disp = 1;
491 probe:
492         if ( (i -= disp) < 0 )
493             i += hsize_reg;
494
495         if ( htabof (i) == fcode ) {
496             ent = codetabof (i);
497             continue;
498         }
499         if ( (long)htabof (i) > 0 )
500             goto probe;
501 nomatch:
502         output ( (code_int) ent );
503         out_count++;
504         ent = c;
505 #ifdef SIGNED_COMPARE_SLOW
506         if ( (unsigned) free_ent < (unsigned) maxmaxcode) {
507 #else
508         if ( free_ent < maxmaxcode ) {
509 #endif
510             codetabof (i) = free_ent++; /* code -> hashtable */
511             htabof (i) = fcode;
512         }
513         else if ( (count_int)in_count >= checkpoint && block_compress )
514             cl_block ();
515     }
516     /*
517      * Put out the final code.
518      */
519     output( (code_int)ent );
520     out_count++;
521     output( (code_int)-1 );
522
523     /*
524      * Print out stats on stderr
525      */
526     if(zcat_flg == 0 && !quiet) {
527 #ifdef DEBUG
528         fprintf( stderr,
529                 "%ld chars in, %ld codes (%ld bytes) out, compression factor: ",
530                 in_count, out_count, bytes_out );
531         prratio( stderr, in_count, bytes_out );
532         fprintf( stderr, "\n");
533         fprintf( stderr, "\tCompression as in compact: " );
534         prratio( stderr, in_count-bytes_out, in_count );
535         fprintf( stderr, "\n");
536         fprintf( stderr, "\tLargest code (of last block) was %d (%d bits)\n",
537                 free_ent - 1, n_bits );
538 #else /* !DEBUG */
539         fprintf( stderr, "Compression: " );
540         prratio( stderr, in_count-bytes_out, in_count );
541 #endif /* DEBUG */
542     }
543     if(bytes_out > in_count)    /* exit(2) if no savings */
544         exit_stat = 2;
545     return;
546 }
547
548 /*****************************************************************
549  * TAG( output )
550  *
551  * Output the given code.
552  * Inputs:
553  *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
554  *              that n_bits =< (long)wordsize - 1.
555  * Outputs:
556  *      Outputs code to the file.
557  * Assumptions:
558  *      Chars are 8 bits long.
559  * Algorithm:
560  *      Maintain a BITS character long buffer (so that 8 codes will
561  * fit in it exactly).  Use the VAX insv instruction to insert each
562  * code in turn.  When the buffer fills up empty it and start over.
563  */
564
565 static char buf[BITS];
566
567 char_type lmask[9] = {0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
568 char_type rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
569
570 output( code )
571 code_int  code;
572 {
573 #ifdef DEBUG
574     static int col = 0;
575 #endif /* DEBUG */
576
577     /*
578      * On the VAX, it is important to have the register declarations
579      * in exactly the order given, or the asm will break.
580      */
581     register int r_off = offset, bits= n_bits;
582     register char * bp = buf;
583
584 #ifdef DEBUG
585         if ( verbose )
586             fprintf( stderr, "%5d%c", code,
587                     (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
588 #endif /* DEBUG */
589     if ( code >= 0 ) {
590 /*
591  * byte/bit numbering on the VAX is simulated by the following code
592  */
593         /*
594          * Get to the first byte.
595          */
596         bp += (r_off >> 3);
597         r_off &= 7;
598         /*
599          * Since code is always >= 8 bits, only need to mask the first
600          * hunk on the left.
601          */
602         *bp = (*bp & rmask[r_off]) | (code << r_off) & lmask[r_off];
603         bp++;
604         bits -= (8 - r_off);
605         code >>= 8 - r_off;
606         /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
607         if ( bits >= 8 ) {
608             *bp++ = code;
609             code >>= 8;
610             bits -= 8;
611         }
612         /* Last bits. */
613         if(bits)
614             *bp = code;
615         offset += n_bits;
616         if ( offset == (n_bits << 3) ) {
617             bp = buf;
618             bits = n_bits;
619             bytes_out += bits;
620             do
621                 putbyte(*bp++);
622             while(--bits);
623             offset = 0;
624         }
625
626         /*
627          * If the next entry is going to be too big for the code size,
628          * then increase it, if possible.
629          */
630         if ( free_ent > maxcode || (clear_flg > 0))
631         {
632             /*
633              * Write the whole buffer, because the input side won't
634              * discover the size increase until after it has read it.
635              */
636             if ( offset > 0 ) {
637                 writebytes( buf, n_bits );
638                 bytes_out += n_bits;
639             }
640             offset = 0;
641
642             if ( clear_flg ) {
643                 maxcode = MAXCODE (n_bits = INIT_BITS);
644                 clear_flg = 0;
645             }
646             else {
647                 n_bits++;
648                 if ( n_bits == maxbits )
649                     maxcode = maxmaxcode;
650                 else
651                     maxcode = MAXCODE(n_bits);
652             }
653 #ifdef DEBUG
654             if ( debug ) {
655                 fprintf( stderr, "\nChange to %d bits\n", n_bits );
656                 col = 0;
657             }
658 #endif /* DEBUG */
659         }
660     } else {
661         /*
662          * At EOF, write the rest of the buffer.
663          */
664         if ( offset > 0 )
665             writebytes( buf, ((offset + 7) / 8) );
666         bytes_out += (offset + 7) / 8;
667         offset = 0;
668 #ifdef DEBUG
669         if ( verbose )
670             fprintf( stderr, "\n" );
671 #endif /* DEBUG */
672     }
673 }
674
675 /*
676  * Decompress stdin to stdout.  This routine adapts to the codes in the
677  * file building the "string" table on-the-fly; requiring no table to
678  * be stored in the compressed file.  The tables used herein are shared
679  * with those of the compress() routine.  See the definitions above.
680  */
681
682 decompress() {
683     register char_type *stackp;
684     register int finchar;
685     register code_int code, oldcode, incode;
686
687     /*
688      * As above, initialize the first 256 entries in the table.
689      */
690     maxcode = MAXCODE(n_bits = INIT_BITS);
691     for ( code = 255; code >= 0; code-- ) {
692         tab_prefixof(code) = 0;
693         tab_suffixof(code) = (char_type)code;
694     }
695     free_ent = ((block_compress) ? FIRST : 256 );
696
697     finchar = oldcode = getcode();
698     if(oldcode == -1)   /* EOF already? */
699         return;                 /* Get out of here */
700     putbyte( (char)finchar );           /* first code must be 8 bits = char */
701     stackp = de_stack;
702
703     while ( (code = getcode()) > -1 ) {
704
705         if ( (code == CLEAR) && block_compress ) {
706             for ( code = 255; code >= 0; code-- )
707                 tab_prefixof(code) = 0;
708             clear_flg = 1;
709             free_ent = FIRST - 1;
710             if ( (code = getcode ()) == -1 )    /* O, untimely death! */
711                 break;
712         }
713         incode = code;
714         /*
715          * Special case for KwKwK string.
716          */
717         if ( code >= free_ent ) {
718             *stackp++ = finchar;
719             code = oldcode;
720         }
721
722         /*
723          * Generate output characters in reverse order
724          */
725 #ifdef SIGNED_COMPARE_SLOW
726         while ( ((unsigned long)code) >= ((unsigned long)256) ) {
727 #else
728         while ( code >= 256 ) {
729 #endif
730             *stackp++ = tab_suffixof(code);
731             code = tab_prefixof(code);
732         }
733         *stackp++ = finchar = tab_suffixof(code);
734
735         /*
736          * And put them out in forward order
737          */
738         do
739             putbyte ( *--stackp );
740         while ( stackp > de_stack );
741
742         /*
743          * Generate the new entry.
744          */
745         if ( (code=free_ent) < maxmaxcode ) {
746             tab_prefixof(code) = (unsigned short)oldcode;
747             tab_suffixof(code) = finchar;
748             free_ent = code+1;
749         }
750         /*
751          * Remember previous code.
752          */
753         oldcode = incode;
754     }
755 }
756
757 /*****************************************************************
758  * TAG( getcode )
759  *
760  * Read one code from the standard input.  If EOF, return -1.
761  * Inputs:
762  *      stdin
763  * Outputs:
764  *      code or -1 is returned.
765  */
766
767 code_int
768 getcode() {
769     /*
770      * On the VAX, it is important to have the register declarations
771      * in exactly the order given, or the asm will break.
772      */
773     register code_int code;
774     static int offset = 0, size = 0;
775     static char_type buf[BITS];
776     register int r_off, bits;
777     register char_type *bp = buf;
778
779     if ( clear_flg > 0 || offset >= size || free_ent > maxcode ) {
780         /*
781          * If the next entry will be too big for the current code
782          * size, then we must increase the size.  This implies reading
783          * a new buffer full, too.
784          */
785         if ( free_ent > maxcode ) {
786             n_bits++;
787             if ( n_bits == maxbits )
788                 maxcode = maxmaxcode;   /* won't get any bigger now */
789             else
790                 maxcode = MAXCODE(n_bits);
791         }
792         if ( clear_flg > 0) {
793             maxcode = MAXCODE (n_bits = INIT_BITS);
794             clear_flg = 0;
795         }
796         size = readbytes( buf, n_bits );
797         if ( size <= 0 )
798             return -1;                  /* end of file */
799         offset = 0;
800         /* Round size down to integral number of codes */
801         size = (size << 3) - (n_bits - 1);
802     }
803     r_off = offset;
804     bits = n_bits;
805         /*
806          * Get to the first byte.
807          */
808         bp += (r_off >> 3);
809         r_off &= 7;
810         /* Get first part (low order bits) */
811 #ifdef NO_UCHAR
812         code = ((*bp++ >> r_off) & rmask[8 - r_off]) & 0xff;
813 #else
814         code = (*bp++ >> r_off);
815 #endif /* NO_UCHAR */
816         bits -= (8 - r_off);
817         r_off = 8 - r_off;              /* now, offset into code word */
818         /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
819         if ( bits >= 8 ) {
820 #ifdef NO_UCHAR
821             code |= (*bp++ & 0xff) << r_off;
822 #else
823             code |= *bp++ << r_off;
824 #endif /* NO_UCHAR */
825             r_off += 8;
826             bits -= 8;
827         }
828         /* high order bits. */
829         code |= (*bp & rmask[bits]) << r_off;
830     offset += n_bits;
831
832     return code;
833 }
834
835 char *
836 rindex(s, c)            /* For those who don't have it in libc.a */
837 register char *s, c;
838 {
839         char *p;
840         for (p = NULL; *s; s++)
841             if (*s == c)
842                 p = s;
843         return(p);
844 }
845
846 #ifdef DEBUG
847 printcodes()
848 {
849     /*
850      * Just print out codes from input file.  For debugging.
851      */
852     code_int code;
853     int col = 0, bits;
854
855     bits = n_bits = INIT_BITS;
856     maxcode = MAXCODE(n_bits);
857     free_ent = ((block_compress) ? FIRST : 256 );
858     while ( ( code = getcode() ) >= 0 ) {
859         if ( (code == CLEAR) && block_compress ) {
860             free_ent = FIRST - 1;
861             clear_flg = 1;
862         }
863         else if ( free_ent < maxmaxcode )
864             free_ent++;
865         if ( bits != n_bits ) {
866             fprintf(stderr, "\nChange to %d bits\n", n_bits );
867             bits = n_bits;
868             col = 0;
869         }
870         fprintf(stderr, "%5d%c", code, (col+=6) >= 74 ? (col = 0, '\n') : ' ' );
871     }
872     putc( '\n', stderr );
873     exit( 0 );
874 }
875
876 code_int sorttab[1<<BITS];      /* sorted pointers into htab */
877
878 dump_tab()      /* dump string table */
879 {
880     register int i, first;
881     register ent;
882 #define STACK_SIZE      15000
883     int stack_top = STACK_SIZE;
884     register c;
885
886     if(do_decomp == 0) {        /* compressing */
887         register int flag = 1;
888
889         for(i=0; i<hsize; i++) {        /* build sort pointers */
890                 if((long)htabof(i) >= 0) {
891                         sorttab[codetabof(i)] = i;
892                 }
893         }
894         first = block_compress ? FIRST : 256;
895         for(i = first; i < free_ent; i++) {
896                 fprintf(stderr, "%5d: \"", i);
897                 de_stack[--stack_top] = '\n';
898                 de_stack[--stack_top] = '"';
899                 stack_top = in_stack((htabof(sorttab[i])>>maxbits)&0xff,
900                                      stack_top);
901                 for(ent=htabof(sorttab[i]) & ((1<<maxbits)-1);
902                     ent > 256;
903                     ent=htabof(sorttab[ent]) & ((1<<maxbits)-1)) {
904                         stack_top = in_stack(htabof(sorttab[ent]) >> maxbits,
905                                                 stack_top);
906                 }
907                 stack_top = in_stack(ent, stack_top);
908                 fwrite( &de_stack[stack_top], 1, STACK_SIZE-stack_top, stderr);
909                 stack_top = STACK_SIZE;
910         }
911    } else if(!debug) {  /* decompressing */
912
913        for ( i = 0; i < free_ent; i++ ) {
914            ent = i;
915            c = tab_suffixof(ent);
916            if ( isascii(c) && isprint(c) )
917                fprintf( stderr, "%5d: %5d/'%c'  \"",
918                            ent, tab_prefixof(ent), c );
919            else
920                fprintf( stderr, "%5d: %5d/\\%03o \"",
921                            ent, tab_prefixof(ent), c );
922            de_stack[--stack_top] = '\n';
923            de_stack[--stack_top] = '"';
924            for ( ; ent != NULL;
925                    ent = (ent >= FIRST ? tab_prefixof(ent) : NULL) ) {
926                stack_top = in_stack(tab_suffixof(ent), stack_top);
927            }
928            fwrite( &de_stack[stack_top], 1, STACK_SIZE - stack_top, stderr );
929            stack_top = STACK_SIZE;
930        }
931     }
932 }
933
934 int
935 in_stack(c, stack_top)
936         register c, stack_top;
937 {
938         if ( (isascii(c) && isprint(c) && c != '\\') || c == ' ' ) {
939             de_stack[--stack_top] = c;
940         } else {
941             switch( c ) {
942             case '\n': de_stack[--stack_top] = 'n'; break;
943             case '\t': de_stack[--stack_top] = 't'; break;
944             case '\b': de_stack[--stack_top] = 'b'; break;
945             case '\f': de_stack[--stack_top] = 'f'; break;
946             case '\r': de_stack[--stack_top] = 'r'; break;
947             case '\\': de_stack[--stack_top] = '\\'; break;
948             default:
949                 de_stack[--stack_top] = '0' + c % 8;
950                 de_stack[--stack_top] = '0' + (c / 8) % 8;
951                 de_stack[--stack_top] = '0' + c / 64;
952                 break;
953             }
954             de_stack[--stack_top] = '\\';
955         }
956         return stack_top;
957 }
958 #endif /* DEBUG */
959
960
961 #ifdef SYSV
962 void
963 #endif  /* SYSV */
964 onintr ( )
965 {
966     unlink ( ofname );
967     exit ( 1 );
968 }
969
970 #ifdef SYSV
971 void
972 #endif  /* SYSV */
973 oops ( )        /* wild pointer -- assume bad input */
974 {
975     if ( do_decomp == 1 )
976         fprintf ( stderr, "uncompress: corrupt input\n" );
977     unlink ( ofname );
978     exit ( 1 );
979 }
980
981 cl_block ()             /* table clear for block compress */
982 {
983     register long int rat;
984
985     checkpoint = in_count + CHECK_GAP;
986 #ifdef DEBUG
987         if ( debug ) {
988                 fprintf ( stderr, "count: %ld, ratio: ", in_count );
989                 prratio ( stderr, in_count, bytes_out );
990                 fprintf ( stderr, "\n");
991         }
992 #endif /* DEBUG */
993
994     if(in_count > 0x007fffff) { /* shift will overflow */
995         rat = bytes_out >> 8;
996         if(rat == 0) {          /* Don't divide by zero */
997             rat = 0x7fffffff;
998         } else {
999             rat = in_count / rat;
1000         }
1001     } else {
1002         rat = (in_count << 8) / bytes_out;      /* 8 fractional bits */
1003     }
1004     if ( rat > ratio ) {
1005         ratio = rat;
1006     } else {
1007         ratio = 0;
1008 #ifdef DEBUG
1009         if(verbose)
1010                 dump_tab();     /* dump string table */
1011 #endif
1012         cl_hash ( (count_int) hsize );
1013         free_ent = FIRST;
1014         clear_flg = 1;
1015         output ( (code_int) CLEAR );
1016 #ifdef DEBUG
1017         if(debug)
1018                 fprintf ( stderr, "clear\n" );
1019 #endif /* DEBUG */
1020     }
1021 }
1022
1023 cl_hash(hsize)          /* reset code table */
1024         register count_int hsize;
1025 {
1026 #ifndef XENIX_16        /* Normal machine */
1027         register count_int *htab_p = htab+hsize;
1028 #else
1029         register j;
1030         register long k = hsize;
1031         register count_int *htab_p;
1032 #endif
1033         register long i;
1034         register long m1 = -1;
1035
1036 #ifdef XENIX_16
1037     for(j=0; j<=8 && k>=0; j++,k-=8192) {
1038         i = 8192;
1039         if(k < 8192) {
1040                 i = k;
1041         }
1042         htab_p = &(htab[j][i]);
1043         i -= 16;
1044         if(i > 0) {
1045 #else
1046         i = hsize - 16;
1047 #endif
1048         do {                            /* might use Sys V memset(3) here */
1049                 *(htab_p-16) = m1;
1050                 *(htab_p-15) = m1;
1051                 *(htab_p-14) = m1;
1052                 *(htab_p-13) = m1;
1053                 *(htab_p-12) = m1;
1054                 *(htab_p-11) = m1;
1055                 *(htab_p-10) = m1;
1056                 *(htab_p-9) = m1;
1057                 *(htab_p-8) = m1;
1058                 *(htab_p-7) = m1;
1059                 *(htab_p-6) = m1;
1060                 *(htab_p-5) = m1;
1061                 *(htab_p-4) = m1;
1062                 *(htab_p-3) = m1;
1063                 *(htab_p-2) = m1;
1064                 *(htab_p-1) = m1;
1065                 htab_p -= 16;
1066         } while ((i -= 16) >= 0);
1067 #ifdef XENIX_16
1068         }
1069     }
1070 #endif
1071         for ( i += 16; i > 0; i-- )
1072                 *--htab_p = m1;
1073 }
1074
1075 prratio(stream, num, den)
1076 FILE *stream;
1077 long int num, den;
1078 {
1079         register int q;                 /* Doesn't need to be long */
1080
1081         if(num > 214748L) {             /* 2147483647/10000 */
1082                 q = num / (den / 10000L);
1083         } else {
1084                 q = 10000L * num / den;         /* Long calculations, though */
1085         }
1086         if (q < 0) {
1087                 putc('-', stream);
1088                 q = -q;
1089         }
1090         fprintf(stream, "%d.%02d%%", q / 100, q % 100);
1091 }
1092
1093 version()
1094 {
1095         fprintf(stderr, "%s\n", rcs_ident);
1096         fprintf(stderr, "Options: ");
1097 #ifdef NO_UCHAR
1098         fprintf(stderr, "NO_UCHAR, ");
1099 #endif
1100 #ifdef SIGNED_COMPARE_SLOW
1101         fprintf(stderr, "SIGNED_COMPARE_SLOW, ");
1102 #endif
1103 #ifdef XENIX_16
1104         fprintf(stderr, "XENIX_16, ");
1105 #endif
1106 #ifdef COMPATIBLE
1107         fprintf(stderr, "COMPATIBLE, ");
1108 #endif
1109 #ifdef DEBUG
1110         fprintf(stderr, "DEBUG, ");
1111 #endif
1112 #ifdef BSD4_2
1113         fprintf(stderr, "BSD4_2, ");
1114 #endif
1115         fprintf(stderr, "BITS = %d\n", BITS);
1116 }
1117
1118
1119
1120
1121 /* SPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPECSPEC */
1122 getbyte()
1123 {
1124         if( InCnt > 0 ) {
1125                 InCnt--;
1126                 return( (unsigned int)*InBuff++ );
1127         } else {
1128                 return( -1 );
1129         }
1130 }
1131
1132 putbyte( c )
1133 char c;
1134 {
1135         *OutBuff++ = c;
1136 }
1137
1138 readbytes( buf, n )
1139 char *buf;
1140 int n;
1141 {
1142         int i;
1143
1144         if( InCnt <= 0 )
1145                 return( -1 );
1146
1147         if( n > InCnt )
1148                 n = InCnt;
1149
1150         for( i=0; i<n; i++ ) {
1151                 buf[i] = *InBuff++;
1152                 InCnt--;
1153         }
1154
1155         return( i );
1156 }
1157
1158 writebytes( buf, n )
1159 char *buf;
1160 int n;
1161 {
1162         int i;
1163
1164         for( i=0; i<n; i++ )
1165                 *OutBuff++ = buf[i];
1166 }