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