home *** CD-ROM | disk | FTP | other *** search
/ Programmer 7500 / MAX_PROGRAMMERS.iso / PROGRAMS / UTILS / COMPRESS / VUNZIP.ZIP / UNZIP.C < prev   
Encoding:
C/C++ Source or Header  |  1990-02-01  |  32.0 KB  |  1,390 lines

  1. /*
  2.  * Copyright 1989 Samuel H. Smith;  All rights reserved
  3.  *
  4.  * Do not distribute modified versions without my permission.
  5.  * Do not remove or alter this notice or any other copyright notice.
  6.  * If you use this in your own program you must distribute source code.
  7.  * Do not use any of this in a commercial product.
  8.  *
  9.  */
  10.  
  11. /*
  12.  * UnZip - A simple zipfile extract utility
  13.  *
  14.  *  ported to VAX by Kw Chiu and Francis Leung
  15.  *
  16.  * To compile using Turbo C:
  17.  *      tcc -B -O -Z -G -mc unzip.c crc32.c    ;turbo C 2.0, compact model
  18.  *
  19.  * To compile in VAX:
  20.  *      cc unzip,crc32
  21.  *      link unzip,crc32
  22.  *
  23.  */
  24.  
  25. #define VERSION  "UnZip:  Zipfile Extract v2.0 (C) of 09-09-89;  (C) 1989 Samuel H. Smith"
  26.  
  27. typedef unsigned char byte;    /* code assumes UNSIGNED bytes */
  28. typedef long longint;
  29. typedef unsigned short word;  /* short in VAX */
  30. typedef char boolean;
  31.  
  32. #define STRSIZ 256
  33.  
  34. #include <stdio.h>
  35.  /* this is your standard header for all C compiles */
  36.  
  37. /* #include <stdlib.h> */
  38.  /* this include defines various standard library prototypes */
  39.  
  40.  
  41. /*
  42.  * SEE HOST OPERATING SYSTEM SPECIFICS SECTION STARTING NEAR LINE 180
  43.  *
  44.  */
  45.  
  46.  
  47. /* ----------------------------------------------------------- */
  48. /*
  49.  * Zipfile layout declarations
  50.  *
  51.  */
  52.  
  53. typedef longint signature_type;
  54.  
  55.  
  56. #define LOCAL_FILE_HEADER_SIGNATURE  0x04034b50L
  57.  
  58.  
  59. typedef struct local_file_header {
  60.     word version_needed_to_extract;
  61.     word general_purpose_bit_flag;
  62.     word compression_method;
  63.     word last_mod_file_time;
  64.     word last_mod_file_date;
  65.     longint crc32;
  66.     longint compressed_size;
  67.     longint uncompressed_size;
  68.     word filename_length;
  69.     word extra_field_length;
  70. } local_file_header;
  71.  
  72.  
  73. #define CENTRAL_FILE_HEADER_SIGNATURE  0x02014b50L
  74.  
  75.  
  76. typedef struct central_directory_file_header {
  77.     word version_made_by;
  78.     word version_needed_to_extract;
  79.     word general_purpose_bit_flag;
  80.     word compression_method;
  81.     word last_mod_file_time;
  82.     word last_mod_file_date;
  83.     longint crc32;
  84.     longint compressed_size;
  85.     longint uncompressed_size;
  86.     word filename_length;
  87.     word extra_field_length;
  88.     word file_comment_length;
  89.     word disk_number_start;
  90.     word internal_file_attributes;
  91.     longint external_file_attributes;
  92.     longint relative_offset_local_header;
  93. } central_directory_file_header;
  94.  
  95.  
  96. #define END_CENTRAL_DIR_SIGNATURE  0x06054b50L
  97.  
  98.  
  99. typedef struct end_central_dir_record {
  100.     word number_this_disk;
  101.     word number_disk_with_start_central;
  102.     word total_entries_central_dir_on_th;
  103.     word total_entries_central_dir;
  104.     longint size_central_directory;
  105.     longint offset_start_central_directory;
  106.     word zipfile_comment_length;
  107. } end_central_dir_record;
  108.  
  109.  
  110.  
  111. /* ----------------------------------------------------------- */
  112. /*
  113.  * input file variables
  114.  *
  115.  */
  116.  
  117. #define INBUFSIZ 0x2000
  118. byte *inbuf;            /* input file buffer - any size is legal */
  119. byte *inptr;
  120.  
  121. int incnt;
  122. unsigned bitbuf;
  123. int bits_left;
  124. boolean zipeof;
  125.  
  126. int zipfd;
  127. char zipfn[STRSIZ];
  128. local_file_header lrec;
  129.  
  130.  
  131. /* ----------------------------------------------------------- */
  132. /*
  133.  * output stream variables
  134.  *
  135.  */
  136.  
  137. #define OUTBUFSIZ 0x2000        /* must be 0x2000 or larger for unImplode */
  138. byte *outbuf;                   /* buffer for rle look-back */
  139. byte *outptr;
  140.  
  141. longint outpos;            /* absolute position in outfile */
  142. int outcnt;            /* current position in outbuf */
  143.  
  144. int outfd;
  145. char filename[STRSIZ];
  146. char extra[STRSIZ];
  147.  
  148. #define DLE 144
  149.  
  150.  
  151. /* ----------------------------------------------------------- */
  152. /*
  153.  * shrink/reduce working storage
  154.  *
  155.  */
  156.  
  157. int factor;
  158. byte followers[256][64];
  159. byte Slen[256];
  160.  
  161. #define max_bits 13
  162. #define init_bits 9
  163. #define hsize 8192
  164. #define first_ent 257
  165. #define clear 256
  166.  
  167. typedef int hsize_array_integer[hsize+1];
  168. typedef byte hsize_array_byte[hsize+1];
  169.  
  170. hsize_array_integer prefix_of;
  171. hsize_array_byte suffix_of;
  172. hsize_array_byte stack;
  173.  
  174. int codesize;
  175. int maxcode;
  176. int free_ent;
  177. int maxcodemax;
  178. int offset;
  179. int sizex;
  180.  
  181.  
  182.  
  183. /* ============================================================= */
  184. /*
  185.  * Host operating system details
  186.  *
  187.  */
  188.  
  189. /* #include <string.h> */
  190.  /* this include defines strcpy, strcmp, etc. */
  191.  
  192. /* ifdef...  added by K.W.Chiu */
  193.  
  194. #ifdef VAX
  195. /* #include <unixio.h> */
  196. #include <file.h>
  197. #define O_BINARY 0
  198. #include <stat.h>
  199. #else
  200.  
  201. #include <io.h>
  202.  /*
  203.   * this include file defines
  204.   *             struct ftime ...        (* file time/date stamp info *)
  205.   *             int setftime (int handle, struct ftime *ftimep);
  206.   *             #define SEEK_CUR  1     (* lseek() modes *)
  207.   *             #define SEEK_END  2
  208.   *             #define SEEK_SET  0
  209.   */
  210.  
  211. #include <fcntl.h>
  212.  /*
  213.   * this include file defines
  214.   *             #define O_BINARY 0x8000  (* no cr-lf translation *)
  215.   * as used in the open() standard function
  216.   */
  217.  
  218. #include <sys/stat.h>
  219.  /*
  220.   * this include file defines
  221.   *             #define S_IREAD 0x0100  (* owner may read *)
  222.   *             #define S_IWRITE 0x0080 (* owner may write *)
  223.   * as used in the creat() standard function
  224.   */
  225. #endif
  226.  
  227. #define SEEK_SET  0        /* wsm */
  228. /* #undef HIGH_LOW */        /* wsm */
  229.  /*
  230.   * change 'undef' to 'define' if your machine stores high order bytes in
  231.   * lower addresses.
  232.   */
  233.  
  234. void set_file_time()
  235.  /*
  236.   * set the output file date/time stamp according to information from the
  237.   * zipfile directory record for this file 
  238.   */
  239. {
  240. #ifdef VAX
  241.     /* don't know how to set file time */
  242. #else
  243.  
  244.     union {
  245.                 struct ftime ft;        /* system file time record */
  246.         struct {
  247.                         word ztime;     /* date and time words */
  248.                         word zdate;     /* .. same format as in .ZIP file */
  249.         } zt;
  250.     } td;
  251.  
  252.     /*
  253.      * set output file date and time - this is optional and can be
  254.      * deleted if your compiler does not easily support setftime() 
  255.      */
  256.  
  257.     td.zt.ztime = lrec.last_mod_file_time;
  258.     td.zt.zdate = lrec.last_mod_file_date;
  259.  
  260.     setftime(outfd, &td.ft);
  261. #endif
  262. }
  263.  
  264.  
  265. int create_output_file()
  266.  /* return non-0 if creat failed */
  267. {
  268.     /* create the output file with READ and WRITE permissions */
  269.     outfd = creat(filename, S_IWRITE | S_IREAD);
  270.     if (outfd < 1) {
  271.         printf("Can't create output: %s\n", filename);
  272.         return 1;
  273.     }
  274.  
  275.     /*
  276.      * close the newly created file and reopen it in BINARY mode to
  277.      * disable all CR/LF translations 
  278.      */
  279.     close(outfd);
  280.     outfd = open(filename, O_RDWR | O_BINARY);
  281.  
  282.     /* write a single byte at EOF to pre-allocate the file */
  283.         lseek(outfd, lrec.uncompressed_size - 1L, SEEK_SET);
  284.     write(outfd, "?", 1);
  285.     lseek(outfd, 0L, SEEK_SET);
  286.     return 0;
  287. }
  288.  
  289.  
  290. int open_input_file()
  291.  /* return non-0 if creat failed */
  292. {
  293.     /*
  294.      * open the zipfile for reading and in BINARY mode to prevent cr/lf
  295.      * translation, which would corrupt the bitstreams 
  296.      */
  297.  
  298.     zipfd = open(zipfn, O_RDONLY | O_BINARY);
  299.     if (zipfd < 1) {
  300.         printf("Can't open input file: %s\n", zipfn);
  301.         return (1);
  302.     }
  303.     return 0;
  304. }
  305.  
  306.  
  307. #ifdef HIGH_LOW
  308.  
  309. void swap_bytes(wordp)
  310. word *wordp;
  311.  /* convert intel style 'short int' variable to host format */
  312. {
  313.     char *charp = (char *) wordp;
  314.     char temp;
  315.  
  316.     temp = charp[0];
  317.     charp[0] = charp[1];
  318.     charp[1] = temp;
  319. }
  320.  
  321. void swap_lbytes(longp)
  322. longint *longp;
  323.  /* convert intel style 'long' variable to host format */
  324. {
  325.     char *charp = (char *) longp;
  326.     char temp[4];
  327.  
  328.     temp[3] = charp[0];
  329.     temp[2] = charp[1];
  330.     temp[1] = charp[2];
  331.     temp[0] = charp[3];
  332.  
  333.     charp[0] = temp[0];
  334.     charp[1] = temp[1];
  335.     charp[2] = temp[2];
  336.     charp[3] = temp[3];
  337. }
  338.  
  339. #endif
  340.  
  341.  
  342.  
  343. /* ============================================================= */
  344.  
  345. int FillBuffer()
  346.  /* fill input buffer if possible */
  347. {
  348.     int readsize;
  349.  
  350.         if (lrec.compressed_size <= 0)
  351.         return incnt = 0;
  352.  
  353.         if (lrec.compressed_size > INBUFSIZ)
  354.         readsize = INBUFSIZ;
  355.     else
  356.                 readsize = (int) lrec.compressed_size;
  357.     incnt = read(zipfd, inbuf, readsize);
  358.  
  359.         lrec.compressed_size -= incnt;
  360.     inptr = inbuf;
  361.     return incnt--;
  362. }
  363.  
  364. int ReadByte(x)
  365. unsigned *x;
  366.  /* read a byte; return 8 if byte available, 0 if not */
  367. {
  368.     if (incnt-- == 0)
  369.         if (FillBuffer() == 0)
  370.             return 0;
  371.  
  372.     *x = *inptr++;
  373.     return 8;
  374. }
  375.  
  376.  
  377. /* ------------------------------------------------------------- */
  378. static unsigned mask_bits[] =
  379.         {0,     0x0001, 0x0003, 0x0007, 0x000f,
  380.                 0x001f, 0x003f, 0x007f, 0x00ff,
  381.                 0x01ff, 0x03ff, 0x07ff, 0x0fff,
  382.                 0x1fff, 0x3fff, 0x7fff, 0xffff
  383.         };
  384.  
  385.  
  386. int FillBitBuffer(bits)
  387. register int bits;
  388. {
  389.     /* get the bits that are left and read the next word */
  390.     unsigned temp;
  391.         register int result = bitbuf;
  392.     int sbits = bits_left;
  393.     bits -= bits_left;
  394.  
  395.     /* read next word of input */
  396.     bits_left = ReadByte(&bitbuf);
  397.     bits_left += ReadByte(&temp);
  398.     bitbuf |= (temp << 8);
  399.     if (bits_left == 0)
  400.         zipeof = 1;
  401.  
  402.     /* get the remaining bits */
  403.         result = result | (int) ((bitbuf & mask_bits[bits]) << sbits);
  404.         bitbuf >>= bits;
  405.         bits_left -= bits;
  406.         return result;
  407. }
  408.  
  409. #define READBIT(nbits,zdest) { if (nbits <= bits_left) { zdest = (int)(bitbuf & mask_bits[nbits]); bitbuf >>= nbits; bits_left -= nbits; } else zdest = FillBitBuffer(nbits);}
  410.  
  411. /*
  412.  * macro READBIT(nbits,zdest)
  413.  *  {
  414.  *      if (nbits <= bits_left) {
  415.  *          zdest = (int)(bitbuf & mask_bits[nbits]);
  416.  *          bitbuf >>= nbits;
  417.  *          bits_left -= nbits;
  418.  *      } else
  419.  *          zdest = FillBitBuffer(nbits);
  420.  *  }
  421.  *
  422.  */
  423.  
  424.  
  425. /* ------------------------------------------------------------- */
  426.  
  427. #include "crc32.h"
  428.  
  429.  
  430. /* ------------------------------------------------------------- */
  431.  
  432. void FlushOutput()
  433.  /* flush contents of output buffer */
  434. {
  435.     UpdateCRC(outbuf, outcnt);
  436.     write(outfd, outbuf, outcnt);
  437.     outpos += outcnt;
  438.     outcnt = 0;
  439.     outptr = outbuf;
  440.     printf (".");       /* inform user of progress. - Francis Leung */
  441. }
  442.  
  443. #define OUTB(intc) { *outptr++=intc; if (++outcnt==OUTBUFSIZ) FlushOutput(); }
  444.  
  445. /*
  446.  *  macro OUTB(intc)
  447.  *  {
  448.  *      *outptr++=intc;
  449.  *      if (++outcnt==OUTBUFSIZ)
  450.  *          FlushOutput();
  451.  *  }
  452.  *
  453.  */
  454.  
  455.  
  456. /* ----------------------------------------------------------- */
  457.  
  458. void LoadFollowers()
  459. {
  460.         register int x;
  461.         register int i;
  462.  
  463.     for (x = 255; x >= 0; x--) {
  464.                 READBIT(6,Slen[x]);
  465.         for (i = 0; i < Slen[x]; i++) {
  466.                         READBIT(8,followers[x][i]);
  467.         }
  468.     }
  469. }
  470.  
  471.  
  472. /* ----------------------------------------------------------- */
  473. /*
  474.  * The Reducing algorithm is actually a combination of two
  475.  * distinct algorithms.  The first algorithm compresses repeated
  476.  * byte sequences, and the second algorithm takes the compressed
  477.  * stream from the first algorithm and applies a probabilistic
  478.  * compression method.
  479.  */
  480.  
  481. int L_table[] = {0, 0x7f, 0x3f, 0x1f, 0x0f};
  482.  
  483. int D_shift[] = {0, 0x07, 0x06, 0x05, 0x04};
  484. int D_mask[]  = {0, 0x01, 0x03, 0x07, 0x0f};
  485.  
  486. int B_table[] = {8, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5,
  487.          5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6,
  488.          6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  489.          6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  490.          7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  491.          7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  492.          7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  493.          7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  494.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  495.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  496.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  497.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  498.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  499.          8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  500.          8, 8, 8, 8};
  501.  
  502. /* ----------------------------------------------------------- */
  503.  
  504. void unReduce()
  505.  /* expand probablisticly reduced data */
  506. {
  507.         register int lchar;
  508.         int nchar;
  509.         int ExState;
  510.         int V;
  511.         int Len;
  512.  
  513.         factor = lrec.compression_method - 1;
  514.     ExState = 0;
  515.     lchar = 0;
  516.     LoadFollowers();
  517.  
  518.         while (((outpos+outcnt) < lrec.uncompressed_size) && (!zipeof)) {
  519.         if (Slen[lchar] == 0)
  520.                         READBIT(8,nchar)      /* ; */
  521.                 else
  522.         {
  523.                         READBIT(1,nchar);
  524.                         if (nchar != 0)
  525.                                 READBIT(8,nchar)      /* ; */
  526.                         else
  527.             {
  528.                                 int follower;
  529.                                 int bitsneeded = B_table[Slen[lchar]];
  530.                                 READBIT(bitsneeded,follower);
  531.                                 nchar = followers[lchar][follower];
  532.             }
  533.         }
  534.  
  535.         /* expand the resulting byte */
  536.         switch (ExState) {
  537.  
  538.         case 0:
  539.                         if (nchar != DLE)
  540.                                 OUTB(nchar) /*;*/
  541.             else
  542.                 ExState = 1;
  543.             break;
  544.  
  545.         case 1:
  546.                         if (nchar != 0) {
  547.                                 V = nchar;
  548.                 Len = V & L_table[factor];
  549.                 if (Len == L_table[factor])
  550.                     ExState = 2;
  551.                 else
  552.                     ExState = 3;
  553.             }
  554.             else {
  555.                                 OUTB(DLE);
  556.                 ExState = 0;
  557.             }
  558.             break;
  559.  
  560.                 case 2: {
  561.                                 Len += nchar;
  562.                 ExState = 3;
  563.             }
  564.             break;
  565.  
  566.                 case 3: {
  567.                 register int i = Len + 3;
  568.                 int offset = (((V >> D_shift[factor]) &
  569.                                           D_mask[factor]) << 8) + nchar + 1;
  570.                                 longint op = (outpos+outcnt) - offset;
  571.  
  572.                 /* special case- before start of file */
  573.                 while ((op < 0L) && (i > 0)) {
  574.                     OUTB(0);
  575.                     op++;
  576.                     i--;
  577.                 }
  578.  
  579.                 /* normal copy of data from output buffer */
  580.                 {
  581.                     register int ix = (int) (op % OUTBUFSIZ);
  582. #ifndef VAX
  583.                   /* it appeared that the VAX memcpy function is not
  584.                    * working the same way as Turbo C, therefore use
  585.                    * OUTB instead.  - Francis Leung
  586.                    */
  587.  
  588.  
  589.                                         /* do a block memory copy if possible */
  590.                                         if ( ((ix    +i) < OUTBUFSIZ) &&
  591.                                              ((outcnt+i) < OUTBUFSIZ) ) {
  592.                                                 memcpy(outptr,&outbuf[ix],i);
  593.                                                 outptr += i;
  594.                                                 outcnt += i;
  595.                                         }
  596.                                         else
  597.                                         /* otherwise copy byte by byte */
  598. #endif
  599.                                         while (i--) {
  600.                                                 OUTB(outbuf[ix]);
  601.                                                 if (++ix >= OUTBUFSIZ)
  602.                                                         ix = 0;
  603.                                         }
  604.                                 }
  605.  
  606.                 ExState = 0;
  607.             }
  608.             break;
  609.         }
  610.  
  611.                 /* store character for next iteration */
  612.                 lchar = nchar;
  613.         }
  614. }
  615.  
  616.  
  617. /* ------------------------------------------------------------- */
  618. /*
  619.  * Shrinking is a Dynamic Ziv-Lempel-Welch compression algorithm
  620.  * with partial clearing.
  621.  *
  622.  */
  623.  
  624. void partial_clear()
  625. {
  626.         register int pr;
  627.         register int cd;
  628.  
  629.     /* mark all nodes as potentially unused */
  630.     for (cd = first_ent; cd < free_ent; cd++)
  631.         prefix_of[cd] |= 0x8000;
  632.  
  633.     /* unmark those that are used by other nodes */
  634.     for (cd = first_ent; cd < free_ent; cd++) {
  635.         pr = prefix_of[cd] & 0x7fff;    /* reference to another node? */
  636.                 if (pr >= first_ent)            /* flag node as referenced */
  637.             prefix_of[pr] &= 0x7fff;
  638.     }
  639.  
  640.     /* clear the ones that are still marked */
  641.     for (cd = first_ent; cd < free_ent; cd++)
  642.         if ((prefix_of[cd] & 0x8000) != 0)
  643.             prefix_of[cd] = -1;
  644.  
  645.     /* find first cleared node as next free_ent */
  646.         cd = first_ent;
  647.         while ((cd < maxcodemax) && (prefix_of[cd] != -1))
  648.                 cd++;
  649.         free_ent = cd;
  650. }
  651.  
  652.  
  653. /* ------------------------------------------------------------- */
  654.  
  655. void unShrink()
  656. {
  657. #define  GetCode(dest) READBIT(codesize,dest)
  658.  
  659.     register int code;
  660.     register int stackp;
  661.     int finchar;
  662.     int oldcode;
  663.     int incode;
  664.  
  665.  
  666.     /* decompress the file */
  667.     maxcodemax = 1 << max_bits;
  668.     codesize = init_bits;
  669.     maxcode = (1 << codesize) - 1;
  670.     free_ent = first_ent;
  671.     offset = 0;
  672.     sizex = 0;
  673.  
  674.     for (code = maxcodemax; code > 255; code--)
  675.         prefix_of[code] = -1;
  676.  
  677.     for (code = 255; code >= 0; code--) {
  678.         prefix_of[code] = 0;
  679.         suffix_of[code] = code;
  680.     }
  681.  
  682.     GetCode(oldcode);
  683.     if (zipeof)
  684.         return;
  685.     finchar = oldcode;
  686.  
  687.         OUTB(finchar);
  688.  
  689.         stackp = hsize;
  690.  
  691.     while (!zipeof) {
  692.         GetCode(code);
  693.         if (zipeof)
  694.             return;
  695.  
  696.         while (code == clear) {
  697.             GetCode(code);
  698.             switch (code) {
  699.  
  700.             case 1:{
  701.                     codesize++;
  702.                     if (codesize == max_bits)
  703.                         maxcode = maxcodemax;
  704.                     else
  705.                         maxcode = (1 << codesize) - 1;
  706.                 }
  707.                 break;
  708.  
  709.             case 2:
  710.                 partial_clear();
  711.                 break;
  712.             }
  713.  
  714.             GetCode(code);
  715.             if (zipeof)
  716.                 return;
  717.         }
  718.  
  719.  
  720.         /* special case for KwKwK string */
  721.         incode = code;
  722.         if (prefix_of[code] == -1) {
  723.                         stack[--stackp] = finchar;
  724.             code = oldcode;
  725.         }
  726.  
  727.  
  728.         /* generate output characters in reverse order */
  729.         while (code >= first_ent) {
  730.                         stack[--stackp] = suffix_of[code];
  731.             code = prefix_of[code];
  732.         }
  733.  
  734.         finchar = suffix_of[code];
  735.                 stack[--stackp] = finchar;
  736.  
  737. #ifndef VAX     /* added by Francis Leung */
  738.  
  739.                 /* and put them out in forward order, block copy */
  740.                 if ((hsize-stackp+outcnt) < OUTBUFSIZ) {
  741.                         memcpy(outptr,&stack[stackp],hsize-stackp);
  742.                         outptr += hsize-stackp;
  743.                         outcnt += hsize-stackp;
  744.                         stackp = hsize;
  745.                 }
  746.                 else
  747.                 /* output byte by byte if we can't go by blocks */
  748. #endif
  749.                 while (stackp < hsize)
  750.                         OUTB(stack[stackp++]);
  751.  
  752.  
  753.         /* generate new entry */
  754.         code = free_ent;
  755.         if (code < maxcodemax) {
  756.             prefix_of[code] = oldcode;
  757.             suffix_of[code] = finchar;
  758.  
  759.             do
  760.                 code++;
  761.             while ((code < maxcodemax) && (prefix_of[code] != -1));
  762.  
  763.             free_ent = code;
  764.         }
  765.  
  766.         /* remember previous code */
  767.         oldcode = incode;
  768.     }
  769.  
  770. }
  771.  
  772.  
  773. /* ------------------------------------------------------------- */ 
  774. /*
  775.  * Imploding
  776.  * ---------
  777.  *
  778.  * The Imploding algorithm is actually a combination of two distinct
  779.  * algorithms.  The first algorithm compresses repeated byte sequences
  780.  * using a sliding dictionary.  The second algorithm is used to compress
  781.  * the encoding of the sliding dictionary ouput, using multiple
  782.  * Shannon-Fano trees.
  783.  *
  784.  */ 
  785.  
  786.    enum { maxSF        = 256 };
  787.  
  788.    typedef struct sf_entry { 
  789.                  word         Code; 
  790.                  byte         Value; 
  791.                  byte         BitLength; 
  792.               } sf_entry; 
  793.  
  794.    typedef struct sf_tree {   /* a shannon-fano tree */ 
  795.       sf_entry     entri[maxSF];
  796.       int          entries;
  797.       int          MaxLength;
  798.    } sf_tree; 
  799.  
  800.    typedef sf_tree      *sf_treep; 
  801.  
  802.    sf_tree      lit_tree; 
  803.    sf_tree      length_tree; 
  804.    sf_tree      distance_tree; 
  805.    boolean      lit_tree_present; 
  806.    boolean      eightK_dictionary; 
  807.    int          minimum_match_length;
  808.    int          dict_bits;
  809.  
  810.  
  811. void SortLengths(tree)
  812. sf_tree *tree;
  813.   /* Sort the Bit Lengths in ascending order, while retaining the order
  814.     of the original lengths stored in the file */ 
  815.    int          x;
  816.    int          gap;
  817.    sf_entry     t; 
  818.    boolean      noswaps;
  819.    int          a, b;
  820.  
  821.    gap = tree->entries / 2; 
  822.  
  823.    do { 
  824.       do { 
  825.          noswaps = 1;
  826.          for (x = 0; x <= (tree->entries - 1) - gap; x++) 
  827.          { 
  828.             a = tree->entri[x].BitLength; 
  829.             b = tree->entri[x + gap].BitLength; 
  830.             if ((a > b) || ((a == b) && (tree->entri[x].Value > tree->entri[x + gap].Value))) 
  831.             { 
  832.                t = tree->entri[x]; 
  833.                tree->entri[x] = tree->entri[x + gap]; 
  834.                tree->entri[x + gap] = t; 
  835.                noswaps = 0;
  836.             } 
  837.          } 
  838.       }  while (!noswaps);
  839.  
  840.       gap = gap / 2; 
  841.    }  while (gap > 0);
  842.  
  843.  
  844. /* ----------------------------------------------------------- */ 
  845.  
  846. void ReadLengths(tree)
  847. sf_tree *tree;
  848.    int          treeBytes;
  849.    int          i;
  850.    int          num, len;
  851.  
  852.   /* get number of bytes in compressed tree */
  853.    READBIT(8,treeBytes);
  854.    treeBytes++; 
  855.    i = 0; 
  856.  
  857.    tree->MaxLength = 0;
  858.  
  859.  /* High 4 bits: Number of values at this bit length + 1. (1 - 16)
  860.     Low  4 bits: Bit Length needed to represent value + 1. (1 - 16) */
  861.    while (treeBytes > 0)
  862.    {
  863.       READBIT(4,len); len++;
  864.       READBIT(4,num); num++;
  865.  
  866.       while (num > 0)
  867.       {
  868.          if (len > tree->MaxLength)
  869.             tree->MaxLength = len;
  870.          tree->entri[i].BitLength = len;
  871.          tree->entri[i].Value = i;
  872.          i++;
  873.          num--;
  874.       }
  875.  
  876.       treeBytes--;
  877.    } 
  878.  
  879.  
  880. /* ----------------------------------------------------------- */ 
  881.  
  882. void GenerateTrees(tree)
  883. sf_tree *tree;
  884.      /* Generate the Shannon-Fano trees */ 
  885.    word         Code;
  886.    int          CodeIncrement;
  887.    int          LastBitLength;
  888.    int          i;
  889.  
  890.  
  891.    Code = 0;
  892.    CodeIncrement = 0; 
  893.    LastBitLength = 0; 
  894.  
  895.    i = tree->entries - 1;   /* either 255 or 63 */ 
  896.    while (i >= 0) 
  897.    { 
  898.       Code += CodeIncrement; 
  899.       if (tree->entri[i].BitLength != LastBitLength) 
  900.       { 
  901.          LastBitLength = tree->entri[i].BitLength; 
  902.          CodeIncrement = 1 << (16 - LastBitLength); 
  903.       } 
  904.  
  905.       tree->entri[i].Code = Code; 
  906.       i--; 
  907.    } 
  908.  
  909.  
  910. /* ----------------------------------------------------------- */ 
  911.  
  912. void ReverseBits(tree)
  913. sf_tree *tree;
  914.  /* Reverse the order of all the bits in the above ShannonCode[]
  915.     vector, so that the most significant bit becomes the least
  916.     significant bit. For example, the value 0x1234 (hex) would become
  917.     0x2C48 (hex). */ 
  918.    int          i;
  919.    word         mask;
  920.    word         revb;
  921.    word         v;
  922.    word         o;
  923.    int          b;
  924.  
  925.  
  926.    for (i = 0; i <= tree->entries - 1; i++) 
  927.    { 
  928.         /* get original code */ 
  929.       o = tree->entri[i].Code; 
  930.  
  931.         /* reverse each bit */ 
  932.       mask = 0x0001;
  933.       revb = 0x8000;
  934.       v = 0;
  935.       for (b = 0; b <= 15; b++) 
  936.       { 
  937.            /* if bit set in mask, then substitute reversed bit */ 
  938.          if ((o & mask) != 0) 
  939.             v = v | revb; 
  940.  
  941.            /* advance to next bit */ 
  942.          revb = (revb >> 1);
  943.          mask = (mask << 1);
  944.       } 
  945.  
  946.         /* store reversed bits */ 
  947.       tree->entri[i].Code = v; 
  948.    } 
  949.  
  950.  
  951. /* ----------------------------------------------------------- */ 
  952.  
  953. void LoadTree(tree, treesize)
  954. sf_tree *tree;
  955. int treesize;
  956.      /* allocate and load a shannon-fano tree from the compressed file */ 
  957.    tree->entries = treesize; 
  958.    ReadLengths(tree); 
  959.    SortLengths(tree); 
  960.    GenerateTrees(tree); 
  961.    ReverseBits(tree); 
  962.  
  963.  
  964. /* ----------------------------------------------------------- */ 
  965.  
  966. void LoadTrees()
  967.    eightK_dictionary = (lrec.general_purpose_bit_flag & 0x02) != 0;   /* bit 1 */
  968.    lit_tree_present = (lrec.general_purpose_bit_flag & 0x04) != 0;   /* bit 2 */
  969.  
  970.    if (eightK_dictionary) 
  971.       dict_bits = 7;
  972.    else 
  973.       dict_bits = 6; 
  974.  
  975.    if (lit_tree_present) 
  976.    { 
  977.       minimum_match_length = 3; 
  978.       LoadTree(&lit_tree,256); 
  979.    } 
  980.    else 
  981.       minimum_match_length = 2; 
  982.  
  983.    LoadTree(&length_tree,64); 
  984.    LoadTree(&distance_tree,64); 
  985.  
  986.  
  987. /* ----------------------------------------------------------- */ 
  988.  
  989. void ReadTree(tree, dest)
  990. sf_tree *tree;
  991. int *dest;
  992.      /* read next byte using a shannon-fano tree */ 
  993.    int          bits = 0;
  994.    word         cv = 0;
  995.    int          cur = 0;
  996.    int          b;
  997.  
  998.    *dest = -1;   /* in case of error */ 
  999.  
  1000.    for (;;)
  1001.    { 
  1002.       READBIT(1,b);
  1003.       cv = cv | (b << bits);
  1004.       bits++; 
  1005.  
  1006.       /* this is a very poor way of decoding shannon-fano.  two quicker
  1007.          methods come to mind:
  1008.             a) arrange the tree as a huffman-style binary tree with
  1009.                a "leaf" indicator at each node,
  1010.          and
  1011.             b) take advantage of the fact that s-f codes are at most 8
  1012.                bits long and alias unused codes for all bits following
  1013.                the "leaf" bit.
  1014.       */
  1015.  
  1016.       while (tree->entri[cur].BitLength < bits) 
  1017.       { 
  1018.          cur++; 
  1019.          if (cur >= tree->entries) 
  1020.             return; /* data error */
  1021.       } 
  1022.  
  1023.       while (tree->entri[cur].BitLength == bits) 
  1024.       { 
  1025.          if (tree->entri[cur].Code == cv) 
  1026.          { 
  1027.             *dest = tree->entri[cur].Value; 
  1028.             return; 
  1029.          } 
  1030.  
  1031.          cur++; 
  1032.          if (cur >= tree->entries) 
  1033.             return; /* data error */
  1034.       } 
  1035.    } 
  1036.  
  1037.  
  1038. /* ----------------------------------------------------------- */ 
  1039.  
  1040. void  unImplode()
  1041.      /* expand imploded data */ 
  1042.  
  1043.    int          lout;
  1044.    longint      op;
  1045.    int          Length;
  1046.    int          Distance;
  1047.    int          i;
  1048.  
  1049.    LoadTrees(); 
  1050.  
  1051.    while ((!zipeof) && ((outpos+outcnt) < lrec.uncompressed_size))
  1052.    { 
  1053.       READBIT(1,lout);
  1054.  
  1055.       if (lout != 0)   /* encoded data is literal data */ 
  1056.       { 
  1057.          if (lit_tree_present)  /* use Literal Shannon-Fano tree */
  1058.             ReadTree(&lit_tree,&lout);
  1059.          else 
  1060.             READBIT(8,lout);
  1061.  
  1062.          OUTB(lout);
  1063.       } 
  1064.       else             /* encoded data is sliding dictionary match */
  1065.       {                
  1066.          READBIT(dict_bits,lout);
  1067.          Distance = lout; 
  1068.  
  1069.          ReadTree(&distance_tree,&lout); 
  1070.          Distance |= (lout << dict_bits);
  1071.          /* using the Distance Shannon-Fano tree, read and decode the
  1072.             upper 6 bits of the Distance value */ 
  1073.  
  1074.          ReadTree(&length_tree,&Length); 
  1075.          /* using the Length Shannon-Fano tree, read and decode the
  1076.             Length value */
  1077.  
  1078.          Length += minimum_match_length; 
  1079.          if (Length == (63 + minimum_match_length)) 
  1080.          { 
  1081.             READBIT(8,lout);
  1082.             Length += lout; 
  1083.          } 
  1084.  
  1085.         /* move backwards Distance+1 bytes in the output stream, and copy
  1086.           Length characters from this position to the output stream.
  1087.           (if this position is before the start of the output stream,
  1088.           then assume that all the data before the start of the output
  1089.           stream is filled with zeros) */ 
  1090.  
  1091.          op = (outpos+outcnt) - Distance - 1L;
  1092.  
  1093.           /* special case- before start of file */
  1094.           while ((op < 0L) && (Length > 0)) {
  1095.                   OUTB(0);
  1096.                   op++;
  1097.                   Length--;
  1098.           }
  1099.  
  1100.           /* normal copy of data from output buffer */
  1101.           {
  1102.                   register int ix = (int) (op % OUTBUFSIZ);
  1103.  
  1104. #ifndef VAX       /* added by Francis Leung */
  1105.  
  1106.                   /* do a block memory copy if possible */
  1107.                   if ( ((ix    +Length) < OUTBUFSIZ) &&
  1108.                        ((outcnt+Length) < OUTBUFSIZ) ) {
  1109.                           memcpy(outptr,&outbuf[ix],Length);
  1110.                           outptr += Length;
  1111.                           outcnt += Length;
  1112.                   }
  1113.                   else
  1114.                   /* otherwise copy byte by byte */
  1115. #endif
  1116.                   while (Length--) {
  1117.                           OUTB(outbuf[ix]);
  1118.                           if (++ix >= OUTBUFSIZ)
  1119.                                   ix = 0;
  1120.                   }
  1121.          }
  1122.       } 
  1123.    } 
  1124.  
  1125.  
  1126.  
  1127. /* ---------------------------------------------------------- */
  1128.  
  1129. void extract_member()
  1130. {
  1131.         word     b;
  1132.  
  1133.     bits_left = 0;
  1134.     bitbuf = 0;
  1135.     incnt = 0;
  1136.     outpos = 0L;
  1137.     outcnt = 0;
  1138.     outptr = outbuf;
  1139.     zipeof = 0;
  1140.     crc32val = 0xFFFFFFFFL;
  1141.  
  1142.  
  1143.     /* create the output file with READ and WRITE permissions */
  1144.     if (create_output_file())
  1145.         exit(1);
  1146.  
  1147.         switch (lrec.compression_method) {
  1148.  
  1149.     case 0:        /* stored */
  1150.         {
  1151.             printf(" Extracting: %-12s ", filename);
  1152.             while (ReadByte(&b))
  1153.                 OUTB(b);
  1154.         }
  1155.         break;
  1156.  
  1157.         case 1: {
  1158.             printf("UnShrinking: %-12s ", filename);
  1159.             unShrink();
  1160.         }
  1161.         break;
  1162.  
  1163.     case 2:
  1164.     case 3:
  1165.     case 4:
  1166.         case 5: {
  1167.             printf("  Expanding: %-12s ", filename);
  1168.             unReduce();
  1169.         }
  1170.         break;
  1171.  
  1172.         case 6: {
  1173.                         printf("  Exploding: %-12s ", filename);
  1174.                         unImplode();
  1175.         }
  1176.         break;
  1177.  
  1178.         default:
  1179.         printf("Unknown compression method.");
  1180.     }
  1181.  
  1182.  
  1183.     /* write the last partial buffer, if any */
  1184.     if (outcnt > 0) {
  1185.         UpdateCRC(outbuf, outcnt);
  1186.         write(outfd, outbuf, outcnt);
  1187.     }
  1188.  
  1189.     /* set output file date and time */
  1190.     set_file_time();
  1191.  
  1192.     close(outfd);
  1193.  
  1194.     crc32val = -1 - crc32val;
  1195.         if (crc32val != lrec.crc32)
  1196.                 printf(" Bad CRC %08lx  (should be %08lx)", lrec.crc32, crc32val);
  1197.  
  1198.     printf("\n");
  1199. }
  1200.  
  1201.  
  1202. /* ---------------------------------------------------------- */
  1203.  
  1204. void get_string(len, s)
  1205. int len;
  1206. char *s;
  1207. {
  1208.     read(zipfd, s, len);
  1209.     s[len] = 0;
  1210. }
  1211.  
  1212.  
  1213. /* ---------------------------------------------------------- */
  1214.  
  1215. void process_local_file_header()
  1216. {
  1217.     read(zipfd, &lrec, sizeof(lrec));
  1218.  
  1219. #ifdef HIGH_LOW
  1220.     swap_bytes(&lrec.filename_length);
  1221.     swap_bytes(&lrec.extra_field_length);
  1222.     swap_lbytes(&lrec.compressed_size);
  1223.     swap_lbytes(&lrec.uncompressed_size);
  1224.     swap_bytes(&lrec.compression_method);
  1225. #endif
  1226.  
  1227.     get_string(lrec.filename_length, filename);
  1228.     get_string(lrec.extra_field_length, extra);
  1229.     extract_member();
  1230. }
  1231.  
  1232.  
  1233. /* ---------------------------------------------------------- */
  1234.  
  1235. void process_central_file_header()
  1236. {
  1237.     central_directory_file_header rec;
  1238.     char filename[STRSIZ];
  1239.     char extra[STRSIZ];
  1240.     char comment[STRSIZ];
  1241.  
  1242.     read(zipfd, &rec, sizeof(rec));
  1243.  
  1244. #ifdef HIGH_LOW
  1245.     swap_bytes(&rec.filename_length);
  1246.     swap_bytes(&rec.extra_field_length);
  1247.     swap_bytes(&rec.file_comment_length);
  1248. #endif
  1249.  
  1250.         get_string(rec.filename_length, filename);
  1251.     get_string(rec.extra_field_length, extra);
  1252.     get_string(rec.file_comment_length, comment);
  1253. }
  1254.  
  1255.  
  1256. /* ---------------------------------------------------------- */
  1257.  
  1258. void process_end_central_dir()
  1259. {
  1260.     end_central_dir_record rec;
  1261.     char comment[STRSIZ];
  1262.  
  1263.     read(zipfd, &rec, sizeof(rec));
  1264.  
  1265. #ifdef HIGH_LOW
  1266.     swap_bytes(&rec.zipfile_comment_length);
  1267. #endif
  1268.  
  1269.     get_string(rec.zipfile_comment_length, comment);
  1270. }
  1271.  
  1272.  
  1273. /* ---------------------------------------------------------- */
  1274.  
  1275. void process_headers()
  1276. {
  1277.     longint sig;
  1278.  
  1279.     while (1) {
  1280.         if (read(zipfd, &sig, sizeof(sig)) != sizeof(sig))
  1281.             return;
  1282.  
  1283. #ifdef HIGH_LOW
  1284.         swap_lbytes(&sig);
  1285. #endif
  1286.  
  1287.                 if (sig == LOCAL_FILE_HEADER_SIGNATURE)
  1288.             process_local_file_header();
  1289.                 else if (sig == CENTRAL_FILE_HEADER_SIGNATURE)
  1290.             process_central_file_header();
  1291.                 else if (sig == END_CENTRAL_DIR_SIGNATURE) {
  1292.             process_end_central_dir();
  1293.             return;
  1294.         }
  1295.                 else {
  1296.             printf("Invalid Zipfile Header\n");
  1297.             return;
  1298.         }
  1299.     }
  1300.  
  1301. }
  1302.  
  1303.  
  1304. /* ---------------------------------------------------------- */
  1305.  
  1306. void extract_zipfile()
  1307. {
  1308.     /*
  1309.      * open the zipfile for reading and in BINARY mode to prevent cr/lf
  1310.      * translation, which would corrupt the bitstreams 
  1311.      */
  1312.  
  1313.     if (open_input_file())
  1314.         exit(1);
  1315.  
  1316.     process_headers();
  1317.  
  1318.     close(zipfd);
  1319. }
  1320.  
  1321.  
  1322. /* ---------------------------------------------------------- */
  1323. /*
  1324.  * main program
  1325.  *
  1326.  */
  1327.  
  1328. void main(argc, argv)
  1329. int argc;
  1330. char **argv;
  1331. {
  1332.     if (argc != 2) {
  1333.                 printf("\n%s\nCourtesy of:  S.H.Smith  and  The Tool Shop BBS,  (602) 279-2673.\n\n",VERSION);
  1334.  
  1335. #ifdef VAX
  1336.    printf("Modified by K.W.Chiu and Francis Leung to work on VAX.\n");
  1337.    printf("   Kw Chiu, Sysop of Chiu's Board (IFNA 700/138), Hong Kong.\n");
  1338.    printf("   ..!uunet!hkucs!hkucc!hcxcckw\n");
  1339.    printf("File date and time not restored. Please teach me how to do so.\n");
  1340. #endif
  1341.         printf("You may copy and distribute this program freely, provided that:\n");
  1342.         printf("    1)   No fee is charged for such copying and distribution, and\n");
  1343.         printf("    2)   It is distributed ONLY in its original, unmodified state.\n\n");
  1344.         printf("If you wish to distribute a modified version of this program, you MUST\n");
  1345.         printf("include the source code.\n\n");
  1346.         printf("If you modify this program, I would appreciate a copy of the  new source\n");
  1347.         printf("code.   I am holding the copyright on the source code, so please don't\n");
  1348.         printf("delete my name from the program files or from the documentation.\n\n");
  1349.                 printf("IN NO EVENT WILL I BE LIABLE TO YOU FOR ANY DAMAGES, INCLUDING ANY LOST\n");
  1350.                 printf("PROFITS, LOST SAVINGS OR OTHER INCIDENTAL OR CONSEQUENTIAL DAMAGES\n");
  1351.                 printf("ARISING OUT OF YOUR USE OR INABILITY TO USE THE PROGRAM, OR FOR ANY\n");
  1352.                 printf("CLAIM BY ANY OTHER PARTY.\n\n");
  1353.                 printf("Usage:  UnZip FILE[.zip]\n");
  1354.                 exit(1);
  1355.     }
  1356.  
  1357.     /* .ZIP default if none provided by user */
  1358.     strcpy(zipfn, argv[1]);
  1359.     if (strchr(zipfn, '.') == NULL)
  1360.         strcat(zipfn, ".ZIP");
  1361.  
  1362.         /* allocate i/o buffers */
  1363.     inbuf = (byte *) (malloc(INBUFSIZ));
  1364.     outbuf = (byte *) (malloc(OUTBUFSIZ));
  1365.     if ((inbuf == NULL) || (outbuf == NULL)) {
  1366.         printf("Can't allocate buffers!\n");
  1367.         exit(1);
  1368.     }
  1369.  
  1370.         /* do the job... */
  1371.         extract_zipfile();
  1372.     exit();
  1373. }
  1374.