/* James Little 5-5-01 
   I hope this is one of the last programs I have to write in this course.
*/

package jlittle_ex9.decompress;

import java.io.*;
import java.util.*;
import util241.*;

public class Decompress {
    private static Decompress  a;
    private static BitStreamInputStream reader;
    private static BufferedOutputStream writer;
    private static String outputfilename;

    public static void main(String [] args){
	String inputfilename = "";
	String outputfilename = "";
	try{
	    if (args.length == 1){//ARGS="test"
		inputfilename = args[0];
		outputfilename = inputfilename + ".DEC";

		// open input streams
		FileInputStream inFile = new FileInputStream(inputfilename);
		BufferedInputStream in = new BufferedInputStream(inFile);
		reader = new BitStreamInputStream(in, 12);

		//open output streams
		FileOutputStream outFile = new FileOutputStream(outputfilename);
		writer = new BufferedOutputStream(outFile);

	    }else{

		reader = new BitStreamInputStream(System.in, 12);
		writer = new BufferedOutputStream(System.out);
		
	}
	   
	}catch(IOException e){
	    System.out.println("Error: " + e);
	    System.exit(1);
	}
	a = new Decompress();
	a.decompress();	
    }
    	

    // decompression routine
    public void decompress(){
	int MAX_VALUE = 4000; 
	//    System.out.println("decompressing...... ");
	// once we get to here we are going
	// to have to flush the table

	Vector string_table = new Vector();

	for(int i=0; i<256; i++){
	    string_table.add(String.valueOf((char)i));
	}

	int oldCode = 0, newCode = 0;


	try{

	    String aString = "", aChar = "";

	    oldCode = (int)reader.readBitField();
	    if(oldCode!=-1){
		aChar = String.valueOf((char)oldCode);
		
		writer.write(oldCode);  // looks like it should be aChar.. but done with oldCode??
		
		// loop through the rest of the characters
		while((newCode=(int)reader.readBitField())!=-1) {
		    
		    if(newCode >= string_table.size()){
			aString = (String)string_table.get(oldCode);
			aString = aString + aChar;
		    } else aString = (String)string_table.get(newCode);

		    writer.write(aString.getBytes());
		    aChar = aString.substring(0,1);
		    string_table.add((String)string_table.get(oldCode)+aChar);
		    oldCode = newCode;

		    if(string_table.size()>MAX_VALUE){
			string_table.removeAllElements();	
			for(int i=0; i<256; i++){
			    string_table.add(String.valueOf((char)i));
			}
		    }
	
		} // end while
	    }// end if the file is empty
	    reader.close();
	    writer.close();
	} catch(IOException e){ 
	    System.out.println("ERROR: "+e);
	    System.exit(1);
	}

	//for(int j=256; j<string_table.size() ; j++){
	//  System.out.println(j+"\t"+string_table.elementAt(j));
	//}
	
    }// end decompress
	
} // end App
