/*
 * $Copyright:	$
 * Copyright (c) 1984, 1985, 1986, 1987, 1988, 1989, 1990 
 * Sequent Computer Systems, Inc.   All rights reserved.
 *  
 * This software is furnished under a license and may be used
 * only in accordance with the terms of that license and with the
 * inclusion of the above copyright notice.   This software may not
 * be provided or otherwise made available to, or used by, any
 * other person.  No title to or ownership of the software is
 * hereby transferred.
 *
 */

/*	Copyright (c) 1984 AT&T	*/
/*	  All Rights Reserved  	*/

/*	THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF AT&T	*/
/*	The copyright notice above does not evidence any   	*/
/*	actual or intended publication of such source code.	*/

#ident	"$Header: pack.c 1.10 89/11/15 $@(#)pack:pack.c	1.12"
/*
 *	Huffman encoding program 
 *	Usage:	pack [[ - ] filename ... ] filename ...
 *		- option: enable/disable listing of statistics
 */

#ifdef CCS
#include "../../tools/compat.h"
#endif

#include  <stdio.h>
#include <sys/param.h>
#include <sys/types.h>
#include <sys/stat.h>
#ifdef	CCS
#define DYNIX_MAXNAMLEN 255             /* maximum filename length */
#endif

#define	END	256
#define PACKED 017436 /* <US><RS> - Unlikely value */
#define	SUF0	'.'
#define	SUF1	'z'

struct stat status, ostatus;

/* union for overlaying a long int with a set of four characters */
union FOUR {
	struct { long int lng; } lint;
	struct { char c0, c1, c2, c3; } chars;
};

/* character counters */
long	count [END+1];
union	FOUR insize;
long	outsize;
long	dictsize;
int	diffbytes;

/* i/o stuff */
char	vflag = 0;
int	force = 0;	/* allow forced packing for consistency in directory */
char	filename [MAXPATHLEN];
int	infile;		/* unpacked file */
int	outfile;	/* packed file */
char	inbuff [8*BUFSIZ];
char	outbuff [8*BUFSIZ+4];

/* variables associated with the tree */
int	maxlev;
int	levcount [25];
int	lastnode;
int	parent [2*END+1];

/* variables associated with the encoding process */
char	length [END+1];
long	bits [END+1];
union	FOUR mask;
long	inc;
#if vax | ns32000 | i386
char	*maskshuff[4]  = {&(mask.chars.c3), &(mask.chars.c2), &(mask.chars.c1), &(mask.chars.c0)};
#else
#ifdef pdp11
char	*maskshuff[4]  = {&(mask.chars.c1), &(mask.chars.c0), &(mask.chars.c3), &(mask.chars.c2)};
#else	/* u370 or 3b20 */
char	*maskshuff[4]  = {&(mask.chars.c0), &(mask.chars.c1), &(mask.chars.c2), &(mask.chars.c3)};
#endif
#endif

/* the heap */
int	n;
struct	heap {
	long int count;
	int node;
} heap [END+2];
#define hmove(a,b) {(b).count = (a).count; (b).node = (a).node;}

/* gather character frequency statistics */
/* return 1 if successful, 0 otherwise */
input ()
{
	register int i;
	for (i=0; i<END; i++)
		count[i] = 0;
	while ((i = read(infile, inbuff, 8*BUFSIZ)) > 0)
		while (i > 0)
			count[inbuff[--i]&0377] += 2;
	if (i == 0)
		return (1);
	printf (gettxt("pack:1", ": read error"));
	return (0);
}

/* encode the current file */
/* return 1 if successful, 0 otherwise */
output ()
{
	extern long lseek();
	int c, i, inleft;
	char *inp;
	register char **q, *outp;
	register int bitsleft;
	long temp;

	/* output ``PACKED'' header */
	outbuff[0] = 037; 	/* ascii US */
	outbuff[1] = 036; 	/* ascii RS */
	/* output the length and the dictionary */
	temp = insize.lint.lng;
	for (i=5; i>=2; i--) {
		outbuff[i] =  (char) (temp & 0377);
		temp >>= 8;
	}
	outp = &outbuff[6];
	*outp++ = maxlev;
	for (i=1; i<maxlev; i++)
		*outp++ = levcount[i];
	*outp++ = levcount[maxlev]-2;
	for (i=1; i<=maxlev; i++)
		for (c=0; c<END; c++)
			if (length[c] == i)
				*outp++ = c;
	dictsize = outp-&outbuff[0];

	/* output the text */
	lseek(infile, 0L, 0);
	outsize = 0;
	bitsleft = 8;
	inleft = 0;
	do {
		if (inleft <= 0) {
			inleft = read(infile, inp = &inbuff[0], 8*BUFSIZ);
			if (inleft < 0) {
				printf (gettxt("pack:1", ": read error"));
				return (0);
			}
		}
		c = (--inleft < 0) ? END : (*inp++ & 0377);
		mask.lint.lng = bits[c]<<bitsleft;
		q = &maskshuff[0];
		if (bitsleft == 8)
			*outp = **q++;
		else
			*outp |= **q++;
		bitsleft -= length[c];
		while (bitsleft < 0) {
			*++outp = **q++;
			bitsleft += 8;
		}
		if (outp >= &outbuff[8*BUFSIZ]) {
			if (write(outfile, outbuff, 8*BUFSIZ) != 8*BUFSIZ) {
wrerr:				printf (gettxt("pack:2", ".z: write error"));
				return (0);
			}
			((union FOUR *) outbuff)->lint.lng = ((union FOUR *) &outbuff[8*BUFSIZ])->lint.lng;
			outp -= 8*BUFSIZ;
			outsize += 8*BUFSIZ;
		}
	} while (c != END);
	if (bitsleft < 8)
		outp++;
	c = outp-outbuff;
	if (write(outfile, outbuff, c) != c)
		goto wrerr;
	outsize += c;
	return (1);
}

/* makes a heap out of heap[i],...,heap[n] */
heapify (i)
{
	register int k;
	int lastparent;
	struct heap heapsubi;
	hmove (heap[i], heapsubi);
	lastparent = n/2;
	while (i <= lastparent) {
		k = 2*i;
		if (heap[k].count > heap[k+1].count && k < n)
			k++;
		if (heapsubi.count < heap[k].count)
			break;
		hmove (heap[k], heap[i]);
		i = k;
	}
	hmove (heapsubi, heap[i]);
}

/* return 1 after successful packing, 0 otherwise */
int packfile ()
{
	register int c, i, p;
	long bitsout;

	/* gather frequency statistics */
	if (input() == 0)
		return (0);

	/* put occurring chars in heap with their counts */
	diffbytes = -1;
	count[END] = 1;
	insize.lint.lng = n = 0;
	for (i=END; i>=0; i--) {
		parent[i] = 0;
		if (count[i] > 0) {
			diffbytes++;
			insize.lint.lng += count[i];
			heap[++n].count = count[i];
			heap[n].node = i;
		}
	}
	if (diffbytes == 1) {
		printf (gettxt("pack:3", ": trivial file"));
		return (0);
	}
	insize.lint.lng >>= 1;
	for (i=n/2; i>=1; i--)
		heapify(i);

	/* build Huffman tree */
	lastnode = END;
	while (n > 1) {
		parent[heap[1].node] = ++lastnode;
		inc = heap[1].count;
		hmove (heap[n], heap[1]);
		n--;
		heapify(1);
		parent[heap[1].node] = lastnode;
		heap[1].node = lastnode;
		heap[1].count += inc;
		heapify(1);
	}
	parent[lastnode] = 0;

	/* assign lengths to encoding for each character */
	bitsout = maxlev = 0;
	for (i=1; i<=24; i++)
		levcount[i] = 0;
	for (i=0; i<=END; i++) {
		c = 0;
		for (p=parent[i]; p!=0; p=parent[p])
			c++;
		levcount[c]++;
		length[i] = c;
		if (c > maxlev)
			maxlev = c;
		bitsout += c*(count[i]>>1);
	}
	if (maxlev > 24) {
		/* can't occur unless insize.lint.lng >= 2**24 */
		printf (gettxt("pack:4", ": Huffman tree has too many levels"));
		return(0);
	}

	/* don't bother if no compression results */
	outsize = ((bitsout+7)>>3)+6+maxlev+diffbytes;
	if ((insize.lint.lng+8*BUFSIZ-1)/8*BUFSIZ <= (outsize+8*BUFSIZ-1)/8*BUFSIZ
	    && !force) {
		printf (gettxt("pack:5", ": no saving"));
		return(0);
	}

	/* compute bit patterns for each character */
	inc = 1L << 24;
	inc >>= maxlev;
	mask.lint.lng = 0;
	for (i=maxlev; i>0; i--) {
		for (c=0; c<=END; c++)
			if (length[c] == i) {
				bits[c] = mask.lint.lng;
				mask.lint.lng += inc;
			}
		mask.lint.lng &= ~inc;
		inc <<= 1;
	}

	return (output());
}

main(argc, argv)
int argc; char *argv[];
{
	register int i;
	register char *cp;
	int k, sep;
	int fcount =0; /* count failures */
	struct {
		time_t	actime;
		time_t modtime;
	} times;

	for (k=1; k<argc; k++) {
		if (argv[k][0] == '-' && argv[k][1] == '\0') {
			vflag = 1 - vflag;
			continue;
		}
		if (argv[k][0] == '-' && argv[k][1] == 'f') {
			force++;
			continue;
		}
		fcount++; /* increase failure count - expect the worst */
		printf (gettxt("colon:43", "%s: %s"), argv[0], argv[k]);
		sep = -1;  cp = filename;
		for (i=0; i < (MAXPATHLEN-3) && (*cp = argv[k][i]); i++)
			if (*cp++ == '/') sep = i;
		if (cp[-1]==SUF1 && cp[-2]==SUF0) {
			printf (gettxt("pack:6", ": already packed\n"));
			continue;
		}
		if (i >= (MAXPATHLEN-3) || (i-sep) > DYNIX_MAXNAMLEN) {
			printf (gettxt("pack:7", ": file name too long\n"));
			continue;
		}
		if ((infile = open (filename, 0)) < 0) {
			printf (gettxt("pack:8", ": cannot open\n"));
			continue;
		}
		fstat(infile,&status);
		if (status.st_mode&S_IFDIR) {
			printf (gettxt("pack:9", ": cannot pack a directory\n"));
			goto closein;
		}
		if (status.st_size == 0) {
			printf(gettxt("pack:10", ": cannot pack a zero length file\n"));
			goto closein;
		}
		if( status.st_nlink != 1 ) {
			printf(gettxt("pack:11", ": has links\n"));
			goto closein;
		}
		*cp++ = SUF0;  *cp++ = SUF1;  *cp = '\0';
		if( stat(filename, &ostatus) != -1) {
			printf(gettxt("pack:12", ".z: already exists\n"));
			goto closein;
		}
		if ((outfile = creat (filename, status.st_mode&07777)) < 0) {
			printf (gettxt("pack:13", ".z: cannot create\n"));
			goto closein;
		}
		if (chmod (filename, status.st_mode) != 0)
			printf(gettxt("pack:14", "can't change mode to %o\n"),
				status.st_mode);
		chown (filename, status.st_uid, status.st_gid);

		if (packfile()) {
			if (unlink(argv[k]) != 0)
				fprintf(stderr,
				    gettxt("pack:15", "%s: can't unlink %s\n"),
				    argv[0], argv[k]);
			fcount--;  /* success after all */
			printf (gettxt("pack:16", ": %.1f%% Compression\n"),
				((double)(-outsize+(insize.lint.lng))/(double)insize.lint.lng)*100);
			/* output statistics */
			if (vflag) {
				printf(gettxt("pack:17", "	from %ld to %ld bytes\n"),
				    insize.lint.lng, outsize);
				printf(gettxt("pack:18", "	Huffman tree has %d levels below root\n"), maxlev);
				printf(gettxt("pack:19", "	%d distinct bytes in input\n"),
				    diffbytes);
				printf(gettxt("pack:20", "	dictionary overhead = %ld bytes\n"),
				    dictsize);
				printf(gettxt("pack:21", "	effective  entropy  = %.2f bits/byte\n"),
					((double) outsize / (double) insize.lint.lng) * 8 );
				printf(gettxt("pack:22", "	asymptotic entropy  = %.2f bits/byte\n"), 
					((double) (outsize-dictsize) / (double) insize.lint.lng) * 8 );
			}
		}
		else
		{       printf (gettxt("pack:23", " - file unchanged\n"));
			unlink(filename);
		}

      closein:	close (outfile);
		close (infile);
		times.actime = status.st_atime;
		times.modtime = status.st_mtime;
		utime(filename, &times);/* preserve acc & mod times */
	}
	return (fcount);
}
