import java.io.*;import java.net.*;import java.awt.*; public class TableSetter extends Thread{	boolean tableLoaded=false;	WordEater we;	NextWordResponse n;	VariableNode CurrentVariable;		// What is currently being parsed.	VariableNode VariableListRoot=null;	    /// The list of all variables. 	boolean WasThereNoError=true;		URL base;		// This must be passed down because only applets can discover their URL base.	    	Label announceHere=null;		public void setAnnounceHere(Label s){		announceHere=s;	}				 /* This returns the variable that starts out every production.   This is just set to be the first one in the list. The first alphabetically.   It would be possible to put some sort of random selection here too if   you wanted to add an additional signifier that said "I'm a good candidate   to start a production." */ VariableNode GetStartVariable()  {	return VariableListRoot;}	public boolean loadTable(){		//This function tries to load the information from the currently opened file into table.}		// Returns true if it succeeds. False if it signals an error.}       boolean looping;            VariableListRoot = null;       looping = true;       while (looping) {       		try {       			sleep(40);       		} catch (InterruptedException e) {       		}         if (HandleFirst()) {           looping = HandleProduction();         } else {            looping = false;         }        }       BuildBitTable();        // PrintVariableList(VariableListRoot);       return  WasThereNoError;      } 		public void run(){		//System.out.println("Starting the run thing.");		if (announceHere!=null){			announceHere.setText("Loading Grammar Table. Please Wait.");		}			try {       			sleep(40);       		} catch (InterruptedException e) {       		}		we.initializeScanHashTable();		we.openGrammarURL("BASE.CFL",base);				//System.out.println("OPened the grammar thing.");		loadTable();					if (announceHere!=null){			announceHere.setText("Table Loaded. Ready to go.");		}		tableLoaded=true;	}		public TableSetter(URL u){		base=u;		we= new WordEater();				}		public void AddVariable (VariableNode v ){		//This adds it to the root.}       VariableNode previous, node;		//For scanning along the list.}       int Relativity;      node = VariableListRoot;      previous = null; // Must init it.      if (VariableListRoot == null) {   		 VariableListRoot = v;    	 v.setNext(null);       } else if (node.w1.compareTo(v.w1)>0) {   		 VariableListRoot = v;         v.next = node;      } else {   		 while (node != null ) {   		 	Relativity = node.w1.compareTo(v.w1);            if (Relativity<0) {       			 previous = node;       			 node = node.next;            } else  if  (Relativity == 0) {      			 System.out.println("'"+  v.w1 +"'  has Been previously defined.");      		} else {        			previous.setNext(v);                v.setNext(node);      		    node = null;       			v=null;       		}       	  }          if (v != null) {      		previous.setNext(v);      		v.setNext(null);      	  }      }    }     		/* Looks up the list and finds the variable corresponding to it.   Note that everything is extremely slow to just keep this in a list! */ VariableNode FindVariable(String name){	VariableNode temp; /* Sort of a stunt double for FindVariable. */	int relativity; /* Just for storing the relative differences between strings. */	temp = VariableListRoot; /* Start at the very beginning. */	while (temp != null) {  	   	relativity = name.compareTo(temp.w1);  		if (relativity > 0) {    		temp = temp.next;  		} else {  			if (relativity == 0)   				 return temp;  			else   			  return null;  			} 		 }		return null;	}				public boolean HandleFirst(){	 // The first word in a line must be a variable. This will be used to set up the variable list...}       VariableNode v;		// This is what is going to get built...}  	 NextWordResponse wa,wb;  	 	 boolean answer=true;     wa = we.nextWord();    if (wa.stopChar == Globals.EndOfFileSignifier) {      if (! wa.w.equals(Globals.NullWord)) {       System.out.println("Unexpected end of the file.");	}  	return false;    }     if ((wa.w.equals(Globals.NullWord)) || (wa.w.charAt(0) != Globals.VariableSignifier)) {     System.out.println("Here's the first char:"+wa.w.charAt(0)+"::"+ Globals.VariableSignifier+"::");     System.out.println("Expected a variable name at the beginning of the line:");    } else {		//System.out.println("Processing variable:"+wa.w);      v=new VariableNode();      v.setW1(wa.w);	  // Now add it to the list in the right place...}      AddVariable(v);      CurrentVariable = v;    }    if (wa.stopChar != Globals.EqualityCharacter) {    	do {          wa = we.nextWord();   		} while ((wa.stopChar == Globals.Space) && (wa.w.equals(Globals.NullWord)));       if (! wa.w.equals(Globals.NullWord)) {         System.out.println("The Variable should only be one word. "+ wa.w+" is too much. Error in line:");       }     }     return true;    }            public void  SkipToEnd(){	 	// This procedure just keeps hitting NextWord until it hits the double StoppingCharacter, which when}		// I wrote this line was defined to be '//'.}  	NextWordResponse wa;    char previous;    boolean dontStopNow=true;        // WasThereNoError := false;     wa = we.nextWord();  	 do {       previous = wa.stopChar;       wa = we.nextWord();       if (wa.stopChar==Globals.EndOfFileSignifier) {       	  dontStopNow=false;       } if ((wa.w.equals(Globals.NullWord)) && (previous == Globals.StoppingCharacter) && (wa.stopChar== Globals.StoppingCharacter)) {  	 	  dontStopNow=false;  	   }  	 } while (dontStopNow);  	}  	 /*public double wordToValue(String s){ 	double answer = Double.valueOf("0"+s).doubleValue(); 	return answer; } */ 	public double wordToValue(String s){ 		double answer = 0.0; 		boolean fraction=false; 		int count = 0; 		for (int i=0;i<s.length();i++){ 			switch (s.charAt(i)){ 				case '0': 					answer=10*answer+0;break; 				case '1': 					answer=10*answer+1;break; 				case '2': 					answer=10*answer+2;break; 				case '3': 					answer=10*answer+3;break; 	 			case '4': 					answer=10*answer+4;break; 	 			case '5': 					answer=10*answer+5;break; 	 			case '6': 					answer=10*answer+6;break; 	 			case '7': 					answer=10*answer+7;break;  	 			case '8': 					answer=10*answer+8;break;  	 			case '9': 					answer=10*answer+9;break;  	 			case '.': 					fraction = true;break; 			} 			if (fraction) count++; 		} 		for (int i=0;i<count;i++){ 			answer=answer/10; 		} 		return answer; 	}  	 					 						 	     public boolean HandleProduction(){	//Keeps Adding Production until it encounters a double Stopping Character.}    WordNode   LastAddedWord=null;		//This is just a place keeper which points to the last word added so the next can be updated when another one is added.}   ProductionNode TheProduction=null;		//This is where the info goes...}   NextWordResponse wa; 		//For local reasons...}       boolean startedVariables=false;		//Variables can only come at the end of productions...}   boolean IsError;		//If there is a problem this get's set to be true.}   boolean answer=true;           do {   	  do {        wa = we.nextWord();        if (wa.stopChar == Globals.EndOfFileSignifier) {           if (LastAddedWord != null) {             System.out.println("Just parsed something left incomplete by the end of the file:");             // PrintWordList(LastAddedWord);             System.out.println("Unexpected end of the file.");            answer = false;      	   }      	   return answer;     	}        if (! wa.w.equals(Globals.NullWord)) {           if (LastAddedWord == null ) {  //Start a new production...             if (wa.w.charAt(0) == Globals.VariableSignifier){                 System.out.println("'The first word of a production, '"+ wa.w+"' cannot be a variable. Ignoring Production.");      		   SkipToEnd();               wa.stopChar  = Globals.StoppingCharacter;               wa.w = Globals.NullWord;    		 } else {    		 		//System.out.print(":"+wa.w);      			 TheProduction = new ProductionNode();                 TheProduction.setNext(CurrentVariable.getProductions());                 CurrentVariable.setProductions(TheProduction);//{Put it at the beginning of the list...}       			 LastAddedWord= new WordNode(wa.w);       			 TheProduction.setTheWords(LastAddedWord);       			 startedVariables = false;    		 }    		}  else {       			LastAddedWord.setNext(new WordNode(wa.w));                LastAddedWord = LastAddedWord.getNext();                if (wa.w.charAt(0) == Globals.VariableSignifier) {                   if  (! startedVariables) {       				  startedVariables= true;       				}       			} else if (startedVariables) {     			  System.out.println("The format of a production is terminal, terminal ... terminal, variable... varable. A terminal comes before the variable in line:");     			  CurrentVariable.productions = null;//Clean out this baby to signal a problem.}      			}      		}      	}      	} while (wa.stopChar!= Globals.StoppingCharacter);       	   if (LastAddedWord != null) {    	 LastAddedWord.next = null;     	 LastAddedWord = null;		}				       if (! wa.doubleStop) {		//At this point a production has been stored away. Now get its probability...}	      wa  = we.nextWord();          if (wa.stopChar == Globals.EndOfFileSignifier) {      		 System.out.println("Unexpected end of the file when looking for a probability.");             answer = false;             return answer;      	  }      	   	//System.out.print(":N:"+wa.w);          	TheProduction.setProbability(wordToValue(wa.w));    	  	   }     else if (wa.stopChar != Globals.StoppingCharacter) {             wa = we.nextWord();             System.out.println("The word '"+ wa.w+ "' does not belong in the probability field . ");    //   write('The error occurs in production:');     //  PrintWordList(LastAddedWord)  	}  }  while ( ! wa.doubleStop);  return answer;}            public BitNode InsertIntoBitList (BitNode node, BitNode ListStart){	  //This is just a temporary procedure that maintains a list of BitNodes Sorted by Probability.}          BitNode Previous, Scanner;		//For scanning along the list.}	 BitNode answer=ListStart;     if (ListStart ==null) {       answer = node;       node.up = null;      } else if (node.probability <= ListStart.probability) {       node.up = ListStart;       answer = node;     }  else {       Scanner = ListStart;       Previous = ListStart;       while (Scanner != null) {      	 if (node.probability > Scanner.probability){          	  Previous = Scanner;        	  Scanner = Scanner.up;       	 } else {       		   Previous.up = node;        	  node.up = Scanner;        	  Scanner = null;        	  node = null;//{To signal that it was added...}			}		}    	  if (node != null) {         Previous.up = node;         node.up = null;     }   }   return answer; }         public void BuildBitTable(){	// It is important that there be a tree that describes how the bits are assigned to each production...}     BitNode IntermediateBitList;		//This contains the list of bit nodes that don't have a root. When there is only}		//one left, then this is crowned king and assigned to the variable's ItsBitRoot.}   BitNode TempBit;		//Used in the building...}   ProductionNode productionList;		//This is the list of productions that the bit list will be built out of...}   int NextBitNumber;		//This is used for assigning a unique number to each node...}   VariableNode v;		// This is so the list can do this for every variable...}      v  = VariableListRoot;    while (v != null) {         productionList = v.productions; //This is the list...}       IntermediateBitList = null;       NextBitNumber = 0;       while (productionList != null)  {         TempBit = new BitNode();                   TempBit.setProbability(productionList.probability);         TempBit.left = null;         TempBit.right = null;         TempBit.polarity = true;         TempBit.bitNumber = -1;         TempBit.theProductionNode = productionList;                 productionList.itsBit = TempBit;         IntermediateBitList=InsertIntoBitList(TempBit, IntermediateBitList);         productionList = productionList.next;        }	  // Now one bit for each production list, let's start making pairs...}    while (IntermediateBitList.up != null)  { // {While there is more than one node in the list...}       TempBit = new BitNode();       TempBit.setProbability(IntermediateBitList.probability + IntermediateBitList.up.probability);       TempBit.left = IntermediateBitList;       TempBit.right = IntermediateBitList.up;       TempBit.bitNumber = NextBitNumber++;       TempBit.polarity = true;       TempBit.theProductionNode = null;              IntermediateBitList = IntermediateBitList.up.up;//Get Rid of the top two...}       TempBit.left.polarity=false; // Flip one... One son should be true and the other false.}       TempBit.left.up = TempBit;       TempBit.right.up = TempBit;       IntermediateBitList=InsertIntoBitList(TempBit, IntermediateBitList); 	}	//There should only be one left at this point...}    v.itsBitRoot = IntermediateBitList;    IntermediateBitList.up = null;    v = v.next; }}                        }