[comp.os.os9] OS-9 Discussions, V3 #7

os9@cbdkc1.UUCP (05/25/87)

OS-9 Discussions         Monday, May 25th 1987         Volume 3 : Issue 7

Today's Topics:
                        OS/9 68K "arc" - 3 of 3

[ I would like to thank Jim O for taking the time to submit this useful
 utility!  Note that it was repackaged into 3 shar files. - JDD ]
--------------------------------------------------------------------------

Date: Sun, 24 May 87 18:43:06 EDT
From: mnetor!lsuc!jimomura
Subject: OS/9 68K "arc" - 3 of 3

87/05/24
 
     This is Dieter Stoll's port of ARC from the MS-DOS version to
OS-9 68K.  It is posted to Usenet with the permission of Systems
Enhancements Associates.  If you wish to port ARC to another system
or wish to re-distribute ARC, you should contact them for approval.
I have found them to be quite reasonable.
 
Cheers! -- Jim O.
 

# This is a shell archive.  Remove anything before this line, then
# unpack it by saving it in a file and typing "sh file".  (Files
# unpacked will be owned by you and have default permissions.)
#
# This archive contains:
# README arcmatch.c arcpack.c arcsq.c arcsvc.c arctst.c arcunp.c arcusq.c system.c

echo x - README
cat > "README" << '//E*O*F README//'
87/05/24
 
     This is Dieter Stoll's port of ARC from the MS-DOS version to
OS-9 68K.  It is posted to Usenet with the permission of Systems
Enhancements Associates.  If you wish to port ARC to another system
or wish to re-distribute ARC, you should contact them for approval.
I have found them to be quite reasonable.
 
Cheers! -- Jim O.
//E*O*F README//

echo x - arcmatch.c
cat > "arcmatch.c" << '//E*O*F arcmatch.c//'
/*  ARC - Archive utility - ARCMATCH

$define(tag,$$segment(@1,$$index(@1,=)+1))#
$define(version,Version $tag(
TED_VERSION DB =2.17), created on $tag(
TED_DATE DB =12/17/85) at $tag(
TED_TIME DB =20:32:18))#
$undefine(tag)#
    $version

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

    By:  Thom Henderson

    Description:
         This file contains service routines needed to maintain an archive.

    Language:
         Computer Innovations Optimizing C86
*/
#include <stdio.h>
#define EXTERN extern
#include "arc.h"

int match(n,t)                         /* test name against template */
char *n;                               /* name to test */
char *t;                               /* template to test against */
{
    upper(n); upper(t);                /* avoid case problems */

    /* first match name part */

    while((*n && *n!='.') || (*t && *t!='.'))
    {    if(*n!=*t && *t!='?')         /* match fail? */
         {    if(*t!='*')              /* wildcard fail? */
                   return 0;           /* then no match */
              else                     /* else jump over wildcard */
              {    while(*n && *n!='.')
                        n++;
                   while(*t && *t!='.')
                        t++;
                   break;              /* name part matches wildcard */
              }
         }
         else                          /* match good for this char */
         {    n++;                     /* advance to next char */
              t++;
         }
    }

    if(*n && *n=='.') n++;             /* skip extension delimiters */
    if(*t && *t=='.') t++;

    /* now match name part */

    while(*n || *t)
    {    if(*n!=*t && *t!='?')         /* match fail? */
         {    if(*t!='*')              /* wildcard fail? */
                   return 0;           /* then no match */
              else return 1;           /* else good enough */
         }
         else                          /* match good for this char */
         {    n++;                     /* advance to next char */
              t++;
         }
    }

    return 1;                          /* match worked */
}

rempath(nargs,arg)                     /* remove paths from filenames */
int nargs;                             /* number of names */
char *arg[];                           /* pointers to names */
{
    char *i, *rindex();                /* string index, reverse indexer */
    int n;                             /* index */

    for(n=0; n<nargs; n++)             /* for each supplied name */
    {    if(!(i=rindex(arg[n],'\\')))  /* search for end of path */
              if(!(i=rindex(arg[n],'/')))
                   i=rindex(arg[n],':');
         if(i)                         /* if path was found */
              arg[n] = i+1;            /* then skip it */
    }
}
//E*O*F arcmatch.c//

echo x - arcpack.c
cat > "arcpack.c" << '//E*O*F arcpack.c//'

/*  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
*
*	changed abort(..) to exit(_errmsg(1,...))
*/
#include <stdio.h>
#define EXTERN extern
#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 */

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();                    /* dynamic crunching cleanup */
    char tnam[STRLEN];                /* temporary name buffer */
    char *makefnam();                  /* filename fixer upper */
    FILE *crn = NULL;                  /* temporary crunch file */

    /* first pass - see which method is best */
#ifdef DEBUG
	puts ("pack");
#endif

    if(!nocomp)                        /* if storage kludge not active */
    {    if(note)
		{
              printf(" analyzing, ");
				fflush (stdout);
		}
#ifdef DEBUG
		puts ("arcpack: !nocomp");
#endif
         if(arctemp)                   /* use temp area if specified */
#ifndef OSK
              sprintf(tnam,"%s$ARCTEMP.CRN",arctemp);
#else
/*
 *	for OS-9, append '/' after the TEMP path name
 */
				sprintf(tnam,"%s/$ARCTEMP.CRN",arctemp);
#endif
         else makefnam("$ARCTEMP.CRN",arcname,tnam);
#ifdef DEBUG
		printf ("arcpack: opening %s RWBIN\n",tnam);
#endif
         crn = fopen(tnam,RWBIN);

         state = NOHIST;               /* initialize ncr packing */
         stdlen =  ncrlen = 0;         /* reset size counters */
         crcval = 0;                   /* initialize CRC check value */
         setcode();                    /* initialize encryption */
#ifdef DEBUG
		puts ("arcpack back from setcode");
#endif
         init_cm(f,crn);               /* initialize for crunching */
#ifdef DEBUG
		puts ("arcpack back from init_cm");
#endif

         init_sq();                  /* initialize for squeeze scan */
#ifdef DEBUG
		puts ("arcpack back from init_sq");
#endif
	  
   	     while((c=getc_ncr(f))!=EOF)   /* for each byte of file */
       	 {    ncrlen++;                /* one more packed byte */
#ifdef OSK
				if (!ZivLempel)
#endif
	            	  scan_sq(c);              /* see what squeezing can do */
	              putc_cm(c,crn);          /* see what crunching can do */
    	     }
#ifdef DEBUG
			puts ("arcpack before pred_sq()");
#endif
    	     huflen = pred_sq();           /* finish up after squeezing */
#ifdef DEBUG
			puts ("arcpack before pred_cm()");
#endif
      	   lzwlen = pred_cm(crn);        /* finish up after crunching */
#ifdef OSK
/*
 *	if unconditional ZivLempel desired, fake Huffman length
 */
			if (ZivLempel)
				huflen = 2 * lzwlen;
#endif
#ifdef DEBUG
			printf ("arcpack: done analyzing.\n");
			printf ("huflen: %d  lzwlen: %d\n",huflen, lzwlen);
#endif
    }
    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 */
#ifdef DEBUG
	printf ("arcpack: just before doing it\n");
#endif

    /* choose and use the shortest method */
		
    if(stdlen<=ncrlen && stdlen<=huflen && stdlen<=lzwlen)
    {    if(kludge)                    /*DEBUG*/
              printf("(%ld) ",lzwlen-stdlen);
         if(note)
              printf("storing, ");     /* store without compression */
		fflush (stdout);
         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(ncrlen<huflen && ncrlen<lzwlen)
    {    if(kludge)                    /*DEBUG*/
              printf("(%ld) ",lzwlen-ncrlen);
         if(note)
              printf("packing, ");     /* pack with repeat suppression */
		fflush (stdout);
	         hdrver = 3;                   /* note packing method */
         hdr->size = ncrlen;           /* set data length */
         while((c=getc_ncr(f))!=EOF)
              putc_pak(c,t);
    }

    else if(huflen<lzwlen)
    {    if(kludge)                    /*DEBUG*/
              printf("(%ld) ",lzwlen-huflen);
         if(note)
              printf("squeezing, ");
		fflush (stdout);
         hdrver = 4;                   /* note packing method */
         hdr->size = file_sq(f,t);     /* note final size */
    }

    else
    {    if(kludge)                    /*DEBUG*/
              printf("(%ld) ",huflen-lzwlen);
         if(note)
              printf("crunching, ");
		fflush (stdout);
         hdrver = 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 */
         {    init_cm(f,t);
              while((c=getc_ncr(f))!=EOF)
                   putc_cm(c,t);
              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:

         <char> <DLE> <count>

    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:
         exit (_errmsg(1,"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;
}

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 */
}

//E*O*F arcpack.c//

echo x - arcsq.c
cat > "arcsq.c" << '//E*O*F arcsq.c//'
/*  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.
*/

#ifdef OSK
#define UWORD unsigned short
/*
 *	WORD is typedef'd in stdio.h
 */
#else
#define WORD int
#define UWORD unsigned int
#endif

#include <stdio.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) 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 */
{   UWORD weight;                   	/* number of appearances */
    WORD tdepth;                        /* length on longest path in tree */
    WORD lchild, rchild;                /* indices to next level */
}   node[NUMNODES];                    /* use large buffer */

static WORD 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 WORD codelen[NUMVALS];           /* number of bits in code */
static UWORD code[NUMVALS];         /* code itself, right adjusted */
static UWORD 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 WORD cbitsrem;                   /* # of code string bits left */
static UWORD ccode;                 /* current code right justified */

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<NUMNODES; ++i)
    {    node[i].weight = 0;
         node[i].tdepth = 0;
         node[i].lchild = NOCHILD;
         node[i].rchild = NOCHILD;
    }

    for(i=0; i<NUMVALS; i++)
         valcount[i] = 0;
}

scan_sq(c)                             /* add a byte to the tables */
int c;                                 /* byte to add */
{
    UWORD *wp;                      /* speeds up weight counting */

    /* Build frequency info in tree */

    if(c == EOF)                       /* it's traditional */
	{
         c = SPEOF;                    /* dumb, but traditional */
	}
	if(*(wp = &node[c].weight) !=  MAXCOUNT)
         ++(*wp);                      /* bump weight counter */

    valcount[c]++;                     /* bump byte counter */
}

long pred_sq()                         /* predict size of squeezed file */
{
    WORD i;
    WORD btlist[NUMVALS];               /* list of intermediate b-trees */
    WORD listlen;                       /* length of btlist */
    UWORD  ceiling;                  	/* limit for scaling */
    long size = 0;                     /* predicted size */
    WORD numnodes;                      /* # of nodes in simplified tree */

    scan_sq(EOF);                      /* signal end of input */

    ceiling = MAXCOUNT;

    /* Keep trying to scale and encode */

    do
    {    scale(ceiling);
         ceiling /= 2;                 /* in case we rescale */

         /* Build list of single node binary trees having
            leaves for the input values with non-zero counts
         */

         for(i=listlen=0; i<NUMVALS; ++i)
         {    if(node[i].weight != 0)
              {    node[i].tdepth = 0;
                   btlist[listlen++] = i;
              }
         }

         /* Arrange list of trees into a heap with the entry
            indexing the node with the least weight at the top.
         */

         heap(btlist,listlen);

         /* Convert the list of trees to a single decoding tree */

         bld_tree(btlist,listlen);

         /* Initialize the encoding table */

         init_enc();

         /* Try to build encoding table.
            Fail if any code is > 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<NUMVALS; i++)           /* add bits for each code */
	{
        size += valcount[i] * codelen[i];
	}
    size = (size+7)/8;                 /* reduce to number of bytes */

    numnodes = dctreehd<NUMVALS ? 0 : dctreehd-(NUMVALS-1);

    size += sizeof(WORD) + 2*numnodes*sizeof(WORD);

    return size;
}

/* The count of number of occurrances of each input value
   have already been prevented from exceeding MAXCOUNT.
   Now we must scale them so that their sum doesn't exceed
   ceiling and yet no non-zero count can become zero.
   This scaling prevents errors in the weights of the
   interior nodes of the Huffman tree and also ensures that
   the codes will fit in an unsigned integer. Rescaling is
   used if necessary to limit the code length.
*/

static scale(ceil)
UWORD ceil;                         /* upper limit on total weight */
{
    register WORD i,c;
    WORD ovflw, divisor;
    UWORD w, sum;
    unsigned char increased;           /* flag */

    do
    {    for(i=sum=ovflw=0; i<NUMVALS; ++i)
         {    if(node[i].weight > (ceil-sum))
                   ++ovflw;
              sum += node[i].weight;
         }

         divisor = ovflw + 1;

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

         increased = FALSE;
         for(i=0; i<NUMVALS; ++i)
         {    w = node[i].weight;
              if(w<divisor && w!=0)
              {    /* Don't fail to provide a code if it's used at all */

                   node[i].weight = divisor;
                   increased = TRUE;
              }
         }
    }    while(increased);

    /* Scaling factor choosen, now scale */

#ifdef DEBUG
	printf ("scale factor: %d\n",divisor);
#endif

    if(divisor>1)
         for(i=0; i<NUMVALS; ++i)
              node[i].weight /= divisor;
}

/* heap() and adjust() maintain a list of binary trees as a
   heap with the top indexing the binary tree on the list
   which has the least weight or, in case of equal weights,
   least depth in its longest path. The depth part is not
   strictly necessary, but tends to avoid long codes which
   might provoke rescaling.
*/

static heap(list,length)
WORD list[], length;
{
    register WORD i;

    for(i=(length-2)/2; i>=0; --i)
         adjust(list,i,length-1);
}

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

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

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

    if(k<=bottom)
    {    if(k<bottom && cmptrees(list[k],list[k+1]))
              ++k;

         /* k indexes "smaller" child (in heap of trees) of top */
         /* now make top index "smaller" of old top and smallest child */

         if(cmptrees(temp,list[k]))
         {    list[top] = list[k];
              list[k] = temp;

              /* Make the changed list a heap */

              adjust(list,k,bottom);   /* recursive */
         }
    }
}

/* Compare two trees, if a > b return true, else return false.
   Note comparison rules in previous comments.
*/

static cmptrees(a,b)
WORD 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 bld_tree(list,len)
WORD list[];
WORD len;
{
    register WORD freenode;             /* next free node in tree */
    register struct nd *frnp;          /* free node pointer */
    WORD lch, rch;                      /* temps for left, right children */
    WORD i;

    /* 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 maxchar(a,b)
{
    return a>b ? a : b;
}

static init_enc()
{
    register int i;

    /* Initialize encoding table */

    for(i=0; i<NUMVALS; ++i)
         codelen[i] = 0;
}

/* Recursive routine to walk the indicated subtree and level
   and maintain the current path code in bstree. When a leaf
   is found the entire code string and length are put into
   the encoding table entry for the leaf's data value .

   Returns ERROR if codes are too long.
*/

static int buildenc(level,root)
WORD level;              /* level of tree being examined, from zero */
WORD root;               /* root of subtree is also data value if leaf */
{
    register WORD l, r;
#ifdef OSK
/*
 *	for building a mask to be ANDed with the code word, we can not use
 *	the method in the original source because the 68k will sign-extend the
 *	all-ones word and, when shifting right, always return an all-ones word.
 */
	register UWORD andmask;
#endif

    l = node[root].lchild;
    r = node[root].rchild;

    if(l==NOCHILD && r==NOCHILD)
    {    /* Leaf. Previous path determines bit string
            code of length level (bits 0 to level - 1).
            Ensures unused code bits are zero.
         */

         codelen[root] = level;
#ifndef OSK
         code[root] = (UWORD)(tcode & (((UWORD)~0) >> (16-level)));
#else
/*
 *	instead of shifting right by (16-level), shift left by level and
 *	subtract one
 */
		andmask = (WORD)(0x01 << level) -1;
		code[root] = (UWORD)(tcode & andmask);
#endif
         return (level>16) ? ERROR : NULL;
    }

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

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

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

static 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)&0xff,f);                  /* then the high byte */
}

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

static long wrt_head(ob)
FILE *ob;
{
    register WORD l,r;
    WORD i, k;
    WORD 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<NUMVALS ? 0 : dctreehd-(NUMVALS-1);

#ifdef DEBUG
	printf ("wrt_head: %d nodes\n",numnodes);
#endif

    put_int(numnodes,ob);

    for(k=0, i=dctreehd; k<numnodes; ++k, --i)
    {    l = node[i].lchild;
         r = node[i].rchild;
         l = l<NUMVALS ? -(l+1) : dctreehd-l;
         r = r<NUMVALS ? -(r+1) : dctreehd-r;
         put_int(l,ob);
         put_int(r,ob);
    }

    return sizeof(WORD) + numnodes*2*sizeof(WORD);
}

/* Get an encoded byte or EOF. Reads from specified stream AS NEEDED.

   There are two unsynchronized bit-byte relationships here.
   The input stream bytes are converted to bit strings of
   various lengths via the static variables named c...
   These bit strings are concatenated without padding to
   become the stream of encoded result bytes, which this
   function returns one at a time. The EOF (end of file) is
   converted to SPEOF for convenience and encoded like any
   other input value. True EOF is returned after that.
*/

static int gethuff(ib)                 /* Returns bytes except for EOF */
FILE *ib;
{
    WORD rbyte;                         /* Result byte value */
    WORD need, take;                    /* numbers of bits */
	
    rbyte = 0;
    need = 8;                          /* build one byte per call */

    /* Loop to build a byte of encoded data.
       Initialization forces read the first time.
    */

loop:
    if(cbitsrem>=need)                 /* if current code is big enough */
    {    if(need==0)
              return (int)(rbyte & 0xff);

         rbyte |= (ccode << (8-need));    /* take what we need */
         ccode >>= need;               /* and leave the rest */
         cbitsrem -= need;
         return (int)(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 : (int)rbyte;
    }

    /* 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&0xff),t);
         size++;
    }
#ifdef DEBUG
	printf ("file_sq: size = %d\n",size);
#endif
    return size;                       /* report true size */
}
//E*O*F arcsq.c//

echo x - arcsvc.c
cat > "arcsvc.c" << '//E*O*F arcsvc.c//'
/*  ARC - Archive utility - ARCSVC

$define(tag,$$segment(@1,$$index(@1,=)+1))#
$define(version,Version $tag(
TED_VERSION DB =2.15), created on $tag(
TED_DATE DB =12/17/85) at $tag(
TED_TIME DB =15:17:16))#
$undefine(tag)#
    $version

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

    By:  Thom Henderson

    Description:
         This file contains service routines needed to maintain an archive.

    Language:
         Computer Innovations Optimizing C86
*
*	changed abort(..) to exit(_errmsg(1,...))
*/
#include <stdio.h>
#define EXTERN extern
#include "arc.h"

openarc(chg)                           /* open archive */
int chg;                               /* true to open for changes */
{
    FILE *fopen();                     /* file opener */

#ifdef DEBUG
	printf ("openarc(%d): trying to open %s\n",chg, arcname);
#endif
									    
    if(!(arc=fopen(arcname,READBIN)))   
    {    if(chg)				  	    
              printf("Creating new archive: %s\n",arcname);
         else exit (_errmsg(1,"Cannot read archive: %s",arcname));
    }							  	    
								  	    
    if(chg)                            /* if opening for changes */
	{
#ifdef DEBUG
	printf ("openarc(%d): trying to open new %s\n",chg, newname);
#endif
         if(!(new=fopen(newname,WRITEBIN)))
              exit (_errmsg(1,"Cannot create archive copy: %s",newname));
	}
}

closearc(chg)                          /* close an archive */
int chg;                               /* true if archive was changed */
{
    if(arc)                            /* if we had an initial archive */
         fclose(arc);                  /* then close it */

    if(chg)                            /* if things have changed */
    {    setstamp(new,arcdate,arctime);/* archive matches newest file */

         fclose(new);                  /* close the new copy */

         if(arc)                       /* if we had an original archive */
         {    if(keepbak)              /* if a backup is wanted */
              {    unlink(bakname);    /* erase any old copies */
                   if(rename(arcname,bakname))
                        exit (_errmsg(1,
						"Cannot rename %s to %s",arcname,bakname));
                   printf("Keeping backup archive: %s\n",bakname);
              }
              else if(unlink(arcname))
                   exit (_errmsg(1,"Cannot delete old archive: %s",arcname));
         }

         if(rename(newname,arcname))
              exit (_errmsg(1,"Cannot rename %s to %s",newname,arcname));
    }
}

/* CRC computation logic

   The logic for this method of calculating the CRC 16 bit polynomial
   is taken from an article by David Schwaderer in the April 1985
   issue of PC Tech Journal.
*/

static int crctab[] =                  /* CRC lookup table */
{   0x0000, 0xC0C1, 0xC181, 0x0140, 0xC301, 0x03C0, 0x0280, 0xC241,
    0xC601, 0x06C0, 0x0780, 0xC741, 0x0500, 0xC5C1, 0xC481, 0x0440,
    0xCC01, 0x0CC0, 0x0D80, 0xCD41, 0x0F00, 0xCFC1, 0xCE81, 0x0E40,
    0x0A00, 0xCAC1, 0xCB81, 0x0B40, 0xC901, 0x09C0, 0x0880, 0xC841,
    0xD801, 0x18C0, 0x1980, 0xD941, 0x1B00, 0xDBC1, 0xDA81, 0x1A40,
    0x1E00, 0xDEC1, 0xDF81, 0x1F40, 0xDD01, 0x1DC0, 0x1C80, 0xDC41,
    0x1400, 0xD4C1, 0xD581, 0x1540, 0xD701, 0x17C0, 0x1680, 0xD641,
    0xD201, 0x12C0, 0x1380, 0xD341, 0x1100, 0xD1C1, 0xD081, 0x1040,
    0xF001, 0x30C0, 0x3180, 0xF141, 0x3300, 0xF3C1, 0xF281, 0x3240,
    0x3600, 0xF6C1, 0xF781, 0x3740, 0xF501, 0x35C0, 0x3480, 0xF441,
    0x3C00, 0xFCC1, 0xFD81, 0x3D40, 0xFF01, 0x3FC0, 0x3E80, 0xFE41,
    0xFA01, 0x3AC0, 0x3B80, 0xFB41, 0x3900, 0xF9C1, 0xF881, 0x3840,
    0x2800, 0xE8C1, 0xE981, 0x2940, 0xEB01, 0x2BC0, 0x2A80, 0xEA41,
    0xEE01, 0x2EC0, 0x2F80, 0xEF41, 0x2D00, 0xEDC1, 0xEC81, 0x2C40,
    0xE401, 0x24C0, 0x2580, 0xE541, 0x2700, 0xE7C1, 0xE681, 0x2640,
    0x2200, 0xE2C1, 0xE381, 0x2340, 0xE101, 0x21C0, 0x2080, 0xE041,
    0xA001, 0x60C0, 0x6180, 0xA141, 0x6300, 0xA3C1, 0xA281, 0x6240,
    0x6600, 0xA6C1, 0xA781, 0x6740, 0xA501, 0x65C0, 0x6480, 0xA441,
    0x6C00, 0xACC1, 0xAD81, 0x6D40, 0xAF01, 0x6FC0, 0x6E80, 0xAE41,
    0xAA01, 0x6AC0, 0x6B80, 0xAB41, 0x6900, 0xA9C1, 0xA881, 0x6840,
    0x7800, 0xB8C1, 0xB981, 0x7940, 0xBB01, 0x7BC0, 0x7A80, 0xBA41,
    0xBE01, 0x7EC0, 0x7F80, 0xBF41, 0x7D00, 0xBDC1, 0xBC81, 0x7C40,
    0xB401, 0x74C0, 0x7580, 0xB541, 0x7700, 0xB7C1, 0xB681, 0x7640,
    0x7200, 0xB2C1, 0xB381, 0x7340, 0xB101, 0x71C0, 0x7080, 0xB041,
    0x5000, 0x90C1, 0x9181, 0x5140, 0x9301, 0x53C0, 0x5280, 0x9241,
    0x9601, 0x56C0, 0x5780, 0x9741, 0x5500, 0x95C1, 0x9481, 0x5440,
    0x9C01, 0x5CC0, 0x5D80, 0x9D41, 0x5F00, 0x9FC1, 0x9E81, 0x5E40,
    0x5A00, 0x9AC1, 0x9B81, 0x5B40, 0x9901, 0x59C0, 0x5880, 0x9841,
    0x8801, 0x48C0, 0x4980, 0x8941, 0x4B00, 0x8BC1, 0x8A81, 0x4A40,
    0x4E00, 0x8EC1, 0x8F81, 0x4F40, 0x8D01, 0x4DC0, 0x4C80, 0x8C41,
    0x4400, 0x84C1, 0x8581, 0x4540, 0x8701, 0x47C0, 0x4680, 0x8641,
    0x8201, 0x42C0, 0x4380, 0x8341, 0x4100, 0x81C1, 0x8081, 0x4040
};

int addcrc(crc,c)                      /* update a CRC check */
int crc;                               /* running CRC value */
unsigned char c;                       /* character to add */
{
    return ((crc>>8)&0x00ff) ^ crctab[(crc^c)&0x00ff];
}
//E*O*F arcsvc.c//

echo x - arctst.c
cat > "arctst.c" << '//E*O*F arctst.c//'

/*  ARC - Archive utility - ARCTST

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

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

    By:  Thom Henderson

    Description:
         This file contains the routines used to test archive integrity.

    Language:
         Computer Innovations Optimizing C86
*/
#include <stdio.h>
#define EXTERN extern
#include "arc.h"

tstarc()                               /* test integrity of an archive */
{
    struct heads hdr;                  /* file header */
    long arcsize, ftell();             /* archive size */

    openarc(0);                        /* open archive for reading */
    fseek(arc,0L,2);                   /* move to end of archive */
    arcsize = ftell(arc);              /* see how big it is */
    fseek(arc,0L,0);                   /* return to top of archive */

    while(readhdr(&hdr,arc))
    {    if(ftell(arc)+hdr.size>arcsize)
         {    printf("Archive truncated in file %s\n",hdr.name);
              nerrs++;
              break;
         }

         else
         {    printf("Testing file: %-12s  ",hdr.name);
				fflush (stdout);
              if(unpack(arc,NULL,&hdr))
                   nerrs++;
              else printf("okay\n");
         }
    }

    if(nerrs<1)
         printf("No errors detected\n");
    else if(nerrs==1)
         printf("One error detected\n");
    else printf("%d errors detected\n",nerrs);
}
//E*O*F arctst.c//

echo x - arcunp.c
cat > "arcunp.c" << '//E*O*F arcunp.c//'

/*  ARC - Archive utility - ARCUNP

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

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

    By:  Thom Henderson

    Description:
         This file contains the routines used to expand a file
         when taking it out of an archive.

    Language:
         Computer Innovations Optimizing C86
*
*	changed abort(..) to exit(_errmsg(1,...))
*/
#include <stdio.h>
#define EXTERN extern
#include "arc.h"

/* stuff for repeat unpacking */

#define DLE 0x90                       /* repeat byte flag */

static int state;                      /* repeat unpacking state */

/* repeat unpacking states */

#define NOHIST 0                       /* no relevant history */
#define INREP 1                        /* sending a repeated value */

static short crcval;                     /* CRC check value */
static long size;                      /* bytes to read */

int unpack(f,t,hdr)                    /* unpack an archive entry */
FILE *f, *t;                           /* source, destination */
struct heads *hdr;                     /* pointer to file header data */
{
    int c;                             /* one char of stream */
#ifdef DEBUG
    int count = 0;
#endif
    /* setups common to all methods */

    crcval = 0;                        /* reset CRC check value */
    size = hdr->size;                  /* set input byte counter */
#ifdef DEBUG
	printf ("size: %ld\n",size);
#endif
    state = NOHIST;                    /* initial repeat unpacking state */
    setcode();                         /* set up for decoding */

    /* use whatever method is appropriate */

    switch(hdrver)                     /* choose proper unpack method */
    {
    case 1:                            /* standard packing */
    case 2:
         while((c=getc_unp(f))!=EOF)
              putc_unp(c,t);
         break;

    case 3:                            /* non-repeat packing */
         while((c=getc_unp(f))!=EOF)
              putc_ncr(c,t);
         break;

    case 4:                            /* Huffman squeezing */
         init_usq(f);
         while((c=getc_usq(f))!=EOF)
         {
              putc_ncr(c,t);
#ifdef DEBUG
              count++;
#endif
          }
#ifdef DEBUG
          printf ("%d calls to getc_usq\n",count);
#endif
          break;

    case 5:                            /* Lempel-Zev compression */
         init_ucr(0);
         while((c=getc_ucr(f))!=EOF)
              putc_unp(c,t);
         break;

    case 6:                            /* Lempel-Zev plus non-repeat */
         init_ucr(0);
         while((c=getc_ucr(f))!=EOF)
              putc_ncr(c,t);
         break;

    case 7:                            /* L-Z plus ncr with new hash */
         init_ucr(1);
         while((c=getc_ucr(f))!=EOF)
              putc_ncr(c,t);
         break;

    case 8:                            /* dynamic Lempel-Zev */
         decomp(f,t);
         break;

    default:                           /* unknown method */
         if(warn)
         {    printf("I don't know how to unpack file %s\n",hdr->name);
              printf("I think you need a newer version of ARC\n");
              nerrs++;
         }
         fseek(f,hdr->size,1);         /* skip over bad file */
         return 1;                     /* note defective file */
    }

    /* cleanups common to all methods */

    if(crcval!=hdr->crc)
    {    if(warn)
         {    printf("WARNING: File %s fails CRC check\n",hdr->name);
              printf ("expected: %04.4x  calculated: %04.4x\n",
				hdr->crc&0xffff, crcval&0xffff);
				nerrs++;
         }
         return 1;                     /* note defective file */
    }
    return 0;                          /* file is okay */
}

/*  This routine is used to put bytes in the output file.  It also
    performs various housekeeping functions, such as maintaining the
    CRC check value.
*/

static putc_unp(c,t)                   /* output an unpacked byte */
char c;                                /* byte to output */
FILE *t;                               /* file to output to */
{
    crcval = addcrc(crcval,c);         /* update the CRC check value */
    putc_tst(c,t);
}

/*  This routine is used to decode non-repeat compression.  Bytes are
    passed one at a time in coded format, and are written out uncoded.
    The data is stored normally, except that runs of more than two
    characters are represented as:

         <char> <DLE> <count>

    With a special case that a count of zero indicates a DLE as data,
    not as a repeat marker.
*/

putc_ncr(c,t)                          /* put NCR coded bytes */
unsigned char c;                       /* next byte of stream */
FILE *t;                               /* file to receive data */
{
    static int lastc;                  /* last character seen */

    switch(state)                      /* action depends on our state */
    {
    case NOHIST:                       /* no previous history */
         if(c==DLE)                    /* if starting a series */
              state = INREP;           /* then remember it next time */
         else putc_unp(lastc=c,t);     /* else nothing unusual */
         return;

    case INREP:                        /* in a repeat */
         if(c)                         /* if count is nonzero */
              while(--c)               /* then repeatedly ... */
                   putc_unp(lastc,t);  /* ... output the byte */
         else putc_unp(DLE,t);         /* else output DLE as data */
         state = NOHIST;               /* back to no history */
         return;

    default:
         exit (_errmsg(1,"Bad NCR unpacking state (%d)",state));
    }
}

/*  This routine provides low-level byte input from an archive.  This
    routine MUST be used, as end-of-file is simulated at the end of
    the archive entry.
*/

int getc_unp(f)                        /* get a byte from an archive */
FILE *f;                               /* archive file to read */
{
    if(!size)                          /* if no data left */
         return EOF;                   /* then pretend end of file */

    size--;                            /* deduct from input counter */
    return code(fgetc(f));             /* and return next decoded byte */
}
//E*O*F arcunp.c//

echo x - arcusq.c
cat > "arcusq.c" << '//E*O*F arcusq.c//'

/*  ARC - Archive utility - ARCUSQ

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

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

    By:  Thom Henderson

    Description:
         This file contains the routines used to expand a file
         which was packed using Huffman squeezing.

         Most of this code is taken from an USQ program by Richard
         Greenlaw, which was adapted to CI-C86 by Robert J. Beilstein.

    Language:
         Computer Innovations Optimizing C86
*
*	changed abort(..) to exit(_errmsg(1,...))
*/
#ifdef OSK
#define UWORD unsigned short
#else
#define WORD int
#define UWORD unsigned int
#endif

#include <stdio.h>
#define EXTERN extern
#include "arc.h"

/* stuff for Huffman unsqueezing */

#define ERROR (-1)

#define SPEOF 256                      /* special endfile token */
#define NUMVALS 257                    /* 256 data values plus SPEOF */

/* extern */
static
struct nd                       /* decoding tree */
{   WORD child[2];                      /* left, right */
}   node[NUMVALS];                     /* use large buffer */

static int bpos;                       /* last bit position read */
static int curin;                      /* last byte value read */
static int numnodes;                   /* number of nodes in decode tree */

static int get_int(f)                  /* get an integer */
FILE *f;                               /* file to get it from */
{
	int i1, i2;
	i1 = getc_unp(f);
    i2 = getc_unp(f);
	return (i1 | (i2 << 8));
	
/*@@@@@@@ that one is definitely unstable:
according to K&R 7.10, expressions involving the '|' operator may be
rearranged by the compiler; thus the execution sequence in the code below
is undetermined.

return getc_unp(f) | (getc_unp(f)<<8);

@@@@@@@@*/
}

init_usq(f)                            /* initialize Huffman unsqueezing */
FILE *f;                               /* file containing squeezed data */
{
    int i;                             /* node index */

    bpos = 99;                         /* force initial read */

    numnodes = get_int(f);
#ifdef DEBUG
	printf ("init_usq: %d nodes in tree\n", numnodes);
#endif

    if(numnodes<0 || numnodes>=NUMVALS)
         exit (_errmsg(1,"File has an invalid decode tree"));

    /* initialize for possible empty tree (SPEOF only) */

    node[0].child[0] = -(SPEOF + 1);
    node[0].child[1] = -(SPEOF + 1);

    for(i=0; i<numnodes; ++i)          /* get decoding tree from file */
    {    node[i].child[0] = (WORD)get_int(f);
         node[i].child[1] = (WORD)get_int(f);
    }
}

int getc_usq(f)                        /* get byte from squeezed file */
FILE *f;                               /* file containing squeezed data */
{
    WORD i;                             /* tree index */

    /* follow bit stream in tree to a leaf */

    for(i=0; i>=0; )                   /* work down(up?) from root */
    {    
		if(++bpos>7)
         {    if((curin=getc_unp(f)) == ERROR)
              {
                   return(ERROR);
              }
              bpos = 0;

              /* move a level deeper in tree */
              i = node[i].child[1&curin];
         }
         else 
		{
			curin >>=1;
			i = node[i].child[1 & curin];
		}
    }

    /* decode fake node index to original data value */

    i = -(i + 1);

    /* decode special endfile token to normal EOF */

    i = (i==SPEOF) ? EOF : i;
    return i;
}
//E*O*F arcusq.c//

echo x - system.c
cat > "system.c" << '//E*O*F system.c//'
#include <stdio.h>
#include <ctype.h>
#define EXTERN extern
#include "arc.h"

int rename (file2, file1)
char *file2, *file1;
{
	char *argblk[4];
	extern int os9forkc();
	extern char **environ;
	int pid;
#ifdef DEBUG
	printf ("trying to rename %s to %s\n", file2, file1);
#endif	

	argblk[0] = "rename";
	argblk[1] = file2;					/* old file name					*/
	argblk[2] = file1;					/* new file name					*/
	argblk[3] = 0;
	if ((pid =os9exec 
		(os9forkc, argblk[0], argblk, environ, 0, 0, 3)) > 0)
	{
		wait (0);
		return 0;
	}
	else
		return -1;
}

/*
 *  setmem      set <num> bytes beginning at <addr> to <c>.
 *              This is commonly supported.
 */
char *
setmem(ptr, num, c)
char *ptr;
int num, c;
{
   register j;

   for(j = 0; j < num; j++)
      ptr[j] = c;
   return ptr;
}

char *upper(string)
char *string;
{
	register int i;
	for (i=0; i<strlen(string); i++)
		string[i] = toupper(string[i]);
	return string;
}

char *realloc (oldptr, newsize)
char *oldptr;
int newsize;
/*
 *	a substitute for the standard realloc function
 */
{   
	register char *newptr;
	register int i;
	extern char *malloc();
	if ((newptr = malloc(newsize)) == (char *)0)
		return (char *)0;
/*  
 *	new block allocated ok, copy old contents to it
 */ 
	for (i=0; i<newsize; i++)
		newptr[i] = oldptr[i];
/*@@@@@	free (oldptr); @@@@*/
	return newptr;	
}
/*
 *	This is an emulation of the Computer Innovations C86 compiler
 *	'makefnam()' function. It takes an input string, a default string,
 *	and a file name string as its parameters. It attempts to construct
 *	a valid file name out of the elements of the input string and the
 *	default string. The default string can be viewed as a template.
 *
 *	Example:
 *	inpnam = "myfile"
 *	defnam = "a:testdir/foobar.dat"
 *	then filnam = "a:testdir/myfile.dat"
 *
 *	In the OS-9 version, the drive ID part is not returned, but still
 *	retained within the function.
 */

char *makefnam (inpnam, defnam, filnam)
char *inpnam, *defnam, *filnam;
{
	int inp_period, def_period;
	int inp_colon,  def_colon;
	int inp_slash,  def_slash;
	char inp_drive[10];
	char def_drive[10];
	char inp_path [80];
	char def_path [80];
	char inp_name [80];
	char def_name [80];
	char inp_ext  [ 8];
	char def_ext  [ 8];
	char loc_inpnam[STRLEN], loc_defnam[STRLEN];
	
	char *temp;
	
	char *index(), *rindex();

	strcpy (loc_inpnam, inpnam);
	strcpy (loc_defnam, defnam);
	
#ifdef DEBUG_MAKE
	printf ("makefnam: inp:%s def:%s\n",loc_inpnam,loc_defnam);
#endif
	inp_colon = ((temp = index (loc_inpnam,':')) ? (int)(temp-loc_inpnam):-1);
	def_colon = ((temp = index (loc_defnam,':')) ? (int)(temp-loc_defnam):-1);
#ifdef DEBUG_MAKE
	printf ("colon index inp: %d  def: %d\n",inp_colon, def_colon);
#endif
	inp_slash = ((temp = rindex (loc_inpnam,'/')) ? (int)(temp-loc_inpnam):-1);
	def_slash = ((temp = rindex (loc_defnam,'/')) ? (int)(temp-loc_defnam):-1);
#ifdef DEBUG_MAKE
	printf ("slash index inp: %d  def: %d\n",inp_slash, def_slash);
#endif
	inp_period = ((temp = index (loc_inpnam,'.')) ? (int)(temp-loc_inpnam):-1);
	def_period = ((temp = index (loc_defnam,'.')) ? (int)(temp-loc_defnam):-1);
#ifdef DEBUG_MAKE
	printf ("period index inp: %d  def: %d\n",inp_period, def_period);
#endif
	if (inp_colon == -1)
	{
		strcpy (inp_drive,"");
	}
	else
		strncpy (inp_drive, loc_inpnam, inp_colon+1);
	if (def_colon == -1)
	{
		strcpy (def_drive,"");
	}
	else
		strncpy (def_drive, loc_defnam, def_colon+1);

	if (inp_slash == -1)
	{
		strcpy (inp_path,"");
		inp_slash = inp_colon;
	}
	else
		strncpy (inp_path, &loc_inpnam[inp_colon+1],inp_slash - inp_colon);
	if (def_slash == -1)
	{
		strcpy (def_path,"");
		def_slash = def_colon;
	}
	else
		strncpy (def_path, &loc_defnam[def_colon+1],def_slash - def_colon);

	if (inp_period == -1)
		strcpy (inp_ext,"");
	else
	{
		strcpy (inp_ext, &loc_inpnam[inp_period]);
		loc_inpnam[inp_period] = '\0';
	}
	strcpy (inp_name, &loc_inpnam[inp_slash+1]);

	if (def_period == -1)
		strcpy (def_ext,"");
	else
	{
		strcpy (def_ext, &loc_defnam[def_period]);
		loc_defnam[def_period] = '\0';
	}
	strcpy (def_name, &loc_defnam[def_slash+1]);

#ifdef DEBUG_MAKE
	printf ("def drive: %s\n", def_drive);
	printf ("inp drive: %s\n", inp_drive);
	printf ("def path : %s\n", def_path);
	printf ("inp path : %s\n", inp_path);
	printf ("def name : %s\n", def_name);
	printf ("inp name : %s\n", inp_name);
	printf ("def ext  : %s\n", def_ext);
	printf ("inp ext  : %s\n", inp_ext);
#endif
/*
 *	now build the name
 */

#ifndef OSK
	if (strlen(inp_drive))
		strcpy (filnam, inp_drive);
	else
		strcpy (filnam, def_drive);
#else
	strcpy (filnam,"");
#endif
		
	if (strlen(inp_path))
		strcat (filnam, inp_path);
	else
		strcat (filnam, def_path);
		
	if (strlen(inp_name))
		strcat (filnam, inp_name);
	else
		strcat (filnam, def_name);
		
	if (strlen(inp_ext))
		strcat (filnam, inp_ext);
	else
		strcat (filnam, def_ext);
		
	return filnam;
}
//E*O*F system.c//

exit 0
-------------------------------------
The views expressed in OS-9 Discussions are those of the individual authors
only.  Copies of digests are available by mail request.
------
Moderator:  John Daleske   cbosgd!cbdkc1!daleske    daleske@cbdkc1.ATT.COM
Submissions should go to:  cbosgd!os9               os9@cbosgd.ATT.COM
Comments to the moderator  cbosgd!os9-request       os9-request@cbosgd.ATT.COM

*********************
End of OS-9 Discussions
*********************