home *** CD-ROM | disk | FTP | other *** search
/ Technotools / Technotools (Chestnut CD-ROM)(1993).ISO / unix / arcunx11 / arc.sh2 / arclzw.c < prev    next >
Encoding:
C/C++ Source or Header  |  1987-04-01  |  24.8 KB  |  825 lines

  1. /*
  2.  *    arclzw.c    1.1
  3.  *
  4.  *    Author: Thom Henderson
  5.  *    Original System V port: Mike Stump
  6.  *    Enhancements, Bug fixes, and cleanup: Chris Seaman
  7.  *    Date: Fri Mar 20 09:57:02 1987
  8.  *    Last Mod.    3/21/87
  9.  *
  10.  */
  11.  
  12. /*
  13.  * ARC - Archive utility - ARCLZW
  14.  * 
  15.  * Version 1.88, created on 01/20/86 at 16:47:04
  16.  * 
  17.  * (C) COPYRIGHT 1985 by System Enhancement Associates; ALL RIGHTS RESERVED
  18.  * 
  19.  *     Description:
  20.  *          This file contains the routines used to implement Lempel-Zev
  21.  *          data compression, which calls for building a coding table on
  22.  *          the fly.  This form of compression is especially good for encoding
  23.  *          files which contain repeated strings, and can often give dramatic
  24.  *          improvements over traditional Huffman SQueezing.
  25.  * 
  26.  *     Programming notes:
  27.  *          In this section I am drawing heavily on the COMPRESS program
  28.  *          from UNIX.  The basic method is taken from "A Technique for High
  29.  *          Performance Data Compression", Terry A. Welch, IEEE Computer
  30.  *          Vol 17, No 6 (June 1984), pp 8-19.  Also see "Knuth's Fundamental
  31.  *          Algorithms", Donald Knuth, Vol 3, Section 6.4.
  32.  * 
  33.  *          As best as I can tell, this method works by tracing down a hash
  34.  *          table of code strings where each entry has the property:
  35.  * 
  36.  *               if <string> <char> is in the table
  37.  *               then <string> is in the table.
  38.  */
  39.  
  40. #include "arc.h"
  41.  
  42. /* definitions for older style crunching */
  43.  
  44. #define FALSE    0
  45. #define TRUE     !FALSE
  46. #define TABSIZE  4096
  47. #define NO_PRED  0xFFFF
  48. #define EMPTY    0xFFFF
  49. #define NOT_FND  0xFFFF
  50.  
  51. static unsigned INT inbuf;             /* partial input code storage */
  52. static INT sp;                         /* current stack pointer */
  53.  
  54. static struct entry {                  /* string table entry format */
  55.     char used;                         /* true when this entry is in use */
  56.     unsigned INT next;                 /* ptr to next in collision list */
  57.     unsigned INT predecessor;          /* code for preceeding string */
  58.     unsigned char follower;            /* char following string */
  59. }   string_tab[TABSIZE];               /* the code string table */
  60.  
  61.  
  62. /* definitions for the new dynamic Lempel-Zev crunching */
  63.  
  64. #define BITS   12                      /* maximum bits per code */
  65. #define HSIZE  5003                    /* 80% occupancy */
  66. #define INIT_BITS 9                    /* initial number of bits/code */
  67.  
  68. static INT n_bits;                     /* number of bits/code */
  69. static INT maxcode;                    /* maximum code, given n_bits */
  70. #define MAXCODE(n)      ((1<<(n)) - 1) /* maximum code calculation */
  71. static INT maxcodemax =  1 << BITS;    /* largest possible code (+1) */
  72.  
  73. static unsigned char buf[BITS];        /* input/output buffer */
  74.  
  75. static unsigned char lmask[9] = {      /* left side masks */
  76.     0xff, 0xfe, 0xfc,
  77.     0xf8, 0xf0, 0xe0,
  78.     0xc0, 0x80, 0x00
  79. };
  80. static unsigned char rmask[9] = {      /* right side masks */
  81.     0x00, 0x01, 0x03,
  82.     0x07, 0x0f, 0x1f,
  83.     0x3f, 0x7f, 0xff
  84. };
  85.  
  86. static INT offset;                     /* byte offset for code output */
  87. static long in_count;                  /* length of input */
  88. static long bytes_out;                 /* length of compressed output */
  89. static unsigned INT ent;
  90.  
  91. /*
  92.  * To save much memory (which we badly need at this point), we overlay
  93.  * the table used by the previous version of Lempel-Zev with those used
  94.  * by the new version.  Since no two of these routines will be used
  95.  * together, we can safely do this.  Note that the tables used for Huffman
  96.  * squeezing may NOT overlay these, since squeezing and crunching are done
  97.  * in parallel.
  98.  */
  99.  
  100. static long htab[HSIZE];               /* hash code table   (crunch) */
  101. static unsigned INT codetab[HSIZE];    /* string code table (crunch) */
  102.  
  103. static unsigned INT *prefix = codetab; /* prefix code table (uncrunch) */
  104.  
  105. static unsigned char suffix[HSIZE];    /* suffix table (uncrunch) */
  106. static INT free_ent;                   /* first unused entry */
  107. static INT firstcmp;                   /* true at start of compression */
  108. static unsigned char stack[HSIZE];     /* local push/pop stack */
  109.  
  110. /*
  111.  * block compression parameters -- after all codes are used up,
  112.  * and compression rate changes, start over.
  113.  */
  114.  
  115. static INT clear_flg;
  116. static long ratio;
  117. #define CHECK_GAP 10000                /* ratio check interval */
  118. static long checkpoint;
  119.  
  120. /*
  121.  * the next two codes should not be changed lightly, as they must not
  122.  * lie within the contiguous general code space.
  123.  */
  124.  
  125. #define FIRST   257                    /* first free entry */
  126. #define CLEAR   256                    /* table clear output code */
  127.  
  128. static INT cl_block(t)                 /* table clear for block compress */
  129. FILE *t;                               /* our output file */
  130. {
  131.     long rat;
  132.     INT putcode();
  133.  
  134.     checkpoint = in_count + CHECK_GAP;
  135.  
  136.     if (in_count > 0x007fffff)         /* shift will overflow */
  137.     {
  138.         rat = bytes_out >> 8;
  139.         if (rat == 0)                  /* Don't divide by zero */
  140.             rat = 0x7fffffff;
  141.         else
  142.             rat = in_count / rat;
  143.     }
  144.     else
  145.         rat = (in_count<<8)/bytes_out;/* 8 fractional bits */
  146.  
  147.     if (rat > ratio)
  148.         ratio = rat;
  149.     else
  150.     {
  151.         ratio = 0;
  152.         setmem(htab,HSIZE*sizeof(long),0xff);
  153.         free_ent = FIRST;
  154.         clear_flg = 1;
  155.         putcode(CLEAR,t);
  156.     }
  157. }
  158.  
  159. /*
  160.  * Output a given code.
  161.  * Inputs:
  162.  *      code:   A n_bits-bit integer.  If == -1, then EOF.  This assumes
  163.  *              that n_bits =< (long)wordsize - 1.
  164.  * Outputs:
  165.  *      Outputs code to the file.
  166.  * Assumptions:
  167.  *      Chars are 8 bits long.
  168.  * Algorithm:
  169.  *      Maintain a BITS character long buffer (so that 8 codes will
  170.  * fit in it exactly).  When the buffer fills up empty it and start over.
  171.  */
  172.  
  173. static INT putcode(code,t)             /* output a code */
  174. INT code;                              /* code to output */
  175. FILE *t;                               /* where to put it */
  176. {
  177.     INT r_off = offset;                /* right offset */
  178.     INT bits = n_bits;                 /* bits to go */
  179.     unsigned char *bp = buf;           /* buffer pointer */
  180.     INT n;                             /* index */
  181.  
  182.     if (code >= 0)                     /* if a real code */
  183.     {
  184.         bp += (r_off >> 3);            /* Get to the first byte. */
  185.         r_off &= 7;
  186.  
  187.         /*
  188.          * Since code is always >= 8 bits, only need to mask the first
  189.          * hunk on the left.
  190.          */
  191.  
  192.         *bp = (*bp&rmask[r_off]) | (code<<r_off) & lmask[r_off];
  193.         bp++;
  194.         bits -= (8 - r_off);
  195.         code >>= (8 - r_off);
  196.  
  197.         /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  198.  
  199.         if (bits >= 8)
  200.         {
  201.             *bp++ = code;
  202.             code >>= 8;
  203.             bits -= 8;
  204.         }
  205.  
  206.         /* Last bits. */
  207.  
  208.         if (bits)
  209.             *bp = code;
  210.  
  211.         offset += n_bits;
  212.  
  213.         if (offset == (n_bits << 3))
  214.         {
  215.             bp = buf;
  216.             bits = n_bits;
  217.             bytes_out += bits;
  218.             do
  219.                 putc_pak(*bp++,t);
  220.             while (--bits);
  221.             offset = 0;
  222.         }
  223.  
  224.         /*
  225.          * If the next entry is going to be too big for the code size,
  226.          * then increase it, if possible.
  227.          */
  228.  
  229.         if (free_ent>maxcode || clear_flg>0)
  230.         {
  231.             /*
  232.              * Write the whole buffer, because the input side won't
  233.              * discover the size increase until after it has read it.
  234.              */
  235.  
  236.             if (offset > 0)
  237.             {
  238.                 bp = buf;              /* reset pointer for writing */
  239.                 bytes_out += n = n_bits;
  240.                 while (n--)
  241.                     putc_pak(*bp++,t);
  242.             }
  243.             offset = 0;
  244.  
  245.             if (clear_flg)             /* reset if clearing */
  246.             {
  247.                 maxcode = MAXCODE(n_bits = INIT_BITS);
  248.                 clear_flg = 0;
  249.             }
  250.             else                       /* else use more bits */
  251.             {
  252.                 n_bits++;
  253.                 if (n_bits == BITS)
  254.                     maxcode = maxcodemax;
  255.                 else
  256.                     maxcode = MAXCODE(n_bits);
  257.             }
  258.         }
  259.     }
  260.     else                               /* dump the buffer on EOF */
  261.     {
  262.         bytes_out += n = (offset+7) / 8;
  263.  
  264.         if (offset > 0)
  265.             while (n--)
  266.                 putc_pak(*bp++,t);
  267.         offset = 0;
  268.     }
  269. }
  270.  
  271. /*
  272.  * Read one code from the standard input.  If EOF, return -1.
  273.  * Inputs:
  274.  *      cmpin
  275.  * Outputs:
  276.  *      code or -1 is returned.
  277.  */
  278.  
  279. static INT getcode(f)                  /* get a code */
  280. FILE *f;                               /* file to get from */
  281. {
  282.     INT code;
  283.     static INT offset = 0, size = 0;
  284.     INT r_off, bits;
  285.     unsigned char *bp = buf;
  286.  
  287.     if (clear_flg > 0 || offset >= size || free_ent > maxcode)
  288.     {
  289.         /*
  290.          * If the next entry will be too big for the current code
  291.          * size, then we must increase the size.  This implies reading
  292.          * a new buffer full, too.
  293.          */
  294.  
  295.         if (free_ent > maxcode)
  296.         {
  297.             n_bits++;
  298.             if (n_bits == BITS)
  299.                 maxcode = maxcodemax;  /* won't get any bigger now */
  300.             else
  301.                 maxcode = MAXCODE(n_bits);
  302.         }
  303.         if (clear_flg > 0)
  304.         {
  305.             maxcode = MAXCODE(n_bits = INIT_BITS);
  306.             clear_flg = 0;
  307.         }
  308.  
  309.         for (size=0; size<n_bits; size++)
  310.         {
  311.             if ((code=getc_unp(f))==EOF)
  312.                 break;
  313.             else
  314.                 buf[size] = code;
  315.         }
  316.         if (size <= 0)
  317.             return(-1);                /* end of file */
  318.  
  319.         offset = 0;
  320.  
  321.         /* Round size down to integral number of codes */
  322.  
  323.         size = (size << 3)-(n_bits - 1);
  324.     }
  325.     r_off = offset;
  326.     bits = n_bits;
  327.  
  328.     /* Get to the first byte. */
  329.  
  330.     bp +=(r_off >> 3);
  331.     r_off &= 7;
  332.  
  333.     /* Get first part (low order bits) */
  334.  
  335.     code = (*bp++ >> r_off);
  336.     bits -= 8 - r_off;
  337.     r_off = 8 - r_off;                 /* now, offset into code word */
  338.  
  339.     /* Get any 8 bit parts in the middle (<=1 for up to 16 bits). */
  340.  
  341.     if (bits >= 8)
  342.     {
  343.         code |= *bp++ << r_off;
  344.         r_off += 8;
  345.         bits -= 8;
  346.     }
  347.  
  348.     /* high order bits. */
  349.  
  350.     code |= (*bp & rmask[bits]) << r_off;
  351.     offset += n_bits;
  352.  
  353.     return(code);
  354. }
  355.  
  356. /*
  357.  * compress a file
  358.  *
  359.  * Algorithm:  use open addressing double hashing (no chaining) on the
  360.  * prefix code / next character combination.  We do a variant of Knuth's
  361.  * algorithm D (vol. 3, sec. 6.4) along with G. Knott's relatively-prime
  362.  * secondary probe.  Here, the modular division first probe is gives way
  363.  * to a faster exclusive-or manipulation.  Also do block compression with
  364.  * an adaptive reset, where the code table is cleared when the compression
  365.  * ratio decreases, but after the table fills.  The variable-length output
  366.  * codes are re-sized at this point, and a special CLEAR code is generated
  367.  * for the decompressor.
  368.  */
  369.  
  370. INT init_cm(f,t)                       /* initialize for compression */
  371. FILE *f;                               /* file we will be compressing */
  372. FILE *t;                               /* where we will put it */
  373. {
  374.     offset = 0;
  375.     bytes_out = 1;
  376.     clear_flg = 0;
  377.     ratio = 0;
  378.     in_count = 1;
  379.     checkpoint = CHECK_GAP;
  380.     maxcode = MAXCODE(n_bits = INIT_BITS);
  381.     free_ent = FIRST;
  382.     setmem(htab,HSIZE*sizeof(long),0xff);
  383.     n_bits = INIT_BITS;                /* set starting code size */
  384.  
  385.     putc_pak(BITS,t);                  /* note our max code length */
  386.  
  387.     firstcmp = 1;                      /* next byte will be first */
  388. }
  389.  
  390. INT putc_cm(c,t)                       /* compress a character */
  391. unsigned char c;                       /* character to compress */
  392. FILE *t;                               /* where to put it */
  393. {
  394.     static long fcode;
  395.     static INT hshift;
  396.     INT i;
  397.     INT disp;
  398.  
  399.     if (firstcmp)                      /* special case for first byte */
  400.     {
  401.         ent = c;                       /* remember first byte */
  402.  
  403.         hshift = 0;
  404.         for (fcode=(long)HSIZE;  fcode<65536L; fcode*=2L)
  405.             hshift++;
  406.         hshift = 8 - hshift;           /* set hash code range bund */
  407.  
  408.         firstcmp = 0;                  /* no longer first */
  409.         return;
  410.     }
  411.  
  412.     in_count++;
  413.     fcode =(long)(((long)c << BITS)+ent);
  414.     i = (c<<hshift)^ent;               /* xor hashing */
  415.  
  416.     if (htab[i]==fcode)
  417.     {
  418.         ent = codetab[i];
  419.         return;
  420.     }
  421.     else if (htab[i]<0)                /* empty slot */
  422.         goto nomatch;
  423.     disp = HSIZE - i;                  /* secondary hash (after G.Knott) */
  424.     if (i == 0)
  425.         disp = 1;
  426.  
  427. probe:
  428.     if ((i -= disp) < 0)
  429.         i += HSIZE;
  430.  
  431.     if (htab[i] == fcode)
  432.     {
  433.         ent = codetab[i];
  434.         return;
  435.     }
  436.     if (htab[i] > 0)
  437.         goto probe;
  438.  
  439. nomatch:
  440.     putcode(ent,t);
  441.     ent = c;
  442.     if (free_ent < maxcodemax)
  443.     {
  444.         codetab[i] = free_ent++;       /* code -> hashtable */
  445.         htab[i] = fcode;
  446.     }
  447.     else if ((long)in_count >= checkpoint)
  448.         cl_block(t);
  449. }
  450.  
  451. long pred_cm(t)                        /* finish compressing a file */
  452. FILE *t;                               /* where to put it */
  453. {
  454.     putcode(ent,t);                    /* put out the final code */
  455.     putcode(-1,t);                     /* tell output we are done */
  456.  
  457.     return(bytes_out);                 /* say how big it got */
  458. }
  459.  
  460. /*
  461.  * Decompress a file.  This routine adapts to the codes in the file
  462.  * building the string table on-the-fly; requiring no table to be stored
  463.  * in the compressed file.  The tables used herein are shared with those of
  464.  * the compress() routine.  See the definitions above.
  465.  */
  466.  
  467. INT decomp(f,t)                        /* decompress a file */
  468. FILE *f;                               /* file to read codes from */
  469. FILE *t;                               /* file to write text to */
  470. {
  471.     unsigned char *stackp;
  472.     INT finchar;
  473.     INT code, oldcode, incode;
  474.  
  475.     if ((code=getc_unp(f))!=BITS)
  476.         abort("File packed with %d bits, I can only handle %d",code,BITS);
  477.  
  478.     n_bits = INIT_BITS;                /* set starting code size */
  479.     clear_flg = 0;
  480.  
  481.     /* As above, initialize the first 256 entries in the table. */
  482.  
  483.     maxcode = MAXCODE(n_bits=INIT_BITS);
  484.     for (code = 255; code >= 0; code--)
  485.     {
  486.         prefix[code] = 0;
  487.         suffix[code] = (unsigned char)code;
  488.     }
  489.     free_ent = FIRST;
  490.  
  491.     finchar = oldcode = getcode(f);
  492.     if (oldcode == -1)                 /* EOF already? */
  493.         return;                        /* Get out of here */
  494.     putc_ncr((char)finchar,t);         /* first code must be 8 bits=char */
  495.     stackp = stack;
  496.  
  497.     while ((code = getcode(f))> -1)
  498.     {
  499.         if (code==CLEAR)
  500.         {
  501.             for (code = 255; code >= 0; code--)
  502.                 prefix[code] = 0;
  503.             clear_flg = 1;
  504.             free_ent = FIRST - 1;
  505.             if ((code=getcode(f))==-1) /* O, untimely death! */
  506.                 break;
  507.         }
  508.         incode = code;
  509.  
  510.         /* Special case for KwKwK string. */
  511.  
  512.         if (code >= free_ent)
  513.         {
  514.             *stackp++ = finchar;
  515.             code = oldcode;
  516.         }
  517.  
  518.         /* Generate output characters in reverse order */
  519.  
  520.         while (code >= 256)
  521.         {
  522.             *stackp++ = suffix[code];
  523.             code = prefix[code];
  524.         }
  525.         *stackp++ = finchar = suffix[code];
  526.  
  527.         /* And put them out in forward order */
  528.  
  529.         do
  530.             putc_ncr(*--stackp,t);
  531.         while (stackp > stack);
  532.  
  533.         /* Generate the new entry. */
  534.  
  535.         if ((code=free_ent) < maxcodemax)
  536.         {
  537.             prefix[code] = (unsigned short)oldcode;
  538.             suffix[code] = finchar;
  539.             free_ent = code+1;
  540.         }
  541.  
  542.         /* Remember previous code. */
  543.  
  544.         oldcode = incode;
  545.     }
  546. }
  547.  
  548.  
  549. /*
  550.  * Please note how much trouble it can be to maintain upwards
  551.  * compatibility.  All that follows is for the sole purpose of unpacking
  552.  * files which were packed using an older method.
  553.  */
  554.  
  555.  
  556. /*
  557.  *  The h() pointer points to the routine to use for calculating a hash
  558.  *  value.  It is set in the init routines to point to either of oldh()
  559.  *  or newh().
  560.  *
  561.  *  oldh() calculates a hash value by taking the middle twelve bits
  562.  *  of the square of the key.
  563.  *
  564.  *  newh() works somewhat differently, and was tried because it makes
  565.  *  ARC about 23% faster.  This approach was abandoned because dynamic
  566.  *  Lempel-Zev (above) works as well, and packs smaller also.  However,
  567.  *  inadvertent release of a developmental copy forces us to leave this in.
  568.  */
  569.  
  570. static unsigned INT (*h)();            /* pointer to hash function */
  571.  
  572. static unsigned INT oldh(pred,foll)    /* old hash function */
  573. unsigned INT pred;                     /* code for preceeding string */
  574. unsigned char foll;                    /* value of following char */
  575. {
  576.     long local;                        /* local hash value */
  577.  
  578.     local = (pred + foll) | 0x0800;    /* create the hash key */
  579.     local *= local;                    /* square it */
  580.     return((local >> 6) & 0x0FFF);     /* return the middle 12 bits */
  581. }
  582.  
  583. static unsigned INT newh(pred,foll)    /* new hash function */
  584. unsigned INT pred;                     /* code for preceeding string */
  585. unsigned char foll;                    /* value of following char */
  586. {
  587.     return(((pred+foll)*15073)&0xFFF); /* faster hash */
  588. }
  589.  
  590. /*
  591.  *  The eolist() function is used to trace down a list of entries with
  592.  *  duplicate keys until the last duplicate is found.
  593.  */
  594.  
  595. static unsigned INT eolist(index)      /* find last duplicate */
  596. unsigned INT index;
  597. {
  598.     INT temp;
  599.  
  600.     while (temp=string_tab[index].next) /* while more duplicates */
  601.         index = temp;
  602.  
  603.     return(index);
  604. }
  605.  
  606. /*
  607.  *  The hash() routine is used to find a spot in the hash table for a new
  608.  *  entry.  It performs a "hash and linear probe" lookup, using h() to
  609.  *  calculate the starting hash value and eolist() to perform the linear
  610.  *  probe.  This routine DOES NOT detect a table full condition.  That
  611.  *  MUST be checked for elsewhere.
  612.  */
  613.  
  614. static unsigned INT hash(pred,foll)    /* find spot in the string table */
  615. unsigned INT pred;                     /* code for preceeding string */
  616. unsigned char foll;                    /* char following string */
  617. {
  618.     unsigned INT local, tempnext;      /* scratch storage */
  619.     struct entry *ep;                  /* allows faster table handling */
  620.  
  621.     local = (*h)(pred,foll);           /* get initial hash value */
  622.  
  623.     if (!string_tab[local].used)       /* if that spot is free */
  624.         return(local);                 /* then that's all we need */
  625.     else                               /* else a collision has occured */
  626.     {
  627.         local = eolist(local);         /* move to last duplicate */
  628.  
  629.         /*
  630.          * We must find an empty spot. We start looking 101 places
  631.          * down the table from the last duplicate.
  632.          */
  633.  
  634.         tempnext = (local+101) & 0x0FFF;
  635.         ep = &string_tab[tempnext];    /* initialize pointer */
  636.  
  637.         while (ep->used)               /* while empty spot not found */
  638.         {
  639.             if (++tempnext==TABSIZE)   /* if we are at the end */
  640.             {
  641.                 tempnext = 0;          /* wrap to beginning of table*/
  642.                 ep = string_tab;
  643.             }
  644.             else
  645.                 ++ep;                  /* point to next element in table */
  646.         }
  647.  
  648.         /*
  649.          * local still has the pointer to the last duplicate, while
  650.          * tempnext has the pointer to the spot we found.  We use
  651.          * this to maintain the chain of pointers to duplicates.
  652.          */
  653.  
  654.         string_tab[local].next = tempnext;
  655.  
  656.         return(tempnext);
  657.     }
  658. }
  659.  
  660. /*
  661.  * The init_tab() routine is used to initialize our hash table.
  662.  * You realize, of course, that "initialize" is a complete misnomer.
  663.  */
  664.  
  665. static INT init_tab()                  /* set ground state in hash table */
  666. {
  667.     unsigned INT i;                    /* table index */
  668.     INT upd_tab();
  669.  
  670.     setmem((char *)string_tab,sizeof(string_tab),0);
  671.  
  672.     for (i=0; i<256; i++)              /* list all single byte strings */
  673.         upd_tab(NO_PRED,i);
  674.  
  675.     inbuf = EMPTY;                     /* nothing is in our buffer */
  676. }
  677.  
  678. /*
  679.  * The upd_tab routine is used to add a new entry to the string table.
  680.  * As previously stated, no checks are made to ensure that the table
  681.  * has any room.  This must be done elsewhere.
  682.  */
  683.  
  684. INT upd_tab(pred,foll)                 /* add an entry to the table */
  685. unsigned INT pred;                     /* code for preceeding string */
  686. unsigned INT foll;                     /* character which follows string */
  687. {
  688.     struct entry *ep;                  /* pointer to current entry */
  689.  
  690.     /* calculate offset just once */
  691.  
  692.     ep = &string_tab[hash(pred,foll)];
  693.  
  694.     ep->used = TRUE;                   /* this spot is now in use */
  695.     ep->next = 0;                      /* no duplicates after this yet */
  696.     ep->predecessor = pred;            /* note code of preceeding string */
  697.     ep->follower = foll;               /* note char after string */
  698. }
  699.  
  700. /*
  701.  * This algorithm encoded a file into twelve bit strings (three nybbles).
  702.  * The gocode() routine is used to read these strings a byte (or two)
  703.  * at a time.
  704.  */
  705.  
  706. static INT gocode(fd)                  /* read in a twelve bit code */
  707. FILE *fd;                              /* file to get code from */
  708. {
  709.     unsigned INT localbuf, returnval;
  710.  
  711.     if (inbuf==EMPTY)                  /* if on a code boundary */
  712.     {
  713.         if ((localbuf=getc_unp(fd))==EOF) /* get start of next code */
  714.             return(EOF);               /* pass back end of file status */
  715.         localbuf &= 0xFF;              /* mask down to true byte value */
  716.         if ((inbuf=getc_unp(fd))==EOF) /* get end of code, start of next */
  717.             return(EOF);               /* this should never happen */
  718.         inbuf &= 0xFF;                 /* mask down to true byte value */
  719.  
  720.         returnval = ((localbuf<<4)&0xFF0) + ((inbuf>>4)&0x00F);
  721.         inbuf &= 0x000F;               /* leave partial code pending */
  722.     }
  723.     else                               /* buffer contains first nybble */
  724.     {
  725.         if ((localbuf=getc_unp(fd))==EOF)
  726.             return(EOF);
  727.         localbuf &= 0xFF;
  728.  
  729.         returnval = localbuf + ((inbuf<<8)&0xF00);
  730.         inbuf = EMPTY;                 /* note no hanging nybbles */
  731.     }
  732.     return(returnval);                 /* pass back assembled code */
  733. }
  734.  
  735. static INT push(c)                     /* push char onto stack */
  736. INT c;                                 /* character to push */
  737. {
  738.     stack[sp] = ((char) c);            /* coerce integer into a char */
  739.  
  740.     if (++sp >= TABSIZE)
  741.         abort("Stack overflow\n");
  742. }
  743.  
  744. static INT pop()                       /* pop character from stack */
  745. {
  746.     if (sp>0)
  747.         return(((INT) stack[--sp]));   /* leave ptr at next empty slot */
  748.     else
  749.         return(EMPTY);
  750. }
  751.  
  752. /***** LEMPEL-ZEV DECOMPRESSION *****/
  753.  
  754. static INT code_count;                 /* needed to detect table full */
  755. static INT firstc;                     /* true only on first character */
  756.  
  757. INT init_ucr(new)                      /* get set for uncrunching */
  758. INT new;                               /* true to use new hash function */
  759. {
  760.     if (new)                           /* set proper hash function */
  761.         h = newh;
  762.     else
  763.         h = oldh;
  764.  
  765.     sp = 0;                            /* clear out the stack */
  766.     init_tab();                        /* set up atomic code definitions */
  767.     code_count = TABSIZE - 256;        /* note space left in table */
  768.     firstc = 1;                        /* true only on first code */
  769. }
  770.  
  771. INT getc_ucr(f)                        /* get next uncrunched byte */
  772. FILE *f;                               /* file containing crunched data */
  773. {
  774.     INT code, newcode;
  775.     static INT oldcode, finchar;
  776.     struct entry *ep;                  /* allows faster table handling */
  777.  
  778.     if (firstc)                        /* first code is always known */
  779.     {
  780.         firstc = FALSE;                /* but next will not be first */
  781.         oldcode = gocode(f);
  782.         return(finchar = string_tab[oldcode].follower);
  783.     }
  784.  
  785.     if (!sp)                           /* if stack is empty */
  786.     {
  787.         if ((code=newcode=gocode(f))==EOF)
  788.             return(EOF);
  789.  
  790.         ep = &string_tab[code];        /* initialize pointer */
  791.  
  792.         if (!ep->used)                 /* if code isn't known */
  793.         {
  794.             code = oldcode;
  795.             ep = &string_tab[code];    /* re-initialize pointer */
  796.             push(finchar);
  797.         }
  798.  
  799.         while (ep->predecessor!=NO_PRED)
  800.         {
  801.             push(ep->follower);        /* decode string backwards */
  802.             code = ep->predecessor;
  803.             ep = &string_tab[code];
  804.         }
  805.  
  806.         push(finchar=ep->follower);    /* save first character also */
  807.  
  808.         /*
  809.          * The above loop will terminate, one way or another,
  810.          * with string_tab[code].follower equal to the first
  811.          * character in the string.
  812.          */
  813.  
  814.         if (code_count)                /* if room left in string table */
  815.         {
  816.             upd_tab(oldcode,finchar);
  817.             --code_count;
  818.         }
  819.  
  820.         oldcode = newcode;
  821.     }
  822.  
  823.     return(pop());                     /* return saved character */
  824. }
  825.