home *** CD-ROM | disk | FTP | other *** search
/ ftp.barnyard.co.uk / 2015.02.ftp.barnyard.co.uk.tar / ftp.barnyard.co.uk / cpm / walnut-creek-CDROM / CPM / LANGUAGS / PASCAL / SQ.PAS < prev    next >
Pascal/Delphi Source File  |  2000-06-30  |  24KB  |  630 lines

  1. {$C-}
  2. {$R-}
  3. program Squeezer;
  4.  
  5.   const version   = '1.8  last update 08-02-84';
  6.  
  7. { CP/M compatible file squeezer utility.
  8.  
  9.   This translation uses the Huffman algorithm to develop a binary tree representing the decoding information
  10.   for a variable length bit string code for each input value.  Each string's length is in inverse proportion
  11.   to its frequency of appearance in the incoming data stream.  The encoding table is derived from the decoding
  12.   table.
  13.  
  14.   The range of valid values into the Huffman algorithm are the values of a byte stored in an integer plus the
  15.   special endfile value chosen to be an adjacent value. Overall, 0-SPEOF.
  16.  
  17.   The algorithm develops the single element trees into a single binary tree by forming subtrees rooted in
  18.   interior nodes having weights equal to the sum of weights of all their descendents and having depth counts
  19.   indicating the depth of their longest paths.
  20.  
  21.   When all trees have been formed into a single tree satisfying the heap property (on weight, with depth as a
  22.   tie breaker) then the binary code assigned to a leaf (value to be encoded) is then the series of left (0) and
  23.   right (1) paths leading from the root to the leaf.  Note that trees are removed from the heaped list by moving
  24.   the last element over the top element and reheaping the shorter list.
  25.  
  26.   To further compress the output code stream, all bytes pass directly through except for:
  27.         1) DLE is encoded as (DLE, zero).
  28.         2) repeated byte values (count >= 3) are encoded as (value, DLE, count).
  29.  
  30.   In the original design it was believed that a Huffman code would fit in the same number of bits that will hold
  31.   the sum of all the counts.  That was disproven by a user's file and was a rare but infamous bug. This version
  32.   attempts to choose among equally weighted subtrees according to their maximum depths to avoid unnecessarily long
  33.   codes. In case that is not sufficient to guarantee codes <= 16 bits long, we initially scale the counts so the
  34.   total fits in an unsigned integer, but if codes longer than 16 bits are generated the counts are rescaled to a
  35.   lower ceiling and code generation is retried.
  36.  
  37.   The "node" array of structures contains the nodes of the binary tree. The first NUMVALS nodes are the leaves
  38.   of the tree and represent the values of the data bytes being encoded and the special endfile, SPEOF.  The
  39.   remaining nodes become the internal nodes of the tree.
  40.  
  41.   Program states:
  42.      NoHist    don't consider previous input
  43.      SentChar  lastchar set, no lookahead yet
  44.      SendNewC  newchar set, previous sequence done
  45.      SendCnt   newchar set, DLE sent, send count next
  46. }
  47. {.pa}
  48.   const space     = ' ';
  49.         Error     = -1;
  50.         Null      = -2;
  51.         Recognize = $FF76;  { unlikely pattern }
  52.         DLE       = #$90;
  53.         SPEOF     = 256;    { special endfile token }
  54.         NumVals   = 257;    { 256 data values plus SPEOF }
  55.         NumNodes  = 513;    { = 2 * NUMVALS - 1 = number of nodes }
  56.         NoChild   = -1;     { indicates end of path through tree }
  57.         maxcount  = MAXINT; { biggest UNSIGNED integer }
  58.  
  59.    type FileName = string[30];
  60.         ValType  = array[0..numvals] of integer;
  61.         StateTypes = (NoHist,SentChar,SendNewC,SendCnt,EndFile);
  62.         NodeType = record
  63.                      weight: real;             { number of appearances }
  64.                      tdepth: integer;          { length on longest path in tree }
  65.                      lchild, rchild: integer;  { indices to next level }
  66.                    end;
  67.  
  68.     var InFileName, OutFileName: FileName;
  69.         InFile, OutFile: file of char;
  70.         start, finish, i: integer;
  71.         crc: integer;      { Cyclic Redundancy Check code }
  72.  
  73.         likect: integer;   { count of consecutive identical chars }
  74.         lastchar, newchar: char;
  75.  
  76.         State: StateTypes;
  77.         EOFlag, done: boolean;
  78.  
  79.         node: array[0..NUMNODES] of NodeType;
  80.         dctreehd: integer;        { index to head node of final tree }
  81.  
  82. { This is the encoding table:  The bit strings have first bit in = low bit.
  83.   Note that counts were scaled so code fits UNSIGNED integer }
  84.  
  85.         codelen, code: array[0..numvals] of integer; { number of bits in code & code itself, right adjusted }
  86.         tcode: integer;     { temporary code value }
  87.  
  88.         curin: integer;     { Value currently being encoded }
  89.         cbitsrem: integer;  { Number of code string bits remaining }
  90.         ccode: integer;     { Current code shifted so next code bit is at right }
  91. {.pa}
  92. {.cp12}
  93.   procedure zero_tree;
  94.     { Initialize all nodes to single element binary trees with zero weight and depth. }
  95.     var i: integer;
  96.     begin
  97.       for i := 0 to NUMNODES
  98.         do begin
  99.              node[i].weight := 0;
  100.              node[i].tdepth := 0;
  101.              node[i].lchild := NoChild;
  102.              node[i].rchild := NoChild;
  103.            end;
  104.     end;
  105. {.cp8}
  106.   procedure putwe(w: integer);
  107.     { write out low order byte of word to file, then high order byte regardless of host CPU. }
  108.     var b1, b2: char;
  109.     begin
  110.       b1 := chr(w and $FF);
  111.       b2 := chr(w shr 8);
  112.       write(OutFile,b1,b2);
  113.     end;
  114. {.cp8}
  115.   function GetC_CRC: char;
  116.     { Get next byte from file and update checksum }
  117.     var c: char;
  118.     begin
  119.       if not(eof(InFile))
  120.         then begin
  121.                read(InFile,c);
  122.                crc := crc + ord(c); { update checksum }
  123.              end
  124.         else EOFlag := true;
  125.       GetC_CRC := c;  {undefined if EOFlag is true}
  126.     end;
  127. {.cp11}(*
  128.   procedure PrintBits(len, number: integer);
  129.     var i, j: integer;
  130.     begin
  131.       write('  code ');
  132.       for i:=len-1 downto 0
  133.         do begin
  134.              j := (number shr i) and $0001;
  135.              write(j:1);
  136.            end;
  137.       writeln;
  138.     end; *)
  139. {.pa}
  140.   function getcnr: char;
  141.     var return: char;
  142.  
  143.     function alike: boolean;
  144.       begin
  145.         newchar := getc_crc;
  146.         if EOFlag
  147.           then alike := false
  148.           else begin
  149.                  if (newchar = lastchar) and (likect < 255)
  150.                    then alike := true
  151.                    else alike := false;
  152.                end;
  153.       end;
  154.  
  155.     procedure NoHistory; {set up the state machine}
  156.       begin
  157.         state := SentChar;
  158.         lastchar := GetC_CRC;
  159.         if EOFlag then state := EndFile;
  160.         return := lastchar;
  161.       end;
  162.  
  163.     procedure SentAChar;   {Lastchar is set, need lookahead}
  164.  
  165.       procedure SentDLE;
  166.         begin
  167.           state := NoHist;
  168.           return := chr(0);
  169.         end;
  170.  
  171.       procedure CheckAlike;
  172.         begin
  173.           likect := 1;   while alike do likect := likect + 1;
  174.           case likect of
  175.             1: begin
  176.                  lastchar := newchar;
  177.                  return := lastchar;
  178.                end;
  179.             2: begin { just pass through }
  180.                  state := SendNewC;
  181.                  return := lastchar;
  182.                end;
  183.           else
  184.             state := SendCnt;
  185.             return := DLE;
  186.           end;
  187.         end;
  188.  
  189.       begin
  190.         if EOFlag
  191.           then state := EndFile {no return value, set to SPEOF in calling routine}
  192.           else begin
  193.                  if lastchar = DLE
  194.                    then SentDLE
  195.                    else CheckAlike;
  196.                end;
  197.       end;
  198.  
  199.     procedure SendNewChar;   {Previous sequence complete, newchar set}
  200.       begin
  201.         state := SentChar;
  202.         lastchar := newchar;
  203.         return := lastchar;
  204.       end;
  205.  
  206.     procedure SendCount;  {Sent DLE for repeat sequence, send count}
  207.       begin
  208.         state := SendNewC;
  209.         return := chr(likect);
  210.       end;
  211.  
  212.     begin
  213.       case state of
  214.         NoHist:   NoHistory;
  215.         SentChar: SentAChar;
  216.         SendNewC: SendNewChar;
  217.         SendCnt:  SendCount;
  218.       else writeln('program bug - bad state');
  219.       end;
  220.       getcnr := return;
  221.     end;
  222. {.pa}
  223.   procedure Write_Header;
  224.   { Write out the header of the compressed file }
  225.  
  226.     var i, k, l, r, numnodes: integer;
  227.         { numnodes: nbr of nodes in simplified tree }
  228.  
  229.     begin
  230.       putwe(RECOGNIZE);   { identifies as compressed }
  231.       putwe(crc);         { unsigned sum of original data }
  232.  
  233.       { Record the original file name w/o drive }
  234.       if (InFileName[2] = ':')
  235.         then InFileName := copy(InFileName,3,length(InFileName)-2);
  236.  
  237.       InFileName := InFileName + chr(0);  {mark end of file name}
  238.       for i:=1 to length(InFileName) do write(OutFile,InFileName[i]);
  239.  
  240.       { Write out a simplified decoding tree. Only the interior nodes are written. When a child is a leaf index
  241.         (representing a data value) it is recoded as -(index + 1) to distinguish it from interior indexes which
  242.         are recoded as positive indexes in the new tree.  Note that this tree will be empty for an empty file. }
  243.  
  244.       if dctreehd < NUMVALS
  245.         then numnodes := 0
  246.         else numnodes := dctreehd - (NUMVALS - 1);
  247.       putwe(numnodes);
  248.  
  249.       i := dctreehd;
  250.       for k:=0 to numnodes-1
  251.         do begin
  252.              l := node[i].lchild;
  253.              r := node[i].rchild;
  254.              if l < NUMVALS
  255.                then l := -(l + 1)
  256.                else l := dctreehd - l;
  257.              if r < NUMVALS
  258.                then r := -(r + 1)
  259.                else r := dctreehd - r;
  260.              putwe(l);  { left child }
  261.              putwe(r);  { right child }
  262.              i := i - 1;
  263.            end;
  264.     end;
  265. {.pa}
  266.   procedure Adjust(top, bottom: integer; var list: ValType);
  267.   { Make a heap from a heap with a new top }
  268.  
  269.     var k, temp: integer;
  270.  
  271.     function cmptrees(a, b: integer): boolean; {entry with root nodes}
  272.     { Compare two trees, if a > b return true, else return false. }
  273.       begin
  274.         cmptrees := false;
  275.         if node[a].weight > node[b].weight
  276.           then cmptrees := true
  277.           else if node[a].weight = node[b].weight
  278.                  then if node[a].tdepth > node[b].tdepth
  279.                         then cmptrees := true;
  280.       end;
  281.  
  282.     begin
  283.       k := 2 * top + 1;    { left child of top }
  284.       temp := list[top];   { remember root node of top tree }
  285.       if (k <= bottom)
  286.         then begin
  287.                if (k < bottom) and (cmptrees(list[k], list[k + 1])) then k := k + 1;
  288.                { k indexes "smaller" child (in heap of trees) of top
  289.                  now make top index "smaller" of old top and smallest child }
  290.                if cmptrees(temp,list[k])
  291.                  then begin
  292.                         list[top] := list[k];
  293.                         list[k] := temp;
  294.                         adjust(k, bottom, list);
  295.                       end;
  296.              end;
  297.     end;
  298.  
  299. {.pa}
  300. { The count of number of occurrances of each input value have already been prevented from exceeding MAXCOUNT.
  301.   Now we must scale them so that their sum doesn't exceed ceiling and yet no non-zero count can become zero.
  302.   This scaling prevents errors in the weights of the interior nodes of the Huffman tree and also ensures that
  303.   the codes will fit in an unsigned integer.  Rescaling is used if necessary to limit the code length. }
  304.  
  305.   procedure Scale(ceil: integer);  { upper limit on total weight }
  306.  
  307.     var i, c, ovflw, divisor: integer;
  308.         w, sum: real;
  309.         increased: boolean;
  310.  
  311.     begin
  312.       repeat
  313.           sum := 0;   ovflw := 0;
  314.           for i:=0 to numvals-1
  315.             do begin
  316.                  if node[i].weight > (ceil - sum) then ovflw := ovflw + 1;
  317.                  sum := sum + node[i].weight;
  318.                end;
  319.  
  320.           divisor := ovflw + 1;
  321.  
  322.           { Ensure no non-zero values are lost }
  323.           increased := FALSE;
  324.           for i:=0 to numvals-1
  325.             do begin
  326.                  w := node[i].weight;
  327.                  if (w < divisor) and (w <> 0)
  328.                    then begin
  329.                           { Don't fail to provide a code if it's used at all }
  330.                           node[i].weight := divisor;
  331.                           increased := TRUE;
  332.                         end;
  333.                end;
  334.         until not(increased);
  335.  
  336.       { Scaling factor choosen, now scale }
  337.       if divisor > 1
  338.         then for i:=0 to numvals-1
  339.                do with node[i] do weight := int((weight / divisor) + 0.5);
  340.     end;
  341. {.pa}
  342.   function buildenc(level, root: integer): integer; {returns error or null}
  343.  
  344.   { Recursive routine to walk the indicated subtree and level
  345.     and maintain the current path code in bstree. When a leaf
  346.     is found the entire code string and length are put into
  347.     the encoding table entry for the leaf's data value.
  348.  
  349.     Returns ERROR if codes are too long. }
  350.  
  351.     var l, r, return: integer;
  352.  
  353.     begin
  354.       return := null;
  355.       l := node[root].lchild;
  356.       r := node[root].rchild;
  357.  
  358.       if (l=NOCHILD) and (r=NOCHILD)
  359.         then begin  {have a leaf}
  360.                codelen[root] := level;
  361.                code[root] := tcode and ($FFFF shr (16 - level));
  362.                if level > 16
  363.                  then return := ERROR
  364.                  else return := NULL;
  365.              end
  366.         else begin
  367.                if l <> NOCHILD
  368.                  then begin  {Clear path bit and go deeper}
  369.                         tcode := tcode and not(1 shl level);
  370.                         if buildenc(level+1,l) = ERROR then return := ERROR;
  371.                       end;
  372.                if r <> NOCHILD
  373.                  then begin  {Set path bit and go deeper}
  374.                         tcode := tcode or (1 shl level);
  375.                         if buildenc(level+1,r)=ERROR then return := ERROR;
  376.                       end;
  377.              end;
  378.       buildenc := return;
  379.     end;
  380. {.pa}
  381.   procedure Build_Tree(var list: ValType; len: integer); {Huffman algorithm}
  382.  
  383.     var freenode: integer;         {next free node in tree}
  384.         lch, rch: integer;         {temporaries for left, right children}
  385.         i: integer;
  386.  
  387.     function Maximum(a, b: integer): integer;
  388.       begin
  389.         if a>b then Maximum:=a else Maximum:=b;
  390.       end;
  391.  
  392.     begin
  393.       write(', Building tree');
  394.       { Initialize index to next available (non-leaf) node.
  395.         Lower numbered nodes correspond to leaves (data values). }
  396.       freenode := NUMVALS;
  397.  
  398.       { Take from list two btrees with least weight and build an
  399.         interior node pointing to them.  This forms a new tree. }
  400.       while (len > 1)
  401.         do begin
  402.              lch := list[0]; { This one will be left child }
  403.  
  404.              { delete top (least) tree from the list of trees }
  405.              len := len - 1;
  406.              list[0] := list[len];
  407.              adjust(0, len - 1, list);
  408.  
  409.              { Take new top (least) tree. Reuse list slot later }
  410.              rch := list[0]; { This one will be right child }
  411.  
  412.              { Form new tree from the two least trees using a free node as root.
  413.                Put the new tree in the list. }
  414.              with node[freenode]
  415.               do begin;
  416.                    lchild := lch;
  417.                    rchild := rch;
  418.                    weight := node[lch].weight + node[rch].weight;
  419.                    tdepth := 1 + Maximum(node[lch].tdepth, node[rch].tdepth);
  420.                  end;
  421.              list[0] := freenode;       {put at top for now}
  422.              freenode := freenode + 1;  {next free node}
  423.              { reheap list to get least tree at top }
  424.              adjust(0, len - 1, list);
  425.            end;
  426.       dctreehd := list[0];   { head of final tree }
  427.     end;
  428. {.pa}
  429.   procedure Initialize_Huffman;
  430.  
  431.   { Initialize the Huffman translation. This requires reading the input file through any preceding translation
  432.     functions to get the frequency distribution of the various values. }
  433.  
  434.     var c, i: integer;
  435.         btlist: ValType;   { list of intermediate binary trees }
  436.         listlen: integer;  { length of btlist }
  437.         ceiling: integer;  { limit for scaling }
  438.  
  439. { Heap and Adjust maintain a list of binary trees as a heap with the top indexing the binary tree on the list which
  440.   has the least weight or, in case of equal weights, least depth in its longest path. The depth part is not strictly
  441.   necessary, but tends to avoid long codes which might provoke rescaling. }
  442.  
  443.     procedure Heap(var list: ValType; l: integer);
  444.       var i, len: integer;
  445.       begin
  446.         len := (l - 2) div 2;
  447.         for i:=len downto 0 do adjust(i, l - 1, list);
  448.       end;
  449. (*
  450.     procedure PrintFrequency;
  451.       var i, j: integer;
  452.       begin
  453.         j := 0;
  454.         for i:=0 to numvals-1
  455.           do if node[i].weight>0
  456.                then begin
  457.                       j := j + 1;
  458.                       writeln(lst,'node ',i:3,'  weight is ',node[i].weight:4:0);
  459.                     end;
  460.         writeln(lst);
  461.         writeln(lst,'Total node count is ',j);
  462.       end;
  463.  
  464.     procedure PrintList;
  465.       var i: integer;
  466.           str: string[10];
  467.       begin
  468.         writeln(', waiting');   readln(str);
  469.         for i:=0 to numvals-1
  470.           do begin
  471.                write('number ',i:3,'  length ',codelen[i]:2);
  472.                write('  weight ',node[i].weight:4:0);
  473.                if codelen[i]>0 then PrintBits(codelen[i], code[i]) else writeln;
  474.              end;
  475.       end;
  476.   *)
  477.   begin
  478.       write('Pass 1: Analysis');
  479.       crc := 0;   zero_tree;   state := NoHist;   EOFlag := false;
  480.  
  481.       repeat    { Build frequency info in tree }
  482.           c := ord(getcnr);
  483.           if EOFlag then c := SPEOF;
  484.           with node[c] do if weight < maxcount then weight := weight + 1;
  485.           if EOFlag then write(', End of file found');
  486.         until (EOFlag);
  487.       {PrintFrequency;}
  488.  
  489.       ceiling := MAXCOUNT;
  490.  
  491.       { Try to build encoding table. Fail if any code is > 16 bits long. }
  492.       repeat
  493.           if (ceiling <> MAXCOUNT) then write('*** rescaling ***, ');
  494.           scale(ceiling);
  495.           ceiling := ceiling div 2;  {in case we rescale again}
  496.  
  497.           listlen := 0;   {find length of list and build single nodes}
  498.           for i:=0 to numvals-1
  499.             do begin
  500.                  if node[i].weight > 0
  501.                    then begin
  502.                           node[i].tdepth := 0;
  503.                           btlist[listlen] := i;
  504.                           listlen := listlen + 1;
  505.                         end;
  506.                end;
  507.           heap(btlist, listlen-1);  { *** changed from listlen }
  508.           Build_Tree(btlist, listlen);
  509.           for i := 0 to NUMVALS-1 do codelen[i] := 0;
  510.         until (buildenc(0,dctreehd) <> ERROR);
  511.  
  512.       {PrintList;}
  513.       { Initialize encoding variables }
  514.       cbitsrem := 0;   curin := 0;
  515.     end;
  516. {.pa}
  517.   function gethuff: char; {returns byte values except for EOF}
  518.   { Get an encoded byte or EOF. Reads from specified stream AS NEEDED.
  519.  
  520.     There are two unsynchronized bit-byte relationships here:
  521.       The input stream bytes are converted to bit strings of various lengths via
  522.       the static variables named Cxxxxx.  These bit strings are concatenated without
  523.       padding to become the stream of encoded result bytes, which this function
  524.       returns one at a time. The EOF (end of file) is converted to SPEOF for
  525.       convenience and encoded like any other input value. True EOF is returned after
  526.       that. }
  527.  
  528.     var rbyte: integer;       {Result byte value}
  529.         need, take: integer;  {numbers of bits}
  530.         return: integer;
  531.  
  532.     begin
  533.       rbyte := 0;
  534.       need := 8;        {build one byte per call}
  535.       return := ERROR;  {start off with an error}
  536.  
  537.       {Loop to build a byte of encoded data.  Initialization forces read the first time}
  538.       while return=ERROR
  539.         do begin
  540.              if cbitsrem >= need
  541.                then begin {Current code fullfills our needs}
  542.                       if need = 0
  543.                         then return := rbyte and $00FF
  544.                         else begin
  545.                                rbyte := rbyte or (ccode shl (8 - need)); {take what we need}
  546.                                ccode := ccode shr need;                  {and leave the rest}
  547.                                cbitsrem := cbitsrem - need;
  548.                                return := rbyte and $00FF;
  549.                              end;
  550.                     end
  551.                else begin
  552.                       if cbitsrem > 0
  553.                         then begin  {We need more than current code}
  554.                                rbyte := rbyte or (ccode shl (8 - need)); {take what there is}
  555.                                need := need - cbitsrem;
  556.                              end;
  557.                       if curin = SPEOF
  558.                         then begin
  559.                                cbitsrem := 0;
  560.                                if need=8
  561.                                  then begin                       {end of file}
  562.                                         done := true;
  563.                                         return := 0; {any valid char value}
  564.                                       end
  565.                                  else return := rbyte and $00FF;  {data first}
  566.                              end
  567.                         else begin
  568.                                curin := ord(getcnr);
  569.                                if EOFlag then curin := SPEOF;
  570.                                ccode := code[curin];
  571.                                cbitsrem := codelen[curin];
  572.                              end;
  573.                     end;
  574.            end;
  575.       gethuff := chr(return);
  576.     end;
  577. {.pa}
  578.   procedure squeeze;
  579.     var c: char;
  580.     begin
  581.       writeln;   write('Pass 2: Squeezing');
  582.       reset(InFile);   rewrite(OutFile);   EOFlag := false;
  583.       write(', header');   Write_Header;
  584.       write(', body');     state := NoHist;
  585.       done := false;   c := gethuff;  {prime while loop}
  586.       while not(done)
  587.         do begin
  588.              write(OutFile,c);
  589.              c := gethuff;
  590.            end;
  591.     end;
  592.  
  593.  
  594. begin { Main }
  595.  
  596.   clrscr;   gotoxy(1,5);
  597.   writeln('File squeezer version ',version);
  598.   writeln;
  599.  
  600.   { get filename to process & convert to upper case}
  601.   write('Enter file to squeeze: ');   readln(InFileName);   writeln;
  602.   for i:=1 to length(InFileName) do InFileName[i] := upcase(InFileName[i]);
  603.  
  604.   { Find and change output file type }
  605.   start := 1; { skip leading blanks }
  606.   while (InFileName[start]=space) and (start <= length(InFileName)) do start := start + 1;
  607.   InFileName := copy(InFileName, start, length(InFileName)-start+1);
  608.   finish := pos('.',InFileName);
  609.   if finish=0
  610.     then OutFileName := InFileName + '.QQQ'
  611.     else begin
  612.            OutFileName := InFileName;
  613.            OutFileName[finish+2] := 'Q';
  614.          end;
  615.  
  616.   { open source file and check for existence }
  617.   assign(InFile,InFileName);   assign(OutFile,OutFileName);
  618.   {$I-}   reset(InFile);   {$I+}
  619.   if IOresult=0
  620.     then begin
  621.            write('The file ',InFileName,' (',longfilesize(InFile):6:0);
  622.            writeln(' bytes) is being squeezed to ',OutFilename);
  623.            Initialize_Huffman;
  624.            squeeze;
  625.            writeln(', Done.');   close(InFile);   close(OutFile);
  626.          end
  627.     else writeln('Error -- input file doesn''t exist');
  628.  
  629. end.
  630.