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