Relay-Version: version B 2.10 5/3/83; site utzoo.UUCP
Path: utzoo!hoptoad!mejac!decwrl!labrea!husc6!ddl
From: ddl@husc6.UUCP
Newsgroups: alt.sources
Subject: arc repost (sort of) 3/4
Message-ID: <2593@husc6.UUCP>
Date: Thu, 23-Jul-87 23:56:16 EDT
Article-I.D.: husc6.2593
Posted: Thu Jul 23 23:56:16 1987
Date-Received: Sat, 25-Jul-87 12:04:18 EDT
Organization: Harvard University Computer Services
Lines: 1377
Keywords: arc UnSquash

#! /bin/sh
# This is a shell archive, meaning:
# 1. Remove everything above the #! /bin/sh line.
# 2. Save the resulting text in a file.
# 3. Execute the file with /bin/sh (not csh) to create the files:
#	arcio.c
#	arcmisc.c
#	arcpack.c
#	arcrun.c
#	arcs.h
#	arcsq.c
# This archive created: Thu Jul 23 23:40:25 1987
export PATH; PATH=/bin:$PATH
if test -f 'arcio.c'
then
	echo shar: will not over-write existing file "'arcio.c'"
else
cat << \SHAR_EOF > 'arcio.c'
static char *RCSid = "$Header: arcio.c,v 1.2 86/07/15 07:53:11 turner Exp $";

/*
 * $Log:	arcio.c,v $
 * Hack-attack 1.3  86/12/20  01:23:45  wilhite@usceast.uucp
 * 	Bludgeoned into submission for VAX 11/780 BSD4.2
 *	(ugly code, but fewer core dumps)
 *
 * Revision 1.2  86/07/15  07:53:11  turner
 * 
 * 
 * Revision 1.1  86/06/26  15:00:21  turner
 * initial version
 * 
 * 
 */

/*  ARC - Archive utility - ARCIO

$define(tag,$$segment(@1,$$index(@1,=)+1))#
$define(version,Version $tag(
TED_VERSION DB =2.30), created on $tag(
TED_DATE DB =02/03/86) at $tag(
TED_TIME DB =22:56:00))#
$undefine(tag)#
    $version

(C) COPYRIGHT 1985 by System Enhancement Associates; ALL RIGHTS RESERVED

    By:  Thom Henderson

    Description:
         This file contains the file I/O routines used to manipulate
         an archive.

    Language:
         Computer Innovations Optimizing C86
*/
#include 
#include "arc.h"

INT readhdr(hdr,f)                     /* read a header from an archive */
struct heads *hdr;                     /* storage for header */
FILE *f;                               /* archive to read header from */
{
#if BSD | ST
        unsigned char dummy[28];
	INT i,j,k;
#endif
    char name[FNLEN];                  /* filename buffer */
    INT try = 0;                       /* retry counter */
    static INT first = 1;              /* true only on first read */

    if(!f)                             /* if archive didn't open */
         return 0;                     /* then pretend it's the end */
    if(feof(f))                        /* if no more data */
         return 0;                     /* then signal end of archive */

    if(fgetc(f)!=ARCMARK)             /* check archive validity */
    {    if(warn)
         {    printf("An entry in %s has a bad header.\n",arcname);
              nerrs++;
         }

         while(!feof(f))
         {    try++;
              if(fgetc(f)==ARCMARK)
              {    ungetc(hdrver=fgetc(f),f);
                   if(hdrver>=0 && hdrver<=ARCVER)
                        break;
              }
         }

         if(feof(f) && first)
              abort("%s is not an archive",arcname);

         if(warn)
              printf("  %d bytes skipped.\n",try);

         if(feof(f))
              return 0;
    }

    hdrver = fgetc(f);                 /* get header version */
    if(hdrver<0)
         abort("Invalid header in archive %s",arcname);
    if(hdrver==0)
         return 0;                     /* note our end of archive marker */
    if(hdrver>ARCVER)
    {    fread(name,sizeof(char),FNLEN,f);
         printf("I don't know how to handle file %s in archive %s\n",
              name,arcname);
         printf("I think you need a newer version of ARC.\n");
         exit(1);
    }

    /* amount to read depends on header type */

    if(hdrver==1)                      /* old style is shorter */
    {    fread(hdr,sizeof(struct heads)-sizeof(long),1,f);
         hdrver = 2;                   /* convert header to new format */
         hdr->length = hdr->size;      /* size is same when not packed */
    }
    else {
#if MSDOS
	fread(hdr,sizeof(struct heads),1,f);
#endif
#if BSD | ST
	fread(dummy,27,1,f);

	for(i=0;i<13;hdr->name[i]=dummy[i],i++);
	hdr->size = (long)((dummy[16]<<24) + (dummy[15]<<16) + (dummy[14]<<8)
	    + dummy[13]);
	hdr->date = (short)((dummy[18]<<8) + dummy[17]);
	hdr->time = (short)((dummy[20]<<8) + dummy[19]);
	hdr->crc  = (short)((dummy[22]<<8) + dummy[21]);
	hdr->length = (long)((dummy[26]<<24) + (dummy[25]<<16)
	    + (dummy[24]<<8) + dummy[23]);
#endif
    }

    first = 0; return 1;               /* we read something */
}

INT writehdr(hdr,f)                        /* write a header to an archive */
struct heads *hdr;                     /* header to write */
FILE *f;                               /* archive to write to */
{
    unsigned char dummy[28];

    fputc(ARCMARK,f);                 /* write out the mark of ARC */
    fputc(hdrver,f);                   /* write out the header version */
    if(!hdrver)                        /* if that's the end */
         return;                       /* then write no more */
#if MSDOS
    fwrite(hdr,sizeof(struct heads),1,f);
#endif
#if BSD | ST
/*
 * put out the hdr in the brain damaged unaligned half back *sswards
 * way HAL does it
 */
    fwrite(hdr->name,1,13,f);
    fwrite(&hdr->size,sizeof(long),1,f);
    fwrite(&hdr->date,sizeof(INT),1,f);
    fwrite(&hdr->time,sizeof(INT),1,f);
    fwrite(&hdr->crc ,sizeof(INT),1,f);
    fwrite(&hdr->length,sizeof(long),1,f);
#endif

    /* note the newest file for updating the archive timestamp */

    if(hdr->date>arcdate
    ||(hdr->date==arcdate && hdr->time>arctime))
    {    arcdate = hdr->date;
         arctime = hdr->time;
    }
}

INT filecopy(f,t,size)                     /* bulk file copier */
FILE *f, *t;                           /* from, to */
long size;                             /* number of bytes */
{
 INT len;                           /* length of a given copy */
 INT putc_tst();

    while(size--)                      /* while more bytes to move */
         putc_tst(fgetc(f),t);
}

INT putc_tst(c,t)                          /* put a character, with tests */
char c;                                /* character to output */
FILE *t;                               /* file to write to */
{
    if(t)
#if MSODS | ST
         if(fputc(c,t)==EOF)
              abort("Write fail (disk full?)");
#endif
#if BSD
/*
 * for reasons beyond me BSD unix returns EOF 
 */
	fputc(c,t);
#endif
}
SHAR_EOF
chmod +x 'arcio.c'
fi # end of overwriting check
if test -f 'arcmisc.c'
then
	echo shar: will not over-write existing file "'arcmisc.c'"
else
cat << \SHAR_EOF > 'arcmisc.c'
#include 
#include "arc.h"

/*	split up a file name (subroutine for makefnam)
 *
 * Hack-attack 1.3  86/12/20  01:23:45  wilhite@usceast.uucp
 * 	Bludgeoned into submission for VAX 11/780 BSD4.2
 *	(ugly code, but fewer core dumps)
*/

static INT _makefn(source,dest)
unsigned char *source;
unsigned char *dest;
{
 INT j;

    setmem (dest, 17, 0);	/* clear result field */
    if (strlen (source) > 1 && source[1] == ':')
	for (j = 0; j < 2;)
	    dest[j++] = *source++;
    for (j = 3; *source && *source != '.'; ++source)
	if (j < 11)
	    dest[j++] = *source;
    for (j = 12; *source; ++source)
	if (j < 16)
	    dest[j++] = *source;
}
/*	make a file name using a template
*/

char *makefnam(rawfn,template,result)
unsigned char *rawfn;			/* the original file name */
unsigned char *template;		/* the template data */
unsigned char *result;			/* where to place the result */
{
  unsigned char et[17],er[17];

  _makefn(template,et);
  _makefn(rawfn,er);
  *result=0;			/* assure no data */
  strcat(result,er[0]?er:et);
  strcat(result,er[3]?er+3:et+3);
  strcat(result,er[12]?er+12:et+12);
  return ((char *)&result[0]);
}

INT freedir(dirs)
register struct direct **dirs;
{
	register INT ii;

	if(dirs == (struct direct **)0)
		return(-1);
	for(ii = 0; dirs[ii] != (struct direct *)0; ii++)
		free(dirs[ii]);
	free(dirs);
	return(0);
}

#if MSDOS
#include 

INT alphasort(dirptr1, dirptr2)
struct direct **dirptr1, **dirptr2;
{
	return(strcmp((*dirptr1)->d_name, (*dirptr2)->d_name));
}

#endif
SHAR_EOF
chmod +x 'arcmisc.c'
fi # end of overwriting check
if test -f 'arcpack.c'
then
	echo shar: will not over-write existing file "'arcpack.c'"
else
cat << \SHAR_EOF > 'arcpack.c'
static char *RCSid = "$Header: arcpack.c,v 1.2 86/07/15 07:53:48 turner Exp $";

/*
 * $Log:	arcpack.c,v $
 * Hack-attack 1.3  86/12/20  01:23:45  wilhite@usceast.uucp
 * 	Bludgeoned into submission for VAX 11/780 BSD4.2
 *	(ugly code, but fewer core dumps)
 *
 * Revision 1.2  86/07/15  07:53:48  turner
 * 
 * 
 * Revision 1.1  86/06/26  15:00:37  turner
 * initial version
 * 
 * 
 */

/*  ARC - Archive utility - ARCPACK

$define(tag,$$segment(@1,$$index(@1,=)+1))#
$define(version,Version $tag(
TED_VERSION DB =3.37), created on $tag(
TED_DATE DB =02/03/86) at $tag(
TED_TIME DB =22:58:01))#
$undefine(tag)#
    $version

(C) COPYRIGHT 1985 by System Enhancement Associates; ALL RIGHTS RESERVED

    By:  Thom Henderson

    Description:
         This file contains the routines used to compress a file
         when placing it in an archive.

    Language:
         Computer Innovations Optimizing C86
*/
#include 
#include "arc.h"

/* stuff for non-repeat packing */

#define DLE 0x90                       /* repeat sequence marker */

static unsigned char state;            /* current packing state */

/* non-repeat packing states */

#define NOHIST  0                      /* don't consider previous input*/
#define SENTCHAR 1                     /* lastchar set, no lookahead yet */
#define SENDNEWC 2                     /* run over, send new char next */
#define SENDCNT 3                      /* newchar set, send count next */

/* packing results */

static long stdlen;                    /* length for standard packing */
static INT crcval;                     /* CRC check value */

INT pack(f,t,hdr)                          /* pack file into an archive */
FILE *f, *t;                           /* source, destination */
struct heads *hdr;                     /* pointer to header data */
{
 INT c;                             /* one character of stream */
    long ncrlen;                       /* length after packing */
    long huflen;                       /* length after squeezing */
    long lzwlen;                       /* length after crunching */
    long pred_sq(), file_sq();         /* stuff for squeezing */
    long pred_cm(), sqpred_cm();       /* dynamic crunching cleanup */
    char tnam[STRLEN];                /* temporary name buffer */
    char *makefnam();                  /* filename fixer upper */
    FILE *crn = NULL;                  /* temporary crunch file */
    INT getch();
    INT getc_ncr();
    INT putc_pak();

    /* first pass - see which method is best */

    if(!nocomp)                        /* if storage kludge not active */
    {    if(note)
            { printf(" analyzing, "); fflush(stdout);}

         if(arctemp)                   /* use temp area if specified */
              sprintf(tnam,"%s.CRN",arctemp);
         else makefnam("$ARCTEMP.CRN",arcname,tnam);
#if MSDOS
         crn = fopen(tnam,"wrb");
#endif
#if BSD | ST
         crn = fopen(tnam,"w+");
#endif
         state = NOHIST;               /* initialize ncr packing */
         stdlen =  ncrlen = 0;         /* reset size counters */
         crcval = 0;                   /* initialize CRC check value */
         setcode();                    /* initialize encryption */

	 if(dosquash)
         sqinit_cm(f,crn);
	 else
         init_cm(f,crn);               /* initialize for crunching */
         init_sq();                    /* initialize for squeeze scan */

	 if(dosquash)
         while((c=getch(f))!=EOF)   /* for each byte of file */
         {    ncrlen++;                /* one more packed byte */
              scan_sq(c);              /* see what squeezing can do */
              sqputc_cm(c,crn);          /* see what crunching can do */
         }
         else
         while((c=getc_ncr(f))!=EOF)   /* for each byte of file */
         {    ncrlen++;                /* one more packed byte */
              scan_sq(c);              /* see what squeezing can do */
              putc_cm(c,crn);          /* see what crunching can do */
         }
         huflen = pred_sq();           /* finish up after squeezing */
	 if(dosquash)
         lzwlen = sqpred_cm(crn);
	 else
         lzwlen = pred_cm(crn);        /* finish up after crunching */
    }
    else                               /* else kludge the method */
    {    stdlen = 0;                   /* make standard look best */
         ncrlen = huflen = lzwlen = 1;
    }

    /* standard set-ups common to all methods */

    fseek(f,0L,0);                     /* rewind input */
    hdr->crc = crcval;                 /* note CRC check value */
    hdr->length = stdlen;              /* set actual file length */
    state = NOHIST;                    /* reinitialize ncr packing */
    setcode();                         /* reinitialize encryption */

    /* choose and use the shortest method */

    if(stdlen<=ncrlen && stdlen<=huflen && stdlen<=lzwlen)
    {    if(kludge)                    /*DEBUG*/
              printf("(%ld) ",lzwlen-stdlen);
         if(note)
          { printf("storing, "); fflush(stdout);}/* store w/out compression */
         hdrver = 2;                   /* note packing method */
         stdlen = crcval = 0;          /* recalc these for kludge */
         while((c=getch(f))!=EOF)      /* store it straight */
              putc_pak(c,t);
         hdr->crc = crcval;
         hdr->length = hdr->size = stdlen;
    }

    else if(ncrlensize = ncrlen;           /* set data length */
         while((c=getc_ncr(f))!=EOF)
              putc_pak(c,t);
    }

    else if(huflensize = file_sq(f,t);     /* note final size */
    }

    else
    {    if(kludge)                    /*DEBUG*/
              printf("(%ld) ",huflen-lzwlen);
         if(note)
            { printf(dosquash ? "squashing, " : "crunching, "); fflush(stdout);}
         hdrver = dosquash ? 9 : 8;
         hdr->size = lzwlen;           /* size should not change */
         if(crn)                       /* if temp was created */
         {    fseek(crn,0L,0);         /* then copy over crunched temp */
              while((c=fgetc(crn))!=EOF)
                   putc_tst(c,t);
         }
         else                          /* else re-crunch */
         {    if(dosquash)
		sqinit_cm(f, t);
	      else
		init_cm(f,t);
	   if(dosquash)
              while((c=getc_ncr(f))!=EOF)
			putc_cm(c,t);
	   else
              while((c=getch(f))!=EOF)
			sqputc_cm(c,t);
	      if(dosquash)
		sqpred_cm(t);
	      else
		pred_cm(t);              /* finish up after crunching */
         }
    }

    /* standard cleanups common to all methods */

    if(crn)                            /* get rid of crunch temporary */
    {    fclose(crn);
         if(unlink(tnam) && warn)
         {    printf("Cannot delete temporary file %s\n",tnam);
              nerrs++;
         }
    }
    if(note)
         printf("done.\n");
}

/*  Non-repeat compression - text is passed through normally, except that
    a run of more than two is encoded as:

           

    Special case: a count of zero indicates that the DLE is really a DLE,
    not a repeat marker.
*/

INT getc_ncr(f)                        /* get bytes with collapsed runs */
FILE *f;                               /* file to get from */
{
    static INT lastc;                  /* value returned on last call */
    static INT repcnt;                 /* repetition counter */
    static INT c;                      /* latest value seen */

    switch(state)                      /* depends on our state */
    {
    case NOHIST:                       /* no relevant history */
         state = SENTCHAR;
         return lastc = getch(f);      /* remember the value next time */

    case SENTCHAR:                     /* char was sent. look ahead */
         switch(lastc)                 /* action depends on char */
         {
         case DLE:                     /* if we sent a real DLE */
              state = NOHIST;          /* then start over again */
              return 0;                /* but note that the DLE was real */

         case EOF:                     /* EOF is always a special case */
              return EOF;

         default:                      /* else test for a repeat */
              for(repcnt=1; (c=getch(f))==lastc && repcnt<255; repcnt++)
                   ;                   /* find end of run */

              switch(repcnt)           /* action depends on run size */
              {
              case 1:                  /* not a repeat */
                   return lastc = c;   /* but remember value next time */

              case 2:                  /* a repeat, but too short */
                   state = SENDNEWC;   /* send the second one next time */
                   return lastc;

              default:                 /* a run - compress it */
                   state = SENDCNT;    /* send repeat count next time */
                   return DLE;         /* send repeat marker this time */
              }
         }

    case SENDNEWC:                     /* send second char of short run */
         state = SENTCHAR;
         return lastc = c;

    case SENDCNT:                      /* sent DLE, now send count */
         state = SENDNEWC;
         return repcnt;

    default:
         abort("Bug - bad ncr state\n");
    }
}

static INT getch(f)                    /* special get char for packing */
FILE *f;                               /* file to get from */
{
 INT c;                             /* a char from the file */

    if((c=fgetc(f))!=EOF)              /* if not the end of file */
    {    crcval = addcrc(crcval,c);    /* then update CRC check value */
         stdlen++;                     /* and bump length counter */
    }

    return c;
}

INT putc_pak(c,f)                          /* put a packed byte into archive */
char c;                                /* byte to put */
FILE *f;                               /* archive to put it in */
{
    putc_tst(code(c),f);               /* put encoded byte, with checks */
}
SHAR_EOF
chmod +x 'arcpack.c'
fi # end of overwriting check
if test -f 'arcrun.c'
then
	echo shar: will not over-write existing file "'arcrun.c'"
else
cat << \SHAR_EOF > 'arcrun.c'
static char *RCSid = "$Header: arcrun.c,v 1.2 86/07/15 07:53:55 turner Exp $";

/*
 * $Log:	arcrun.c,v $
 * Hack-attack 1.3  86/12/20  01:23:45  wilhite@usceast.uucp
 * 	Bludgeoned into submission for VAX 11/780 BSD4.2
 *	(ugly code, but fewer core dumps)
 *
 * Revision 1.2  86/07/15  07:53:55  turner
 * 
 * 
 * Revision 1.1  86/06/26  15:00:40  turner
 * initial version
 * 
 * 
 */

/*  ARC - Archive utility - ARCRUN

$define(tag,$$segment(@1,$$index(@1,=)+1))#
$define(version,Version $tag(
TED_VERSION DB =1.17), created on $tag(
TED_DATE DB =02/03/86) at $tag(
TED_TIME DB =22:59:06))#
$undefine(tag)#
    $version

(C) COPYRIGHT 1985 by System Enhancement Associates; ALL RIGHTS RESERVED

    By:  Thom Henderson

    Description:
         This file contains the routines used to "run" a file
         which is stored in an archive.  At present, all we really do
         is (a) extract a temporary file, (b) give its name as a system
         command, and then (c) delete the file.

    Language:
         Computer Innovations Optimizing C86
*/
#include 
#include "arc.h"

INT runarc(num,arg)                        /* run file from archive */
INT num;                               /* number of arguments */
char *arg[];                           /* pointers to arguments */
{
    struct heads hdr;                  /* file header */
 INT run;                           /* true to run current file */
 INT did[MAXARG];                  /* true when argument was used */
 INT n;                             /* index */
    char *makefnam();                  /* filename fixer */
    char buf[STRLEN];                 /* filename buffer */
    FILE *fopen();                     /* file opener */
    INT runfile();

    for(n=0; nname,buf); */
    sprintf(buf,"%s.RUN",arctemp);

/*  if(!strcmp(buf,"$ARCTEMP.BAS"))
 *       strcpy(sys,"BASICA $ARCTEMP");
 *
 *  else if(!strcmp(buf,"$ARCTEMP.BAT")
 *       || !strcmp(buf,"$ARCTEMP.COM")
 *       || !strcmp(buf,"$ARCTEMP.EXE"))
 *       strcpy(sys,"$ARCTEMP");
 *
 *  else
 *  {    if(warn)
 *       {    printf("File %s is not a .BAS, .BAT, .COM, or .EXE\n",
 *                 hdr->name);
 *            nerrs++;
 *       }
 *       fseek(arc,hdr->size,1);
 *       return;
 *  }
 */

    if(warn)
         if(tmp=fopen(buf,"r"))
              abort("Temporary file %s already exists",buf);
    if(!(tmp=fopen(buf,"w")))
         abort("Unable to create temporary file %s",buf);

    if(note)
         printf("Invoking file: %s\n",hdr->name);

    dir = gcdir("");                   /* see where we are */
    unpack(arc,tmp,hdr);               /* unpack the entry */
    fclose(tmp);                       /* release the file */
    chmod(buf,"700");                  /* make it exec'able */
    system(buf);                       /* try to invoke it */
    chdir(dir); free(dir);             /* return to whence we started */
    if(unlink(buf) && warn)
    {    printf("Cannot unsave temporary file %s\n",buf);
         nerrs++;
    }
}
SHAR_EOF
chmod +x 'arcrun.c'
fi # end of overwriting check
if test -f 'arcs.h'
then
	echo shar: will not over-write existing file "'arcs.h'"
else
cat << \SHAR_EOF > 'arcs.h'
/*
 * $Header: arcs.h,v 1.2 86/07/15 07:54:02 turner Exp $
 */

/*
 * $Log:	arcs.h,v $
 * Revision 1.2  86/07/15  07:54:02  turner
 * 
 * 
 * Revision 1.1  86/06/26  15:01:27  turner
 * initial version
 * 
 * 
 */

/*  ARC - Archive utility - Archive file header format

    Version 2.12, created on 12/17/85 at 14:40:26

(C) COPYRIGHT 1985 by System Enhancement Associates; ALL RIGHTS RESERVED

    By:  Thom Henderson

    Description:
         This file defines the format of an archive file header, excluding
         the archive marker and the header version number.

         Each entry in an archive begins with a one byte archive marker,
         which is set to 26.  The marker is followed by a one byte
         header type code, from zero to 7.

         If the header type code is zero, then it is an end marker, and
         no more data should be read from the archive.

         If the header type code is in the range 2 to 7, then it is
         followed by a standard archive header, which is defined below.

         If the header type code is one, then it is followed by an older
         format archive header.  The older format header does not contain
         the true length.  A header should be read for a length of
         sizeof(struct heads)-sizeof(long).  Then set length equal to size
         and change the header version to 2.

    Programming note:
         The crc value given in the header is based on the unpacked data.

    Language:
         Computer Innovations Optimizing C86
*/

struct heads                           /* archive entry header format */
{   char name[FNLEN];                 /* file name */
    long size;                         /* size of file, in bytes */
    unsigned INT date;                 /* creation date */
    unsigned INT time;                 /* creation time */
 INT crc;                           /* cyclic redundancy check */
    long length;                       /* true file length */
}   ;
SHAR_EOF
chmod +x 'arcs.h'
fi # end of overwriting check
if test -f 'arcsq.c'
then
	echo shar: will not over-write existing file "'arcsq.c'"
else
cat << \SHAR_EOF > 'arcsq.c'
static char *RCSid = "$Header: arcsq.c,v 1.2 86/07/15 07:54:05 turner Exp $";

/*
 * $Log:	arcsq.c,v $
 * Hack-attack 1.3  86/12/20  01:23:45  wilhite@usceast.uucp
 * 	Bludgeoned into submission for VAX 11/780 BSD4.2
 *	(ugly code, but fewer core dumps)
 *
 * Revision 1.2  86/07/15  07:54:05  turner
 * 
 * 
 * Revision 1.1  86/06/26  15:00:48  turner
 * initial version
 * 
 * 
 */

/*  ARC - Archive utility - ARCSQ

$define(tag,$$segment(@1,$$index(@1,=)+1))#
$define(version,Version $tag(
TED_VERSION DB =3.10), created on $tag(
TED_DATE DB =01/30/86) at $tag(
TED_TIME DB =20:10:46))#
$undefine(tag)#
    $version

(C) COPYRIGHT 1985 by System Enhancement Associates; ALL RIGHTS RESERVED

    By:  Thom Henderson

    Description:
         This file contains the routines used to squeeze a file
         when placing it in an archive.

    Language:
         Computer Innovations Optimizing C86

    Programming notes:
         Most of the routines used for the Huffman squeezing algorithm
         were lifted from the SQ program by Dick Greenlaw, as adapted
         to CI-C86 by Robert J. Beilstein.
*/
#include 
#include "arc.h"

/* stuff for Huffman squeezing */

#define TRUE 1
#define FALSE 0
#define ERROR (-1)
#define SPEOF 256                      /* special endfile token */
#define NOCHILD (-1)                   /* marks end of path through tree */
#define NUMVALS 257                    /* 256 data values plus SPEOF*/
#define NUMNODES (NUMVALS+NUMVALS-1)   /* number of nodes */
#define MAXCOUNT (unsigned INT) 65535      /* biggest unsigned integer */

/* The following array of structures are the nodes of the
   binary trees. The first NUMVALS nodes become the leaves of the
   final tree and represent the values of the data bytes being
   encoded and the special endfile, SPEOF.
   The remaining nodes become the internal nodes of the final tree.
*/

struct nd                              /* shared by unsqueezer */
{   unsigned INT weight;                   /* number of appearances */
 INT tdepth;                        /* length on longest path in tree */
 INT lchild, rchild;                /* indices to next level */
}   node[NUMNODES];                    /* use large buffer */

static INT dctreehd;                   /* index to head of final tree */

/* This is the encoding table:
   The bit strings have first bit in low bit.
   Note that counts were scaled so code fits unsigned integer.
*/

static INT codelen[NUMVALS];           /* number of bits in code */
static unsigned INT code[NUMVALS];         /* code itself, right adjusted */
static unsigned INT tcode;                 /* temporary code value */
static long valcount[NUMVALS];         /* actual count of times seen */

/* Variables used by encoding process */

static INT curin;                      /* value currently being encoded */
static INT cbitsrem;                   /* # of code string bits left */
static unsigned INT ccode;                 /* current code right justified */

INT init_sq()                              /* prepare for scanning pass */
{
 INT i;                             /* node index */

    /* Initialize all nodes to single element binary trees
       with zero weight and depth.
    */

    for(i=0; i 16 bits long.
         */
    }    while(buildenc(0,dctreehd) == ERROR);

    /* Initialize encoding variables */

    cbitsrem = 0;                      /* force initial read */
    curin = 0;                         /* anything but endfile */

    for(i=0; i (ceil-sum))
                   ++ovflw;
              sum += node[i].weight;
         }

         divisor = ovflw + 1;

         /* Ensure no non-zero values are lost */

         increased = FALSE;
         for(i=0; i1)
         for(i=0; i=0; --i)
         adjust(list,i,length-1);
}

/* Make a heap from a heap with a new top */

static INT adjust(list,top,bottom)
INT list[], top, bottom;
{
    register INT k, temp;
    INT cmptrees();

    k = 2 * top + 1;                   /* left child of top */
    temp = list[top];                  /* remember root node of top tree */

    if(k<=bottom)
    {    if(k b return true, else return false.
   Note comparison rules in previous comments.
*/

static INT cmptrees(a,b)
INT a, b;                              /* root nodes of trees */
{
    if(node[a].weight > node[b].weight)
         return TRUE;
    if(node[a].weight == node[b].weight)
         if(node[a].tdepth > node[b].tdepth)
              return TRUE;
    return FALSE;
}

/* HUFFMAN ALGORITHM: develops the single element trees
   into a single binary tree by forming subtrees rooted in
   interior nodes having weights equal to the sum of weights of all
   their descendents and having depth counts indicating the
   depth of their longest paths.

   When all trees have been formed into a single tree satisfying
   the heap property (on weight, with depth as a tie breaker)
   then the binary code assigned to a leaf (value to be encoded)
   is then the series of left (0) and right (1)
   paths leading from the root to the leaf.
   Note that trees are removed from the heaped list by
   moving the last element over the top element and
   reheaping the shorter list.
*/

static INT bld_tree(list,len)
INT list[];
INT len;
{
    register INT freenode;             /* next free node in tree */
    register struct nd *frnp;          /* free node pointer */
 INT lch, rch;                      /* temps for left, right children */
 INT i;
    INT maxchar();

    /* Initialize index to next available (non-leaf) node.
       Lower numbered nodes correspond to leaves (data values).
    */

    freenode = NUMVALS;

    while(len>1)
    {    /* Take from list two btrees with least weight
            and build an interior node pointing to them.
            This forms a new tree.
         */

         lch = list[0];                /* This one will be left child */

         /* delete top (least) tree from the list of trees */

         list[0] = list[--len];
         adjust(list,0,len-1);

         /* Take new top (least) tree. Reuse list slot later */

         rch = list[0];                /* This one will be right child */

         /* Form new tree from the two least trees using
            a free node as root. Put the new tree in the list.
         */

         frnp = &node[freenode];       /* address of next free node */
         list[0] = freenode++;         /* put at top for now */
         frnp->lchild = lch;
         frnp->rchild = rch;
         frnp->weight = node[lch].weight + node[rch].weight;
         frnp->tdepth = 1 + maxchar(node[lch].tdepth, node[rch].tdepth);

         /* reheap list  to get least tree at top */

         adjust(list,0,len-1);
    }
    dctreehd = list[0];                /* head of final tree */
}

static INT maxchar(a,b)
{
    return a>b ? a : b;
}

static INT init_enc()
{
    register INT i;

    /* Initialize encoding table */

    for(i=0; i> (16-level));
         return (level>16) ? ERROR : NULL;
    }

    else
    {    if(l!=NOCHILD)
         {    /* Clear path bit and continue deeper */

              tcode &= ~(1 << level);
              if(buildenc(level+1,l)==ERROR)
                   return ERROR;       /* pass back bad statuses */
         }
         if(r!=NOCHILD)
         {    /* Set path bit and continue deeper */

              tcode |= 1 << level;
              if(buildenc(level+1,r)==ERROR)
                   return ERROR;       /* pass back bad statuses */
         }
    }
    return NULL;                       /* it worked if we reach here */
}

static INT put_int(n,f)                    /* output an integer */
INT n;                                 /* integer to output */
FILE *f;                               /* file to put it to */
{
    putc_pak(n&0xff,f);                /* first the low byte */
    putc_pak(n>>8,f);                  /* then the high byte */
}

/* Write out the header of the compressed file */

static long wrt_head(ob)
FILE *ob;
{
    register INT l,r;
 INT i, k;
 INT numnodes;                      /* # of nodes in simplified tree */

    /* Write out a simplified decoding tree. Only the interior
       nodes are written. When a child is a leaf index
       (representing a data value) it is recoded as
       -(index + 1) to distinguish it from interior indexes
       which are recoded as positive indexes in the new tree.

       Note that this tree will be empty for an empty file.
    */

    numnodes = dctreehd=need)                 /* if current code is big enough */
    {    if(need==0)
              return rbyte;

         rbyte |= ccode << (8-need);   /* take what we need */
         ccode >>= need;               /* and leave the rest */
         cbitsrem -= need;
         return rbyte & 0xff;
    }

    /* We need more than current code */

    if(cbitsrem>0)
    {    rbyte |= ccode << (8-need);   /* take what there is */
         need -= cbitsrem;
    }

    /* No more bits in current code string */

    if(curin==SPEOF)
    {    /* The end of file token has been encoded. If
            result byte has data return it and do EOF next time.
         */

         cbitsrem = 0;
         return (need==8) ? EOF : rbyte + 0;
    }

    /* Get an input byte */

    if((curin=getc_ncr(ib)) == EOF)
         curin = SPEOF;                /* convenient for encoding */

    ccode = code[curin];               /* get the new byte's code */
    cbitsrem = codelen[curin];

    goto loop;
}

/*  This routine is used to perform the actual squeeze operation.  It can
    only be called after the file has been scanned.  It returns the true
    length of the squeezed entry.
*/

long file_sq(f,t)                      /* squeeze a file into an archive */
FILE *f;                               /* file to squeeze */
FILE *t;                               /* archive to receive file */
{
 INT c;                             /* one byte of squeezed data */
    long size;                         /* size after squeezing */

    size = wrt_head(t);                /* write out the decode tree */

    while((c=gethuff(f))!=EOF)
    {    putc_pak(c,t);
         size++;
    }

    return size;                       /* report true size */
}
SHAR_EOF
chmod +x 'arcsq.c'
fi # end of overwriting check
#	End of shell archive
exit 0