Home | History | Annotate | Line # | Download | only in compress
zopen.c revision 1.1.1.1
      1 /*-
      2  * Copyright (c) 1985, 1986, 1992, 1993
      3  *	The Regents of the University of California.  All rights reserved.
      4  *
      5  * This code is derived from software contributed to Berkeley by
      6  * Diomidis Spinellis and James A. Woods, derived from original
      7  * work by Spencer Thomas and Joseph Orost.
      8  *
      9  * Redistribution and use in source and binary forms, with or without
     10  * modification, are permitted provided that the following conditions
     11  * are met:
     12  * 1. Redistributions of source code must retain the above copyright
     13  *    notice, this list of conditions and the following disclaimer.
     14  * 2. Redistributions in binary form must reproduce the above copyright
     15  *    notice, this list of conditions and the following disclaimer in the
     16  *    documentation and/or other materials provided with the distribution.
     17  * 3. All advertising materials mentioning features or use of this software
     18  *    must display the following acknowledgement:
     19  *	This product includes software developed by the University of
     20  *	California, Berkeley and its contributors.
     21  * 4. Neither the name of the University nor the names of its contributors
     22  *    may be used to endorse or promote products derived from this software
     23  *    without specific prior written permission.
     24  *
     25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     35  * SUCH DAMAGE.
     36  */
     37 
     38 #if defined(LIBC_SCCS) && !defined(lint)
     39 static char sccsid[] = "@(#)zopen.c	8.1 (Berkeley) 6/27/93";
     40 #endif /* LIBC_SCCS and not lint */
     41 
     42 /*-
     43  * fcompress.c - File compression ala IEEE Computer, June 1984.
     44  *
     45  * Compress authors:
     46  *		Spencer W. Thomas	(decvax!utah-cs!thomas)
     47  *		Jim McKie		(decvax!mcvax!jim)
     48  *		Steve Davies		(decvax!vax135!petsd!peora!srd)
     49  *		Ken Turkowski		(decvax!decwrl!turtlevax!ken)
     50  *		James A. Woods		(decvax!ihnp4!ames!jaw)
     51  *		Joe Orost		(decvax!vax135!petsd!joe)
     52  *
     53  * Cleaned up and converted to library returning I/O streams by
     54  * Diomidis Spinellis <dds (at) doc.ic.ac.uk>.
     55  *
     56  * zopen(filename, mode, bits)
     57  *	Returns a FILE * that can be used for read or write.  The modes
     58  *	supported are only "r" and "w".  Seeking is not allowed.  On
     59  *	reading the file is decompressed, on writing it is compressed.
     60  *	The output is compatible with compress(1) with 16 bit tables.
     61  *	Any file produced by compress(1) can be read.
     62  */
     63 
     64 #include <sys/param.h>
     65 #include <sys/stat.h>
     66 
     67 #include <ctype.h>
     68 #include <errno.h>
     69 #include <signal.h>
     70 #include <stdio.h>
     71 #include <stdlib.h>
     72 #include <string.h>
     73 #include <unistd.h>
     74 
     75 #define	BITS		16		/* Default bits. */
     76 #define	HSIZE		69001		/* 95% occupancy */
     77 
     78 /* A code_int must be able to hold 2**BITS values of type int, and also -1. */
     79 typedef long code_int;
     80 typedef long count_int;
     81 
     82 typedef u_char char_type;
     83 static char_type magic_header[] =
     84 	{'\037', '\235'};		/* 1F 9D */
     85 
     86 #define	BIT_MASK	0x1f		/* Defines for third byte of header. */
     87 #define	BLOCK_MASK	0x80
     88 
     89 /*
     90  * Masks 0x40 and 0x20 are free.  I think 0x20 should mean that there is
     91  * a fourth header byte (for expansion).
     92  */
     93 #define	INIT_BITS 9			/* Initial number of bits/code. */
     94 
     95 #define	MAXCODE(n_bits)	((1 << (n_bits)) - 1)
     96 
     97 struct s_zstate {
     98 	FILE *zs_fp;			/* File stream for I/O */
     99 	char zs_mode;			/* r or w */
    100 	enum {
    101 		S_START, S_MIDDLE, S_EOF
    102 	} zs_state;			/* State of computation */
    103 	int zs_n_bits;			/* Number of bits/code. */
    104 	int zs_maxbits;			/* User settable max # bits/code. */
    105 	code_int zs_maxcode;		/* Maximum code, given n_bits. */
    106 	code_int zs_maxmaxcode;		/* Should NEVER generate this code. */
    107 	count_int zs_htab [HSIZE];
    108 	u_short zs_codetab [HSIZE];
    109 	code_int zs_hsize;		/* For dynamic table sizing. */
    110 	code_int zs_free_ent;		/* First unused entry. */
    111 	/*
    112 	 * Block compression parameters -- after all codes are used up,
    113 	 * and compression rate changes, start over.
    114 	 */
    115 	int zs_block_compress;
    116 	int zs_clear_flg;
    117 	long zs_ratio;
    118 	count_int zs_checkpoint;
    119 	int zs_offset;
    120 	long zs_in_count;		/* Length of input. */
    121 	long zs_bytes_out;		/* Length of compressed output. */
    122 	long zs_out_count;		/* # of codes output (for debugging). */
    123 	char_type zs_buf[BITS];
    124 	union {
    125 		struct {
    126 			long zs_fcode;
    127 			code_int zs_ent;
    128 			code_int zs_hsize_reg;
    129 			int zs_hshift;
    130 		} w;			/* Write paramenters */
    131 		struct {
    132 			char_type *zs_stackp;
    133 			int zs_finchar;
    134 			code_int zs_code, zs_oldcode, zs_incode;
    135 			int zs_roffset, zs_size;
    136 			char_type zs_gbuf[BITS];
    137 		} r;			/* Read parameters */
    138 	} u;
    139 };
    140 
    141 /* Definitions to retain old variable names */
    142 #define	fp		zs->zs_fp
    143 #define	zmode		zs->zs_mode
    144 #define	state		zs->zs_state
    145 #define	n_bits		zs->zs_n_bits
    146 #define	maxbits		zs->zs_maxbits
    147 #define	maxcode		zs->zs_maxcode
    148 #define	maxmaxcode	zs->zs_maxmaxcode
    149 #define	htab		zs->zs_htab
    150 #define	codetab		zs->zs_codetab
    151 #define	hsize		zs->zs_hsize
    152 #define	free_ent	zs->zs_free_ent
    153 #define	block_compress	zs->zs_block_compress
    154 #define	clear_flg	zs->zs_clear_flg
    155 #define	ratio		zs->zs_ratio
    156 #define	checkpoint	zs->zs_checkpoint
    157 #define	offset		zs->zs_offset
    158 #define	in_count	zs->zs_in_count
    159 #define	bytes_out	zs->zs_bytes_out
    160 #define	out_count	zs->zs_out_count
    161 #define	buf		zs->zs_buf
    162 #define	fcode		zs->u.w.zs_fcode
    163 #define	hsize_reg	zs->u.w.zs_hsize_reg
    164 #define	ent		zs->u.w.zs_ent
    165 #define	hshift		zs->u.w.zs_hshift
    166 #define	stackp		zs->u.r.zs_stackp
    167 #define	finchar		zs->u.r.zs_finchar
    168 #define	code		zs->u.r.zs_code
    169 #define	oldcode		zs->u.r.zs_oldcode
    170 #define	incode		zs->u.r.zs_incode
    171 #define	roffset		zs->u.r.zs_roffset
    172 #define	size		zs->u.r.zs_size
    173 #define	gbuf		zs->u.r.zs_gbuf
    174 
    175 /*
    176  * To save much memory, we overlay the table used by compress() with those
    177  * used by decompress().  The tab_prefix table is the same size and type as
    178  * the codetab.  The tab_suffix table needs 2**BITS characters.  We get this
    179  * from the beginning of htab.  The output stack uses the rest of htab, and
    180  * contains characters.  There is plenty of room for any possible stack
    181  * (stack used to be 8000 characters).
    182  */
    183 
    184 #define	htabof(i)	htab[i]
    185 #define	codetabof(i)	codetab[i]
    186 
    187 #define	tab_prefixof(i)	codetabof(i)
    188 #define	tab_suffixof(i)	((char_type *)(htab))[i]
    189 #define	de_stack	((char_type *)&tab_suffixof(1 << BITS))
    190 
    191 #define	CHECK_GAP 10000		/* Ratio check interval. */
    192 
    193 /*
    194  * the next two codes should not be changed lightly, as they must not
    195  * lie within the contiguous general code space.
    196  */
    197 #define	FIRST	257		/* First free entry. */
    198 #define	CLEAR	256		/* Table clear output code. */
    199 
    200 static int	cl_block __P((struct s_zstate *));
    201 static void	cl_hash __P((struct s_zstate *, count_int));
    202 static code_int	getcode __P((struct s_zstate *));
    203 static int	output __P((struct s_zstate *, code_int));
    204 static int	zclose __P((void *));
    205 static int	zread __P((void *, char *, int));
    206 static int	zwrite __P((void *, const char *, int));
    207 
    208 /*-
    209  * Algorithm from "A Technique for High Performance Data Compression",
    210  * Terry A. Welch, IEEE Computer Vol 17, No 6 (June 1984), pp 8-19.
    211  *
    212  * Algorithm:
    213  * 	Modified Lempel-Ziv method (LZW).  Basically finds common
    214  * substrings and replaces them with a variable size code.  This is
    215  * deterministic, and can be done on the fly.  Thus, the decompression
    216  * procedure needs no input table, but tracks the way the table was built.
    217  */
    218 
    219 /*-
    220  * compress write
    221  *
    222  * Algorithm:  use open addressing double hashing (no chaining) on the
    223  * prefix code / next character combination.  We do a variant of Knuth's
    224  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
    225  * secondary probe.  Here, the modular division first probe is gives way
    226  * to a faster exclusive-or manipulation.  Also do block compression with
    227  * an adaptive reset, whereby the code table is cleared when the compression
    228  * ratio decreases, but after the table fills.  The variable-length output
    229  * codes are re-sized at this point, and a special CLEAR code is generated
    230  * for the decompressor.  Late addition:  construct the table according to
    231  * file size for noticeable speed improvement on small files.  Please direct
    232  * questions about this implementation to ames!jaw.
    233  */
    234 static int
    235 zwrite(cookie, wbp, num)
    236 	void *cookie;
    237 	const char *wbp;
    238 	int num;
    239 {
    240 	register code_int i;
    241 	register int c, disp;
    242 	struct s_zstate *zs;
    243 	const u_char *bp;
    244 	u_char tmp;
    245 	int count;
    246 
    247 	if (num == 0)
    248 		return (0);
    249 
    250 	zs = cookie;
    251 	count = num;
    252 	bp = (u_char *)wbp;
    253 	if (state == S_MIDDLE)
    254 		goto middle;
    255 	state = S_MIDDLE;
    256 
    257 	maxmaxcode = 1L << BITS;
    258 	if (fwrite(magic_header,
    259 	    sizeof(char), sizeof(magic_header), fp) != sizeof(magic_header))
    260 		return (-1);
    261 	tmp = (u_char)(BITS | block_compress);
    262 	if (fwrite(&tmp, sizeof(char), sizeof(tmp), fp) != sizeof(tmp))
    263 		return (-1);
    264 
    265 	offset = 0;
    266 	bytes_out = 3;		/* Includes 3-byte header mojo. */
    267 	out_count = 0;
    268 	clear_flg = 0;
    269 	ratio = 0;
    270 	in_count = 1;
    271 	checkpoint = CHECK_GAP;
    272 	maxcode = MAXCODE(n_bits = INIT_BITS);
    273 	free_ent = ((block_compress) ? FIRST : 256);
    274 
    275 	ent = *bp++;
    276 	--count;
    277 
    278 	hshift = 0;
    279 	for (fcode = (long)hsize; fcode < 65536L; fcode *= 2L)
    280 		hshift++;
    281 	hshift = 8 - hshift;	/* Set hash code range bound. */
    282 
    283 	hsize_reg = hsize;
    284 	cl_hash(zs, (count_int)hsize_reg);	/* Clear hash table. */
    285 
    286 middle:	for (i = 0; count--;) {
    287 		c = *bp++;
    288 		in_count++;
    289 		fcode = (long)(((long)c << maxbits) + ent);
    290 		i = ((c << hshift) ^ ent);	/* Xor hashing. */
    291 
    292 		if (htabof(i) == fcode) {
    293 			ent = codetabof(i);
    294 			continue;
    295 		} else if ((long)htabof(i) < 0)	/* Empty slot. */
    296 			goto nomatch;
    297 		disp = hsize_reg - i;	/* Secondary hash (after G. Knott). */
    298 		if (i == 0)
    299 			disp = 1;
    300 probe:		if ((i -= disp) < 0)
    301 			i += hsize_reg;
    302 
    303 		if (htabof(i) == fcode) {
    304 			ent = codetabof(i);
    305 			continue;
    306 		}
    307 		if ((long)htabof(i) >= 0)
    308 			goto probe;
    309 nomatch:	if (output(zs, (code_int) ent) == -1)
    310 			return (-1);
    311 		out_count++;
    312 		ent = c;
    313 		if (free_ent < maxmaxcode) {
    314 			codetabof(i) = free_ent++;	/* code -> hashtable */
    315 			htabof(i) = fcode;
    316 		} else if ((count_int)in_count >=
    317 		    checkpoint && block_compress) {
    318 			if (cl_block(zs) == -1)
    319 				return (-1);
    320 		}
    321 	}
    322 	return (num);
    323 }
    324 
    325 static int
    326 zclose(cookie)
    327 	void *cookie;
    328 {
    329 	struct s_zstate *zs;
    330 	int rval;
    331 
    332 	zs = cookie;
    333 	if (zmode == 'w') {		/* Put out the final code. */
    334 		if (output(zs, (code_int) ent) == -1) {
    335 			(void)fclose(fp);
    336 			free(zs);
    337 			return (-1);
    338 		}
    339 		out_count++;
    340 		if (output(zs, (code_int) - 1) == -1) {
    341 			(void)fclose(fp);
    342 			free(zs);
    343 			return (-1);
    344 		}
    345 	}
    346 	rval = fclose(fp) == EOF ? -1 : 0;
    347 	free(zs);
    348 	return (rval);
    349 }
    350 
    351 /*-
    352  * Output the given code.
    353  * Inputs:
    354  * 	code:	A n_bits-bit integer.  If == -1, then EOF.  This assumes
    355  *		that n_bits =< (long)wordsize - 1.
    356  * Outputs:
    357  * 	Outputs code to the file.
    358  * Assumptions:
    359  *	Chars are 8 bits long.
    360  * Algorithm:
    361  * 	Maintain a BITS character long buffer (so that 8 codes will
    362  * fit in it exactly).  Use the VAX insv instruction to insert each
    363  * code in turn.  When the buffer fills up empty it and start over.
    364  */
    365 
    366 static char_type lmask[9] =
    367 	{0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80, 0x00};
    368 static char_type rmask[9] =
    369 	{0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
    370 
    371 static int
    372 output(zs, ocode)
    373 	struct s_zstate *zs;
    374 	code_int ocode;
    375 {
    376 	register int bits, r_off;
    377 	register char_type *bp;
    378 
    379 	r_off = offset;
    380 	bits = n_bits;
    381 	bp = buf;
    382 	if (ocode >= 0) {
    383 		/* Get to the first byte. */
    384 		bp += (r_off >> 3);
    385 		r_off &= 7;
    386 		/*
    387 		 * Since ocode is always >= 8 bits, only need to mask the first
    388 		 * hunk on the left.
    389 		 */
    390 		*bp = (*bp & rmask[r_off]) | (ocode << r_off) & lmask[r_off];
    391 		bp++;
    392 		bits -= (8 - r_off);
    393 		ocode >>= 8 - r_off;
    394 		/* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
    395 		if (bits >= 8) {
    396 			*bp++ = ocode;
    397 			ocode >>= 8;
    398 			bits -= 8;
    399 		}
    400 		/* Last bits. */
    401 		if (bits)
    402 			*bp = ocode;
    403 		offset += n_bits;
    404 		if (offset == (n_bits << 3)) {
    405 			bp = buf;
    406 			bits = n_bits;
    407 			bytes_out += bits;
    408 			if (fwrite(bp, sizeof(char), bits, fp) != bits)
    409 				return (-1);
    410 			bp += bits;
    411 			bits = 0;
    412 			offset = 0;
    413 		}
    414 		/*
    415 		 * If the next entry is going to be too big for the ocode size,
    416 		 * then increase it, if possible.
    417 		 */
    418 		if (free_ent > maxcode || (clear_flg > 0)) {
    419 		       /*
    420 			* Write the whole buffer, because the input side won't
    421 			* discover the size increase until after it has read it.
    422 			*/
    423 			if (offset > 0) {
    424 				if (fwrite(buf, 1, n_bits, fp) != n_bits)
    425 					return (-1);
    426 				bytes_out += n_bits;
    427 			}
    428 			offset = 0;
    429 
    430 			if (clear_flg) {
    431 				maxcode = MAXCODE(n_bits = INIT_BITS);
    432 				clear_flg = 0;
    433 			} else {
    434 				n_bits++;
    435 				if (n_bits == maxbits)
    436 					maxcode = maxmaxcode;
    437 				else
    438 					maxcode = MAXCODE(n_bits);
    439 			}
    440 		}
    441 	} else {
    442 		/* At EOF, write the rest of the buffer. */
    443 		if (offset > 0) {
    444 			offset = (offset + 7) / 8;
    445 			if (fwrite(buf, 1, offset, fp) != offset)
    446 				return (-1);
    447 			bytes_out += offset;
    448 		}
    449 		offset = 0;
    450 	}
    451 	return (0);
    452 }
    453 
    454 /*
    455  * Decompress read.  This routine adapts to the codes in the file building
    456  * the "string" table on-the-fly; requiring no table to be stored in the
    457  * compressed file.  The tables used herein are shared with those of the
    458  * compress() routine.  See the definitions above.
    459  */
    460 static int
    461 zread(cookie, rbp, num)
    462 	void *cookie;
    463 	char *rbp;
    464 	int num;
    465 {
    466 	register u_int count;
    467 	struct s_zstate *zs;
    468 	u_char *bp, header[3];
    469 
    470 	if (num == 0)
    471 		return (0);
    472 
    473 	zs = cookie;
    474 	count = num;
    475 	bp = (u_char *)rbp;
    476 	switch (state) {
    477 	case S_START:
    478 		state = S_MIDDLE;
    479 		break;
    480 	case S_MIDDLE:
    481 		goto middle;
    482 	case S_EOF:
    483 		goto eof;
    484 	}
    485 
    486 	/* Check the magic number */
    487 	if (fread(header,
    488 	    sizeof(char), sizeof(header), fp) != sizeof(header) ||
    489 	    memcmp(header, magic_header, sizeof(magic_header)) != 0) {
    490 		errno = EFTYPE;
    491 		return (-1);
    492 	}
    493 	maxbits = header[2];	/* Set -b from file. */
    494 	block_compress = maxbits & BLOCK_MASK;
    495 	maxbits &= BIT_MASK;
    496 	maxmaxcode = 1L << maxbits;
    497 	if (maxbits > BITS) {
    498 		errno = EFTYPE;
    499 		return (-1);
    500 	}
    501 	/* As above, initialize the first 256 entries in the table. */
    502 	maxcode = MAXCODE(n_bits = INIT_BITS);
    503 	for (code = 255; code >= 0; code--) {
    504 		tab_prefixof(code) = 0;
    505 		tab_suffixof(code) = (char_type) code;
    506 	}
    507 	free_ent = block_compress ? FIRST : 256;
    508 
    509 	finchar = oldcode = getcode(zs);
    510 	if (oldcode == -1)	/* EOF already? */
    511 		return (0);	/* Get out of here */
    512 
    513 	/* First code must be 8 bits = char. */
    514 	*bp++ = (u_char)finchar;
    515 	count--;
    516 	stackp = de_stack;
    517 
    518 	while ((code = getcode(zs)) > -1) {
    519 
    520 		if ((code == CLEAR) && block_compress) {
    521 			for (code = 255; code >= 0; code--)
    522 				tab_prefixof(code) = 0;
    523 			clear_flg = 1;
    524 			free_ent = FIRST - 1;
    525 			if ((code = getcode(zs)) == -1)	/* O, untimely death! */
    526 				break;
    527 		}
    528 		incode = code;
    529 
    530 		/* Special case for KwKwK string. */
    531 		if (code >= free_ent) {
    532 			*stackp++ = finchar;
    533 			code = oldcode;
    534 		}
    535 
    536 		/* Generate output characters in reverse order. */
    537 		while (code >= 256) {
    538 			*stackp++ = tab_suffixof(code);
    539 			code = tab_prefixof(code);
    540 		}
    541 		*stackp++ = finchar = tab_suffixof(code);
    542 
    543 		/* And put them out in forward order.  */
    544 middle:		do {
    545 			if (count-- == 0)
    546 				return (num);
    547 			*bp++ = *--stackp;
    548 		} while (stackp > de_stack);
    549 
    550 		/* Generate the new entry. */
    551 		if ((code = free_ent) < maxmaxcode) {
    552 			tab_prefixof(code) = (u_short) oldcode;
    553 			tab_suffixof(code) = finchar;
    554 			free_ent = code + 1;
    555 		}
    556 
    557 		/* Remember previous code. */
    558 		oldcode = incode;
    559 	}
    560 	state = S_EOF;
    561 eof:	return (num - count);
    562 }
    563 
    564 /*-
    565  * Read one code from the standard input.  If EOF, return -1.
    566  * Inputs:
    567  * 	stdin
    568  * Outputs:
    569  * 	code or -1 is returned.
    570  */
    571 static code_int
    572 getcode(zs)
    573 	struct s_zstate *zs;
    574 {
    575 	register code_int gcode;
    576 	register int r_off, bits;
    577 	register char_type *bp;
    578 
    579 	bp = gbuf;
    580 	if (clear_flg > 0 || roffset >= size || free_ent > maxcode) {
    581 		/*
    582 		 * If the next entry will be too big for the current gcode
    583 		 * size, then we must increase the size.  This implies reading
    584 		 * a new buffer full, too.
    585 		 */
    586 		if (free_ent > maxcode) {
    587 			n_bits++;
    588 			if (n_bits == maxbits)	/* Won't get any bigger now. */
    589 				maxcode = maxmaxcode;
    590 			else
    591 				maxcode = MAXCODE(n_bits);
    592 		}
    593 		if (clear_flg > 0) {
    594 			maxcode = MAXCODE(n_bits = INIT_BITS);
    595 			clear_flg = 0;
    596 		}
    597 		size = fread(gbuf, 1, n_bits, fp);
    598 		if (size <= 0)			/* End of file. */
    599 			return (-1);
    600 		roffset = 0;
    601 		/* Round size down to integral number of codes. */
    602 		size = (size << 3) - (n_bits - 1);
    603 	}
    604 	r_off = roffset;
    605 	bits = n_bits;
    606 
    607 	/* Get to the first byte. */
    608 	bp += (r_off >> 3);
    609 	r_off &= 7;
    610 
    611 	/* Get first part (low order bits). */
    612 	gcode = (*bp++ >> r_off);
    613 	bits -= (8 - r_off);
    614 	r_off = 8 - r_off;	/* Now, roffset into gcode word. */
    615 
    616 	/* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
    617 	if (bits >= 8) {
    618 		gcode |= *bp++ << r_off;
    619 		r_off += 8;
    620 		bits -= 8;
    621 	}
    622 
    623 	/* High order bits. */
    624 	gcode |= (*bp & rmask[bits]) << r_off;
    625 	roffset += n_bits;
    626 
    627 	return (gcode);
    628 }
    629 
    630 static int
    631 cl_block(zs)			/* Table clear for block compress. */
    632 	struct s_zstate *zs;
    633 {
    634 	register long rat;
    635 
    636 	checkpoint = in_count + CHECK_GAP;
    637 
    638 	if (in_count > 0x007fffff) {	/* Shift will overflow. */
    639 		rat = bytes_out >> 8;
    640 		if (rat == 0)		/* Don't divide by zero. */
    641 			rat = 0x7fffffff;
    642 		else
    643 			rat = in_count / rat;
    644 	} else
    645 		rat = (in_count << 8) / bytes_out;	/* 8 fractional bits. */
    646 	if (rat > ratio)
    647 		ratio = rat;
    648 	else {
    649 		ratio = 0;
    650 		cl_hash(zs, (count_int) hsize);
    651 		free_ent = FIRST;
    652 		clear_flg = 1;
    653 		if (output(zs, (code_int) CLEAR) == -1)
    654 			return (-1);
    655 	}
    656 	return (0);
    657 }
    658 
    659 static void
    660 cl_hash(zs, cl_hsize)			/* Reset code table. */
    661 	struct s_zstate *zs;
    662 	register count_int cl_hsize;
    663 {
    664 	register count_int *htab_p;
    665 	register long i, m1;
    666 
    667 	m1 = -1;
    668 	htab_p = htab + cl_hsize;
    669 	i = cl_hsize - 16;
    670 	do {			/* Might use Sys V memset(3) here. */
    671 		*(htab_p - 16) = m1;
    672 		*(htab_p - 15) = m1;
    673 		*(htab_p - 14) = m1;
    674 		*(htab_p - 13) = m1;
    675 		*(htab_p - 12) = m1;
    676 		*(htab_p - 11) = m1;
    677 		*(htab_p - 10) = m1;
    678 		*(htab_p - 9) = m1;
    679 		*(htab_p - 8) = m1;
    680 		*(htab_p - 7) = m1;
    681 		*(htab_p - 6) = m1;
    682 		*(htab_p - 5) = m1;
    683 		*(htab_p - 4) = m1;
    684 		*(htab_p - 3) = m1;
    685 		*(htab_p - 2) = m1;
    686 		*(htab_p - 1) = m1;
    687 		htab_p -= 16;
    688 	} while ((i -= 16) >= 0);
    689 	for (i += 16; i > 0; i--)
    690 		*--htab_p = m1;
    691 }
    692 
    693 FILE *
    694 zopen(fname, mode, bits)
    695 	const char *fname, *mode;
    696 	int bits;
    697 {
    698 	struct s_zstate *zs;
    699 
    700 	if (mode[0] != 'r' && mode[0] != 'w' || mode[1] != '\0' ||
    701 	    bits < 0 || bits > BITS) {
    702 		errno = EINVAL;
    703 		return (NULL);
    704 	}
    705 
    706 	if ((zs = calloc(1, sizeof(struct s_zstate))) == NULL)
    707 		return (NULL);
    708 
    709 	maxbits = bits ? bits : BITS;	/* User settable max # bits/code. */
    710 	maxmaxcode = 1 << BITS;		/* Should NEVER generate this code. */
    711 	hsize = HSIZE;			/* For dynamic table sizing. */
    712 	free_ent = 0;			/* First unused entry. */
    713 	block_compress = BLOCK_MASK;
    714 	clear_flg = 0;
    715 	ratio = 0;
    716 	checkpoint = CHECK_GAP;
    717 	in_count = 1;			/* Length of input. */
    718 	out_count = 0;			/* # of codes output (for debugging). */
    719 	state = S_START;
    720 	roffset = 0;
    721 	size = 0;
    722 
    723 	/*
    724 	 * Layering compress on top of stdio in order to provide buffering,
    725 	 * and ensure that reads and write work with the data specified.
    726 	 */
    727 	if ((fp = fopen(fname, mode)) == NULL) {
    728 		free(zs);
    729 		return (NULL);
    730 	}
    731 	switch (*mode) {
    732 	case 'r':
    733 		zmode = 'r';
    734 		return (funopen(zs, zread, NULL, NULL, zclose));
    735 	case 'w':
    736 		zmode = 'w';
    737 		return (funopen(zs, NULL, zwrite, NULL, zclose));
    738 	}
    739 	/* NOTREACHED */
    740 }
    741