home *** CD-ROM | disk | FTP | other *** search
/ GEMini Atari / GEMini_Atari_CD-ROM_Walnut_Creek_December_1993.iso / files / archiver / lzarc / lzari.c < prev    next >
C/C++ Source or Header  |  1989-05-29  |  13KB  |  476 lines

  1. /**************************************************************
  2.     LZARI.C -- A Data Compression Program
  3.     (tab = 4 spaces)
  4. ***************************************************************
  5.     4/7/1989 Haruhiko Okumura
  6.     Use, distribute, and modify this program freely.
  7.     Please send me your improved versions.
  8.         PC-VAN        SCIENCE
  9.         NIFTY-Serve    PAF01022
  10.         CompuServe    74050,1022
  11. **************************************************************/
  12. #include <stdio.h>
  13. /*
  14. #include <stdlib.h>
  15. #include <string.h>
  16. */
  17. #include <ctype.h>
  18.  
  19. /********** Bit I/O **********/
  20.  
  21. FILE  *infile, *outfile;
  22. unsigned long int  textsize = 0, codesize = 0, printcount = 0;
  23.  
  24. #define EXIT_FAILURE -1
  25. #define EXIT_SUCCESS 0
  26. #define SEEK_END 2 
  27.  
  28. void Error(message)
  29. char *message;
  30. {
  31.     printf("\n%s\n", message);
  32.     exit(EXIT_FAILURE);
  33. }
  34.  
  35. void PutBit(bit)  /* Output one bit (bit = 0,1) */
  36. int bit;
  37. {
  38.     static unsigned int  buffer = 0, mask = 128;
  39.     
  40.     if (bit) buffer |= mask;
  41.     if ((mask >>= 1) == 0) {
  42.         if (putc(buffer, outfile) == EOF) Error("Write Error");
  43.         buffer = 0;  mask = 128;  codesize++;
  44.     }
  45. }
  46.  
  47. void FlushBitBuffer()  /* Send remaining bits */
  48. {
  49.     int  i;
  50.     
  51.     for (i = 0; i < 7; i++) PutBit(0);
  52. }
  53.  
  54. int GetBit()  /* Get one bit (0 or 1) */
  55. {
  56.     static unsigned int  buffer, mask = 0;
  57.     
  58.     if ((mask >>= 1) == 0) {
  59.         buffer = getc(infile);  mask = 128;
  60.     }
  61.     return ((buffer & mask) != 0);
  62. }
  63.  
  64. /********** LZSS with multiple binary trees **********/
  65.  
  66. #define N         4096    /* size of ring buffer */
  67. #define F           60    /* upper limit for match_length */
  68. #define THRESHOLD    2   /* encode string into position and length
  69.                            if match_length is greater than this */
  70. #define NIL            N    /* index for root of binary search trees */
  71.  
  72. unsigned char  text_buf[N + F - 1];    /* ring buffer of size N,
  73.             with extra F-1 bytes to facilitate string comparison */
  74. int        match_position, match_length,  /* of longest match.  These are
  75.             set by the InsertNode() procedure. */
  76.         lson[N + 1], rson[N + 257], dad[N + 1];  /* left & right children &
  77.             parents -- These constitute binary search trees. */
  78.  
  79. void InitTree()  /* Initialize trees */
  80. {
  81.     int  i;
  82.  
  83.     /* For i = 0 to N - 1, rson[i] and lson[i] will be the right and
  84.        left children of node i.  These nodes need not be initialized.
  85.        Also, dad[i] is the parent of node i.  These are initialized to
  86.        NIL (= N), which stands for 'not used.'
  87.        For i = 0 to 255, rson[N + i + 1] is the root of the tree
  88.        for strings that begin with character i.  These are initialized
  89.        to NIL.  Note there are 256 trees. */
  90.  
  91.     for (i = N + 1; i <= N + 256; i++) rson[i] = NIL;    /* root */
  92.     for (i = 0; i < N; i++) dad[i] = NIL;    /* node */
  93. }
  94.  
  95. void InsertNode(r)
  96.     /* Inserts string of length F, text_buf[r..r+F-1], into one of the
  97.        trees (text_buf[r]'th tree) and returns the longest-match position
  98.        and length via the global variables match_position and match_length.
  99.        If match_length = F, then removes the old node in favor of the new
  100.        one, because the old one will be deleted sooner.
  101.        Note r plays double role, as tree node and position in buffer. */
  102. int r;
  103. {
  104.     int  i, p, cmp, temp;
  105.     unsigned char  *key;
  106.  
  107.     cmp = 1;  key = &text_buf[r];  p = N + 1 + key[0];
  108.     rson[r] = lson[r] = NIL;  match_length = 0;
  109.     for ( ; ; ) {
  110.         if (cmp >= 0) {
  111.             if (rson[p] != NIL) p = rson[p];
  112.             else {  rson[p] = r;  dad[r] = p;  return;  }
  113.         } else {
  114.             if (lson[p] != NIL) p = lson[p];
  115.             else {  lson[p] = r;  dad[r] = p;  return;  }
  116.         }
  117.         for (i = 1; i < F; i++)
  118.             if ((cmp = key[i] - text_buf[p + i]) != 0)  break;
  119.         if (i > THRESHOLD) {
  120.             if (i > match_length) {
  121.                 match_position = (r - p) & (N - 1);
  122.                 if ((match_length = i) >= F) break;
  123.             } else if (i == match_length) {
  124.                 if ((temp = (r - p) & (N - 1)) < match_position)
  125.                     match_position = temp;
  126.             }
  127.         }
  128.     }
  129.     dad[r] = dad[p];  lson[r] = lson[p];  rson[r] = rson[p];
  130.     dad[lson[p]] = r;  dad[rson[p]] = r;
  131.     if (rson[dad[p]] == p) rson[dad[p]] = r;
  132.     else                   lson[dad[p]] = r;
  133.     dad[p] = NIL;  /* remove p */
  134. }
  135.  
  136. void DeleteNode(p)  /* Delete node p from tree */
  137. int p;
  138. {
  139.     int  q;
  140.     
  141.     if (dad[p] == NIL) return;  /* not in tree */
  142.     if (rson[p] == NIL) q = lson[p];
  143.     else if (lson[p] == NIL) q = rson[p];
  144.     else {
  145.         q = lson[p];
  146.         if (rson[q] != NIL) {
  147.             do {  q = rson[q];  } while (rson[q] != NIL);
  148.             rson[dad[q]] = lson[q];  dad[lson[q]] = dad[q];
  149.             lson[q] = lson[p];  dad[lson[p]] = q;
  150.         }
  151.         rson[q] = rson[p];  dad[rson[p]] = q;
  152.     }
  153.     dad[q] = dad[p];
  154.     if (rson[dad[p]] == p) rson[dad[p]] = q;
  155.     else                   lson[dad[p]] = q;
  156.     dad[p] = NIL;
  157. }
  158.  
  159. /********** Arithmetic Compression **********/
  160.  
  161. /*  If you are not familiar with arithmetic compression, you should read
  162.         I. E. Witten, R. M. Neal, and J. G. Cleary,
  163.             Communications of the ACM, Vol. 30, pp. 520-540 (1987),
  164.     from which much have been borrowed.  */
  165.  
  166. #define M   15
  167.  
  168. /*    Q1 (= 2 to the M) must be sufficiently large, but not so
  169.     large as the unsigned long 4 * Q1 * (Q1 - 1) overflows.  */
  170.  
  171. #define Q1  (1UL << M)
  172. #define Q2  (2 * Q1)
  173. #define Q3  (3 * Q1)
  174. #define Q4  (4 * Q1)
  175. #define MAX_CUM (Q1 - 1)
  176.  
  177. #define N_CHAR  (256 - THRESHOLD + F)
  178.     /* character code = 0, 1, ..., N_CHAR - 1 */
  179.  
  180. unsigned long int  low = 0, high = Q4, value = 0;
  181. int  shifts = 0;  /* counts for magnifying low and high around Q2 */
  182. int  char_to_sym[N_CHAR], sym_to_char[N_CHAR + 1];
  183. unsigned int
  184.     sym_freq[N_CHAR + 1],  /* frequency for symbols */
  185.     sym_cum[N_CHAR + 1],   /* cumulative freq for symbols */
  186.     position_cum[N + 1];   /* cumulative freq for positions */
  187.  
  188. void StartModel()  /* Initialize model */
  189. {
  190.     int ch, sym, i;
  191.     
  192.     sym_cum[N_CHAR] = 0;
  193.     for (sym = N_CHAR; sym >= 1; sym--) {
  194.         ch = sym - 1;
  195.         char_to_sym[ch] = sym;  sym_to_char[sym] = ch;
  196.         sym_freq[sym] = 1;
  197.         sym_cum[sym - 1] = sym_cum[sym] + sym_freq[sym];
  198.     }
  199.     sym_freq[0] = 0;  /* sentinel (!= sym_freq[1]) */
  200.     position_cum[N] = 0;
  201.     for (i = N; i >= 1; i--)
  202.         position_cum[i - 1] = position_cum[i] + 10000 / (i + 200);
  203.             /* empirical distribution function (quite tentative) */
  204.             /* Please devise a better mechanism! */
  205. }
  206.  
  207. void UpdateModel(sym)
  208. int sym;
  209. {
  210.     int i, c, ch_i, ch_sym;
  211.     
  212.     if (sym_cum[0] >= MAX_CUM) {
  213.         c = 0;
  214.         for (i = N_CHAR; i > 0; i--) {
  215.             sym_cum[i] = c;
  216.             c += (sym_freq[i] = (sym_freq[i] + 1) >> 1);
  217.         }
  218.         sym_cum[0] = c;
  219.     }
  220.     for (i = sym; sym_freq[i] == sym_freq[i - 1]; i--) ;
  221.     if (i < sym) {
  222.         ch_i = sym_to_char[i];    ch_sym = sym_to_char[sym];
  223.         sym_to_char[i] = ch_sym;  sym_to_char[sym] = ch_i;
  224.         char_to_sym[ch_i] = sym;  char_to_sym[ch_sym] = i;
  225.     }
  226.     sym_freq[i]++;
  227.     while (--i >= 0) sym_cum[i]++;
  228. }
  229.  
  230. static void Output(bit)
  231. int bit;  /* Output 1 bit, followed by its complements */
  232. {
  233.     PutBit(bit);
  234.     for ( ; shifts > 0; shifts--) PutBit(! bit);
  235. }
  236.  
  237. void EncodeChar(ch)
  238. int ch;
  239. {
  240.     int  sym;
  241.     unsigned long int  range;
  242.  
  243.     sym = char_to_sym[ch];
  244.     range = high - low;
  245.     high = low + (range * sym_cum[sym - 1]) / sym_cum[0];
  246.     low +=       (range * sym_cum[sym    ]) / sym_cum[0];
  247.     for ( ; ; ) {
  248.         if (high <= Q2) Output(0);
  249.         else if (low >= Q2) {
  250.             Output(1);  low -= Q2;  high -= Q2;
  251.         } else if (low >= Q1 && high <= Q3) {
  252.             shifts++;  low -= Q1;  high -= Q1;
  253.         } else break;
  254.         low += low;  high += high;
  255.     }
  256.     UpdateModel(sym);
  257. }
  258.  
  259. void EncodePosition(position)
  260. int position;
  261. {
  262.     unsigned long int  range;
  263.  
  264.     range = high - low;
  265.     high = low + (range * position_cum[position    ]) / position_cum[0];
  266.     low +=       (range * position_cum[position + 1]) / position_cum[0];
  267.     for ( ; ; ) {
  268.         if (high <= Q2) Output(0);
  269.         else if (low >= Q2) {
  270.             Output(1);  low -= Q2;  high -= Q2;
  271.         } else if (low >= Q1 && high <= Q3) {
  272.             shifts++;  low -= Q1;  high -= Q1;
  273.         } else break;
  274.         low += low;  high += high;
  275.     }
  276. }
  277.  
  278. void EncodeEnd()
  279. {
  280.     shifts++;
  281.     if (low < Q1) Output(0);  else Output(1);
  282.     FlushBitBuffer();  /* flush bits remaining in buffer */
  283. }
  284.  
  285. int BinarySearchSym(x)
  286. unsigned int x;
  287.     /* 1      if x >= sym_cum[1],
  288.        N_CHAR if sym_cum[N_CHAR] > x,
  289.        i such that sym_cum[i - 1] > x >= sym_cum[i] otherwise */
  290. {
  291.     int i, j, k;
  292.     
  293.     i = 1;  j = N_CHAR;
  294.     while (i < j) {
  295.         k = (i + j) / 2;
  296.         if (sym_cum[k] > x) i = k + 1;  else j = k;
  297.     }
  298.     return i;
  299. }
  300.  
  301. int BinarySearchPos(x)
  302. unsigned int x;
  303.     /* 0 if x >= position_cum[1],
  304.        N - 1 if position_cum[N] > x,
  305.        i such that position_cum[i] > x >= position_cum[i + 1] otherwise */
  306. {
  307.     int i, j, k;
  308.     
  309.     i = 1;  j = N;
  310.     while (i < j) {
  311.         k = (i + j) / 2;
  312.         if (position_cum[k] > x) i = k + 1;  else j = k;
  313.     }
  314.     return i - 1;
  315. }
  316.  
  317. void StartDecode()
  318. {
  319.     int i;
  320.  
  321.     for (i = 0; i < M + 2; i++)
  322.         value = 2 * value + GetBit();
  323. }
  324.  
  325. int DecodeChar()
  326. {
  327.     int     sym, ch;
  328.     unsigned long int  range;
  329.     
  330.     range = high - low;
  331.     sym = BinarySearchSym((unsigned int)
  332.         (((value - low + 1) * sym_cum[0] - 1) / range));
  333.     high = low + (range * sym_cum[sym - 1]) / sym_cum[0];
  334.     low +=       (range * sym_cum[sym    ]) / sym_cum[0];
  335.     for ( ; ; ) {
  336.         if (low >= Q2) {
  337.             value -= Q2;  low -= Q2;  high -= Q2;
  338.         } else if (low >= Q1 && high <= Q3) {
  339.             value -= Q1;  low -= Q1;  high -= Q1;
  340.         } else if (high > Q2) break;
  341.         low += low;  high += high;
  342.         value = 2 * value + GetBit();
  343.     }
  344.     ch = sym_to_char[sym];
  345.     UpdateModel(sym);
  346.     return ch;
  347. }
  348.  
  349. int DecodePosition()
  350. {
  351.     int position;
  352.     unsigned long int  range;
  353.     
  354.     range = high - low;
  355.     position = BinarySearchPos((unsigned int)
  356.         (((value - low + 1) * position_cum[0] - 1) / range));
  357.     high = low + (range * position_cum[position    ]) / position_cum[0];
  358.     low +=       (range * position_cum[position + 1]) / position_cum[0];
  359.     for ( ; ; ) {
  360.         if (low >= Q2) {
  361.             value -= Q2;  low -= Q2;  high -= Q2;
  362.         } else if (low >= Q1 && high <= Q3) {
  363.             value -= Q1;  low -= Q1;  high -= Q1;
  364.         } else if (high > Q2) break;
  365.         low += low;  high += high;
  366.         value = 2 * value + GetBit();
  367.     }
  368.     return position;
  369. }
  370.  
  371. /********** Encode and Decode **********/
  372.  
  373. void Encode()
  374. {
  375.     int  i, c, len, r, s, last_match_length;
  376.     
  377.     fseek(infile, 0L, SEEK_END);
  378.     textsize = ftell(infile);
  379.     if (fwrite(&textsize, sizeof textsize, 1, outfile) < 1)
  380.         Error("Write Error");  /* output size of text */
  381.     codesize += sizeof textsize;
  382.     if (textsize == 0) return;
  383.     rewind(infile);  textsize = 0;
  384.     StartModel();  InitTree();
  385.     s = 0;  r = N - F;
  386.     for (i = s; i < r; i++) text_buf[i] = ' ';
  387.     for (len = 0; len < F && (c = getc(infile)) != EOF; len++)
  388.         text_buf[r + len] = c;
  389.     textsize = len;
  390.     for (i = 1; i <= F; i++) InsertNode(r - i);
  391.     InsertNode(r);
  392.     do {
  393.         if (match_length > len) match_length = len;
  394.         if (match_length <= THRESHOLD) {
  395.             match_length = 1;  EncodeChar(text_buf[r]);
  396.         } else {
  397.             EncodeChar(255 - THRESHOLD + match_length);
  398.             EncodePosition(match_position - 1);
  399.         }
  400.         last_match_length = match_length;
  401.         for (i = 0; i < last_match_length &&
  402.                 (c = getc(infile)) != EOF; i++) {
  403.             DeleteNode(s);  text_buf[s] = c;
  404.             if (s < F - 1) text_buf[s + N] = c;
  405.             s = (s + 1) & (N - 1);
  406.             r = (r + 1) & (N - 1);
  407.             InsertNode(r);
  408.         }
  409.         if ((textsize += i) > printcount) {
  410.             printf("%12ld\r", textsize);  printcount += 1024;
  411.         }
  412.         while (i++ < last_match_length) {
  413.             DeleteNode(s);
  414.             s = (s + 1) & (N - 1);
  415.             r = (r + 1) & (N - 1);
  416.             if (--len) InsertNode(r);
  417.         }
  418.     } while (len > 0);
  419.     EncodeEnd();
  420.     printf("In : %lu bytes\n", textsize);
  421.     printf("Out: %lu bytes\n", codesize);
  422.     printf("Out/In: %.3f\n", (double)codesize / textsize);
  423. }
  424.  
  425. void Decode()
  426. {
  427.     int  i, j, k, r, c;
  428.     unsigned long int  count;
  429.  
  430.     if (fread(&textsize, sizeof textsize, 1, infile) < 1)
  431.         Error("Read Error");  /* read size of text */
  432.     if (textsize == 0) return;
  433.     StartDecode();  StartModel();
  434.     for (i = 0; i < N - F; i++) text_buf[i] = ' ';
  435.     r = N - F;
  436.     for (count = 0; count < textsize; ) {
  437.         c = DecodeChar();
  438.         if (c < 256) {
  439.             putc(c, outfile);  text_buf[r++] = c;
  440.             r &= (N - 1);  count++;
  441.         } else {
  442.             i = (r - DecodePosition() - 1) & (N - 1);
  443.             j = c - 255 + THRESHOLD;
  444.             for (k = 0; k < j; k++) {
  445.                 c = text_buf[(i + k) & (N - 1)];
  446.                 putc(c, outfile);  text_buf[r++] = c;
  447.                 r &= (N - 1);  count++;
  448.             }
  449.         }
  450.         if (count > printcount) {
  451.             printf("%12lu\r", count);  printcount += 1024;
  452.         }
  453.     }
  454.     printf("%12lu\n", count);
  455. }
  456.  
  457. int main(argc,argv)
  458. int argc; char *argv[];
  459. {
  460.     char  *s;
  461.     
  462.     if (argc != 4) {
  463.         printf("'lzari e file1 file2' encodes file1 into file2.\n"
  464.                "'lzari d file2 file1' decodes file2 into file1.\n");
  465.         return EXIT_FAILURE;
  466.     }
  467.     if ((s = argv[1], s[1] || strpbrk(s, "DEde") == NULL)
  468.      || (s = argv[2], (infile  = fopen(s, "rb")) == NULL)
  469.      || (s = argv[3], (outfile = fopen(s, "wb")) == NULL)) {
  470.         printf("??? %s\n", s);  return EXIT_FAILURE;
  471.     }
  472.     if (toupper(*argv[1]) == 'E') Encode();  else Decode();
  473.     fclose(infile);  fclose(outfile);
  474.     return EXIT_SUCCESS;
  475. }
  476.