/* 
  Test_huf_encode.java
  Testing Huffman encoding.
  Read in .dct file and output a .huf file.
  Compile:   javac Test_huf_encode.java
  Run:  e.g. java Test_huf_encode ../6/t.dct t.huf
*/

import java.io.*;

public class Test_huf_encode {
   
  public static int read_dct_header( DataInputStream in )
  {
    byte dct_header[] = { 'D', 'C', 'T', '4', ':', '2', ':', '0' };
    byte [] bytes = new byte[dct_header.length];
    int width, height;
    try {
      in.read ( bytes );
      width  = in.readInt ();
      height = in.readInt ();
      System.out.printf("\nwidth=%d, height=%d \n", width, height );
    } catch (IOException e) {
       e.printStackTrace();
       System.exit(0);
    }
    for ( int i = 0; i < dct_header.length; ++i )
      if ( bytes[i] != dct_header[i] )
        return -1;      //wrong header

    return 1;
  }

  static void print_block( short X[][] )
  {
    for ( int i = 0; i < 8; ++i ){
      System.out.printf("\n");
      for ( int j = 0; j < 8; ++j ) {
        System.out.printf("%4d, ", X[i][j] );
      }
    }
  }


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

    //encoding
    try {
      FileInputStream fins = new FileInputStream( args[0] );
      DataInputStream in   = new DataInputStream ( fins );
      FileOutputStream fouts = new FileOutputStream( args[1] );
      BitOutputStream bitout = new BitOutputStream ( fouts );
      if ( read_dct_header (in ) == -1 ){
        System.out.println("Not DCT File");
        return;
      }
      while ( run.get64 ( Y, in ) > 0 ) {       
        quantizer.quantize_block ( Y );
        reorder.reorder ( Y, Yr );
        run.run_block ( Yr, runs );
        hcodec.huff_encode ( runs, bitout );      //encode and save
      }
      //No more data, encode the End of Stream Symbol
      hcodec.huff_encode_EOS ( bitout );
      in.close();
      bitout.close();
    } catch (IOException e) {
       e.printStackTrace();
       System.exit(0);
    }
  }
}
