import WAVInputStream;
import java.io.*;
import HaarWavelet;
import WaveletCompression;
import FourFourWavelet;
import FourTwoWavelet;

class Encode
{	
	public static void main(String args[])
	{
		if(args.length != 1)
    {
      System.out.println("No file specified");
      return;
    }
    String filename = args[0];
		try
		{
			WAVInputStream Sound = new WAVInputStream(new BufferedInputStream(new FileInputStream(filename)));
			int Length = Sound.length();
			int Channels = Sound.channels();
			int Depth = Sound.depth();
			int Rate = Sound.rate();

			System.out.println("Bits: " + Depth + " Channels: " + Channels + " Sample Rate: " + Rate + " Length: " + Length);
			short s[] = new short[Channels * Length];
			int m[] = new int[Channels * Length];
			Sound.readSample(s, 0, Length);
			for(int i = 0; i < s.length; i++)
			{
				m[i] = s[i];
			}
			FourTwoWavelet.FWT(m, 8);
			BufferedOutputStream BuffOut = new BufferedOutputStream(new FileOutputStream("test.bin"));
			int bitcounts[] = new int[8];
			bitcounts[0] = 13;
			bitcounts[1] = 11;
			bitcounts[2] = 10;
			bitcounts[3] = 10;
			bitcounts[4] = 9;
			bitcounts[5] = 9;
			bitcounts[6] = 8;
			bitcounts[7] = 8;
			WaveletCompression.compress(m, 8, bitcounts, BuffOut);
			BuffOut.close();
		/*	for(int i = 0; i < m.length; i++)
			{
				m[i] = (short)m[i];
			}*/


			BufferedInputStream BuffIn = new BufferedInputStream(new FileInputStream("test.bin"));
			WaveletCompression.decompress(m, 8, bitcounts, BuffIn);
			FourTwoWavelet.IFWT(m, 8);

			for(int i = 0; i < s.length; i++)
			{
				if(m[i] > 32767)
				{
					s[i] = 32767;
				}
				else
				{
					if(m[i] < -32768)
					{
						s[i] = -32768;
					}
					else
					{
						s[i] = (short)m[i];
					}
				}
			}
			WAVOutputStream s2 = new WAVOutputStream(new BufferedOutputStream(new FileOutputStream("out.wav")), Channels, Rate, Depth, Length);
			s2.writeSample(s, 0, Length);
			s2.close();
		}
		catch(IOException e)
		{
			System.out.println("IO Exception: " + e);
		}
		catch(Exception e)
		{
			System.out.println("Exception: " + e);
		}
	}
}
