LZARI.C
Upload User: szqxhk
Upload Date: 2010-02-15
Package Size: 54k
Code Size: 13k
Development Platform:

Visual C++

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