home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 4 / Apprentice-Release4.iso / Source Code / C / Snippets / MacLZSS 1.0.2 / lzss.c < prev    next >
Encoding:
Text File  |  1996-01-04  |  8.8 KB  |  258 lines  |  [TEXT/CWIE]

  1. // MacLZSS
  2. // version 1.0.1
  3. // ported to CW7 on 951215
  4.  
  5. /**************************************************************
  6.     LZSS.C -- A Data Compression Program
  7.     (tab = 4 spaces)
  8. ***************************************************************
  9.     4/6/1989 Haruhiko Okumura
  10.     Use, distribute, and modify this program freely.
  11.     Please send me your improved versions.
  12.         PC-VAN        SCIENCE
  13.         NIFTY-Serve    PAF01022
  14.         CompuServe    74050,1022
  15.     
  16.     ---    
  17.     26 May 1989 Modifications by Rob Elliott
  18.     Usenet     rob@embossed.com
  19.     FidoNet    1:115/729
  20.     CompuServe 70675,1204
  21.     
  22.     Converted to AT&T System V UNIX, then Macintosh THINK 'C'
  23.     
  24.     - Changed function prototypes into old-style declarations,
  25.     e.g.         void DecodeChar(int x)
  26.     becomes     void DecodeChar(x) int x;
  27.     - changed 'int' to 'short', 'unsigned' to 'long', etc. as
  28.     needed (system & compiler dependent)
  29.     
  30. **************************************************************/
  31.  
  32. #include <stdio.h>
  33. /* #include <stdlib.h>   not needed */
  34. #include <strings.h>    /* was string.h */
  35. #include <ctype.h>
  36. #define N         4096    /* size of ring buffer */
  37. #define F           18    /* upper limit for match_length */
  38. #define THRESHOLD    2   /* encode string into position and length
  39.                            if match_length is greater than this */
  40. #define NIL            N    /* index for root of binary search trees */
  41. #define EXIT_SUCCESS 0
  42. #define EXIT_FAILURE 1
  43. /* #define int short    needed for some UNIX versions */
  44.  
  45. unsigned long 
  46.         textsize = 0,    /* text size counter */
  47.         codesize = 0,    /* code size counter */
  48.         printcount = 0;    /* counter for reporting progress every 1K bytes */
  49. unsigned char
  50.         text_buf[N + F - 1];    /* ring buffer of size N,
  51.             with extra F-1 bytes to facilitate string comparison */
  52. int        match_position, match_length,  /* of longest match.  These are
  53.             set by the InsertNode() procedure. */
  54.         lson[N + 1], rson[N + 257], dad[N + 1];  /* left & right children &
  55.             parents -- These constitute binary search trees. */
  56. FILE    *infile, *outfile;  /* input & output files */
  57. void InitTree()  /* initialize trees */
  58.  
  59. {
  60.     int  i;
  61.     /* For i = 0 to N - 1, rson[i] and lson[i] will be the right and
  62.        left children of node i.  These nodes need not be initialized.
  63.        Also, dad[i] is the parent of node i.  These are initialized to
  64.        NIL (= N), which stands for 'not used.'
  65.        For i = 0 to 255, rson[N + i + 1] is the root of the tree
  66.        for strings that begin with character i.  These are initialized
  67.        to NIL.  Note there are 256 trees. */
  68.     for (i = N + 1; i <= N + 256; i++) rson[i] = NIL;
  69.     for (i = 0; i < N; i++) dad[i] = NIL;
  70. }
  71. void InsertNode(r)
  72. int r;
  73.     /* Inserts string of length F, text_buf[r..r+F-1], into one of the
  74.        trees (text_buf[r]'th tree) and returns the longest-match position
  75.        and length via the global variables match_position and match_length.
  76.        If match_length = F, then removes the old node in favor of the new
  77.        one, because the old one will be deleted sooner.
  78.        Note r plays double role, as tree node and position in buffer. */
  79. {
  80.     int  i, p, cmp;
  81.     unsigned char  *key;
  82.     cmp = 1;  key = &text_buf[r];  p = N + 1 + key[0];
  83.     rson[r] = lson[r] = NIL;  match_length = 0;
  84.     for ( ; ; ) {
  85.         if (cmp >= 0) {
  86.             if (rson[p] != NIL) p = rson[p];
  87.             else {  rson[p] = r;  dad[r] = p;  return;  }
  88.         } else {
  89.             if (lson[p] != NIL) p = lson[p];
  90.             else {  lson[p] = r;  dad[r] = p;  return;  }
  91.         }
  92.         for (i = 1; i < F; i++)
  93.             if ((cmp = key[i] - text_buf[p + i]) != 0)  break;
  94.         if (i > match_length) {
  95.             match_position = p;
  96.             if ((match_length = i) >= F)  break;
  97.         }
  98.     }
  99.     dad[r] = dad[p];  lson[r] = lson[p];  rson[r] = rson[p];
  100.     dad[lson[p]] = r;  dad[rson[p]] = r;
  101.     if (rson[dad[p]] == p) rson[dad[p]] = r;
  102.     else                   lson[dad[p]] = r;
  103.     dad[p] = NIL;  /* remove p */
  104. }
  105. void DeleteNode(p)  /* deletes node p from tree */
  106. int p;
  107. {
  108.     int  q;
  109.     
  110.     if (dad[p] == NIL) return;  /* not in tree */
  111.     if (rson[p] == NIL) q = lson[p];
  112.     else if (lson[p] == NIL) q = rson[p];
  113.     else {
  114.         q = lson[p];
  115.         if (rson[q] != NIL) {
  116.             do {  q = rson[q];  } while (rson[q] != NIL);
  117.             rson[dad[q]] = lson[q];  dad[lson[q]] = dad[q];
  118.             lson[q] = lson[p];  dad[lson[p]] = q;
  119.         }
  120.         rson[q] = rson[p];  dad[rson[p]] = q;
  121.     }
  122.     dad[q] = dad[p];
  123.     if (rson[dad[p]] == p) rson[dad[p]] = q;  else lson[dad[p]] = q;
  124.     dad[p] = NIL;
  125. }
  126. void Encode()
  127.  
  128. {
  129.     int  i, c, len, r, s, last_match_length, code_buf_ptr;
  130.     unsigned char  code_buf[17], mask;
  131.     
  132.     InitTree();  /* initialize trees */
  133.     code_buf[0] = 0;  /* code_buf[1..16] saves eight units of code, and
  134.         code_buf[0] works as eight flags, "1" representing that the unit
  135.         is an unencoded letter (1 byte), "0" a position-and-length pair
  136.         (2 bytes).  Thus, eight units require at most 16 bytes of code. */
  137.     code_buf_ptr = mask = 1;
  138.     s = 0;  r = N - F;
  139.     for (i = s; i < r; i++) text_buf[i] = ' ';  /* Clear the buffer with
  140.         any character that will appear often. */
  141.     for (len = 0; len < F && (c = getc(infile)) != EOF; len++)
  142.         text_buf[r + len] = c;  /* Read F bytes into the last F bytes of
  143.             the buffer */
  144.     if ((textsize = len) == 0) return;  /* text of size zero */
  145.     for (i = 1; i <= F; i++) InsertNode(r - i);  /* Insert the F strings,
  146.         each of which begins with one or more 'space' characters.  Note
  147.         the order in which these strings are inserted.  This way,
  148.         degenerate trees will be less likely to occur. */
  149.     InsertNode(r);  /* Finally, insert the whole string just read.  The
  150.         global variables match_length and match_position are set. */
  151.     do {
  152.         if (match_length > len) match_length = len;  /* match_length
  153.             may be spuriously long near the end of text. */
  154.         if (match_length <= THRESHOLD) {
  155.             match_length = 1;  /* Not long enough match.  Send one byte. */
  156.             code_buf[0] |= mask;  /* 'send one byte' flag */
  157.             code_buf[code_buf_ptr++] = text_buf[r];  /* Send uncoded. */
  158.         } else {
  159.             code_buf[code_buf_ptr++] = (unsigned char) match_position;
  160.             code_buf[code_buf_ptr++] = (unsigned char)
  161.                 (((match_position >> 4) & 0xf0)
  162.               | (match_length - (THRESHOLD + 1)));  /* Send position and
  163.                     length pair. Note match_length > THRESHOLD. */
  164.         }
  165.         if ((mask <<= 1) == 0) {  /* Shift mask left one bit. */
  166.             for (i = 0; i < code_buf_ptr; i++)  /* Send at most 8 units of */
  167.                 putc(code_buf[i], outfile);     /* code together */
  168.             codesize += code_buf_ptr;
  169.             code_buf[0] = 0;  code_buf_ptr = mask = 1;
  170.         }
  171.         last_match_length = match_length;
  172.         for (i = 0; i < last_match_length &&
  173.                 (c = getc(infile)) != EOF; i++) {
  174.             DeleteNode(s);        /* Delete old strings and */
  175.             text_buf[s] = c;    /* read new bytes */
  176.             if (s < F - 1) text_buf[s + N] = c;  /* If the position is
  177.                 near the end of buffer, extend the buffer to make
  178.                 string comparison easier. */
  179.             s = (s + 1) & (N - 1);  r = (r + 1) & (N - 1);
  180.                 /* Since this is a ring buffer, increment the position
  181.                    modulo N. */
  182.             InsertNode(r);    /* Register the string in text_buf[r..r+F-1] */
  183.         }
  184.         if ((textsize += i) > printcount) {
  185.             printf("%12ld\r", textsize);  printcount += 1024;
  186.                 /* Reports progress each time the textsize exceeds
  187.                    multiples of 1024. */
  188.         }
  189.         while (i++ < last_match_length) {    /* After the end of text, */
  190.             DeleteNode(s);                    /* no need to read, but */
  191.             s = (s + 1) & (N - 1);  r = (r + 1) & (N - 1);
  192.             if (--len) InsertNode(r);        /* buffer may not be empty. */
  193.         }
  194.     } while (len > 0);    /* until length of string to be processed is zero */
  195.     if (code_buf_ptr > 1) {        /* Send remaining code. */
  196.         for (i = 0; i < code_buf_ptr; i++) putc(code_buf[i], outfile);
  197.         codesize += code_buf_ptr;
  198.     }
  199.     printf("In : %ld bytes\n", textsize);    /* Encoding is done. */
  200.     printf("Out: %ld bytes\n", codesize);
  201.     printf("Out/In: %.3f\n", (double)codesize / textsize);
  202. }
  203. void Decode()    /* Just the reverse of Encode(). */
  204.  
  205. {
  206.     int  i, j, k, r, c;
  207.     unsigned int  flags;
  208.     
  209.     for (i = 0; i < N - F; i++) text_buf[i] = ' ';
  210.     r = N - F;  flags = 0;
  211.     for ( ; ; ) {
  212.         if (((flags >>= 1) & 256) == 0) {
  213.             if ((c = getc(infile)) == EOF) break;
  214.             flags = c | 0xff00;        /* uses higher byte cleverly */
  215.         }                            /* to count eight */
  216.         if (flags & 1) {
  217.             if ((c = getc(infile)) == EOF) break;
  218.             putc(c, outfile);  text_buf[r++] = c;  r &= (N - 1);
  219.         } else {
  220.             if ((i = getc(infile)) == EOF) break;
  221.             if ((j = getc(infile)) == EOF) break;
  222.             i |= ((j & 0xf0) << 4);  j = (j & 0x0f) + THRESHOLD;
  223.             for (k = 0; k <= j; k++) {
  224.                 c = text_buf[(i + k) & (N - 1)];
  225.                 putc(c, outfile);  text_buf[r++] = c;  r &= (N - 1);
  226.             }
  227.         }
  228.     }
  229. }
  230. int _main(argc, argv)
  231. int argc;
  232. char *argv[];
  233. {
  234.     char  *s;
  235.     
  236. /*    infile = stdin;                For filter operation
  237.     outfile = stdout;
  238.     if (argc > 1) {
  239.         printf("Decoding...\n");
  240.         Decode(); }
  241.     else
  242.         Encode();*/
  243.  
  244.     if (argc != 4) {
  245.         printf("'lzss e file1 file2' encodes file1 into file2.\n"
  246.                "'lzss d file2 file1' decodes file2 into file1.\n");
  247.         return EXIT_FAILURE;
  248.     }
  249.     if ((s = argv[1], s[1] || strpbrk(s, "DEde") == NULL)
  250.      || (s = argv[2], (infile  = fopen(s, "rb")) == NULL)
  251.      || (s = argv[3], (outfile = fopen(s, "wb")) == NULL)) {
  252.         printf("??? %s\n", s);  return EXIT_FAILURE;
  253.     }
  254.     if (toupper(*argv[1]) == 'E') Encode();  else Decode();
  255.     fclose(infile);  fclose(outfile);
  256.     return EXIT_SUCCESS;
  257. }
  258.