/* 
  Test_huf_deccode.java
  Testing Huffman decoding.
  Read in a .huf file and output a .dec file.
  Comple: javac Test_huf_decode.java
  Run:    e.g. Test_huf_decode t.huf t.dec
*/

import java.io.*;

public class Test_huf_decode {
   
  public static void main(String[] args) throws InterruptedException
  {
    if (args.length < 2) {
      System.out.println("Usage: java " + "Test_huf_decode" +
        " input-filename " + "output-filename");
      System.out.println("    e.g. Test_huf_decode t.huf t.dec" );
      System.exit(-1);
    }
  
    Hcodec hcodec = new Hcodec();
    hcodec.build_htable();
    hcodec.print_htable(); 
    Dtables decode_tables = new Dtables();    //tables used in decoding process
    hcodec.build_huff_tree ( decode_tables );
    Run3D runs[] = new Run3D[64];
    for ( int i = 0; i < 64; ++i )
      runs[i] = new Run3D();
    Run run = new Run();
    Reorder reorder = new Reorder();
    Quantizer quantizer = new Quantizer();
    short Yr[][] = new short[8][8];
    short Y[][] = new short[8][8];

    //decoding
    try {
      int bit;
      FileInputStream fins = new FileInputStream( args[0] );
      BitInputStream bitin = new BitInputStream ( fins );
      FileOutputStream fouts = new FileOutputStream( args[1] );
      DataOutputStream out = new DataOutputStream ( fouts );
      while ( hcodec.huff_decode( bitin, decode_tables, runs ) > 0 ){
        run.run_decode ( runs, Yr );
        reorder.reverse_reorder ( Yr, Y );
        quantizer.inverse_quantize_block ( Y );
        run.put64( Y, out );
      }
      bitin.close();
      out.close();
    } catch (IOException e) {
       e.printStackTrace();
       System.exit(0);
    }
  }
}
