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