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