import java.io.*;import java.net.*;import java.awt.*;class MyIntegerWrapper {	int x;		// Used to pass by reference.			public MyIntegerWrapper(int zz){		x=zz;	}		public void setX(int y){		x=y;	}	public int getX(){		return x;	}}public class MimicParser {		public final static int spacer=1;	public final static int normal=2;	public final static int stopper=3;		public final static char equalityCharacter='=';	public final static char stoppingCharacter='/';		public final static int MaxLookAhead=200; 	public final static int StandardLookAhead=20;    /* MaxLookAhead is the absolute maximum permitted by the sizes of the array.       StandardLookAhead is the usual amount to search. Note that the running       time is potentially exponential in the LookAhead... Don't be greedy.       Sorry I didn't write a better algorithm. */           public RandomBits rb = new RandomBits();    	// For synchronizing things. ...     public boolean debug=false;    public int debugStackDepth=0;    	// For controlling the printout.           public int offsetTraffic=0;    	// Used for passing information.    	public TableSetter ts;		// Where te information is kept.			public TextField outputLocation=null;		// Where the data goes. 	public String[] LookAheadTable;    	/* The next MaxLookAhead words are kept in this circular array.      		 When the end of file is found, the table contains nullWord. */	public int LookAheadOffset=0;   	 /* Keeps track of where the first word will be. */ 	public boolean FoundAmbiguity=false;    /* When the machine starts to do some parsing and discovers that there       are two different paths for each production, this baby is set to true. */	public int SoftMaxLookAhead;    /* This allows the parser to set its lookahead on the fly if it wants to	increase it. */	public boolean ReachedEndOfFile=false;    /* Set true when everything is exhausted... */	StringBuffer outputStrings;		/// Where the data is going.		int tempOutputBits = 0;	int tempOutputBitsPosition = 0;		public void openOutputFile(){		outputStrings= new StringBuffer("");	}		String toBeParsed;		// What will be parsed.	int toBeParsedPosition=0;		// The current characters.	public int[] scanTable=new int[256];		// This is a scan table used for parsing.			public void setOutputLocation(TextField f){		outputLocation=f; 	}					public void initializeScanHashTable(){ 		//The Scanning Hash Table has 256 entries. They identify a character as either, letter, stop character,}		//a space or a comment.}  	int i; 		for (i=14; i<=255; i++){ 			scanTable[i]=normal; 		} 		for (i=0; i<=13; i++){ 			scanTable[i]=spacer; 		}    		 scanTable[(byte)(equalityCharacter)] = stopper;  		  scanTable[(byte)(stoppingCharacter)]  = stopper;  		  scanTable[(byte)(' ')] = spacer; 	}	public void debugFirstPrint(String s){		for (int i=0; i<debugStackDepth;i++){			System.out.print("-");		}		System.out.print(s);	}		public void debugPrintln(String s) { 		for (int i=0; i<debugStackDepth;i++){			System.out.print("-");		}		System.out.println(s);	}			public String parserNextWord(){		// Pull off the next word. 		String answer ="";		while ((toBeParsedPosition < toBeParsed.length()) && (scanTable[toBeParsed.charAt(toBeParsedPosition)] != normal)) {			toBeParsedPosition++;		} 		while ((toBeParsedPosition < toBeParsed.length()) && (scanTable[toBeParsed.charAt(toBeParsedPosition)] == normal)) {			answer=answer+toBeParsed.charAt(toBeParsedPosition++);		}		if (toBeParsedPosition >= toBeParsed.length()){			ReachedEndOfFile = true;		}		return answer+" ";	} /* Sets up the lookahead buffer to keep all of the words in place. */	public void InitLookAhead(){		int i;		char Stopper; /* to be ignored. */		LookAheadTable = new String[MaxLookAhead+1];						LookAheadOffset = 0;		for (i = 0; i <= MaxLookAhead - 1; i ++){  			LookAheadTable[i]= parserNextWord();  		}	}		 public MimicParser(TableSetter tt, String doMe){     	ts=tt;     	toBeParsed = doMe;     	toBeParsedPosition=0;     	initializeScanHashTable();     	InitLookAhead();     } public String  TimeDelayNextWord(){	String result;	result=LookAheadTable[LookAheadOffset];	LookAheadTable[LookAheadOffset]=parserNextWord();	 	LookAheadOffset = (LookAheadOffset + 1) % MaxLookAhead;	return result;}				public char convertNumToChar(int c){		// Just converts things back.				switch(c){			case 23:			case  31:			case  26:			case 0: return ' '; 			//  29=11101=10111=23			// 31 = 11111=11111=31			// 11= 01011-11010=26			// 00000=00000			case 16: return 'A'; 			// 00001=10000=16			case 8: return 'B'; 			// 00010=01000=8			case 24: return 'C'; 			// 00011=11000=24			case 4: return 'D'; 			// 00100=00100=4			case 20: return 'E'; 			// 00101=10100=20			case 12: return 'F'; 			// 00110 = 01100 = 12			case 28: return 'G'; 			// 00111=11100=28			case 2: return 'H'; 			// 01000=00010=2			case 18: return 'I'; 			// 01001=10010=18			case 10: return 'J'; 			// 01010 = 01010=10			case 15: return 'K'; 			// 01011 = 11010=26			// K is now 30=11110=01111=15			case 6: return 'L';			// 01100 = 00110 = 6 			case 22: return 'M'; 			// 01101 = 10110=22			case 14: return 'N'; 			// 01110 = 01110 = 14			case 30: return 'O'; 			// 01111= 11110=30			case 1: return 'P'; 			// 10000= 00001 = 1			case 17: return 'Q'; 			// 10001=10001=17			case 9: return 'R'; 			// 10010 = 01001 = 9			case 25: return 'S'; 			// 10011 = 11001 = 25			case 5: return 'T'; 			// 10100 = 00101= 5			case 21: return 'U'; 			// 10101= 10101=21			case 13: return 'V'; 			// 10110 = 01101 = 13			case 29: return 'W'; 			// 10111=11101 =29			case 3: return 'X'; 			// 11000=00011=3			case 19: return 'Y'; 			// 11001=10011=19			case 11: return 'Z'; 			// 11010=01011 = 11	 		case 27: return '-';	 		// 11011=11011 = 27	 		default: return '*';	 	}	}			public void storeOutputBit(boolean b){		if (b) {			tempOutputBits = (tempOutputBits << 1) +1;		} else 			tempOutputBits = (tempOutputBits <<1);		tempOutputBitsPosition++;		if (tempOutputBitsPosition>=5){			tempOutputBitsPosition = 0;			outputStrings.append(convertNumToChar(tempOutputBits));			tempOutputBits = 0;		}	}			public boolean RandomBit(int a){		return true;		// No random synchronization at this time.	}			public void ProductionToBits(ProductionNode p){		BitNode BitPointer; /* This will lead the way. */		long TempBit; /* This will hold the bits... */		int BitCounter=0; /* This is position of the next bit to be stored. */		boolean[] store=new boolean[30];			// This should be enough. 		rb.updateRandomBits();			/* Get a new group of random bits for the random generator... */		TempBit = 0;		BitCounter = 0;		BitPointer = p.itsBit;  /* We're not concerned about the first node because			    it is just an interface. */		//debugFirstPrint("Bits:");		while (BitPointer.up != null) {  			if (BitPointer.polarity) {  					store[BitCounter++]=(rb.randomBit(BitPointer.up.bitNumber) && true);  					// System.out.print("T");   				} else {   					store[BitCounter++]=(rb.randomBit(BitPointer.up.bitNumber) ^ true);   					// System.out.print("F");    			}	    		BitPointer= BitPointer.up;		}		for (int i=BitCounter-1;i>=0;i--){			storeOutputBit(store[i]);}			// These are backwards. We can reverse them here.	//	System.out.print(" ");	}/* Imagine this case. You are now trying to decide whether the next token,   say "Ernest" came for the production of a variable "*Dudes" or "*Duds". It   could be from either. This tries to lookahead and see if there is any clue   that says, "Hey, it can't be "*Dudes" because the production of the token   "Ernest" is always followed by the token "Rex" to indicate his stature. */ public ProductionNode TokenInVariable(MyIntegerWrapper MoreOffsetWrapper, VariableNode v){	ProductionNode ProductionNumber; /* Well not as much a number as a pun. */	boolean OneFound;    	/* This is just set to look for ambiguities...Problems, you know.... */	int  RealOffset;   		 /* This holds the temporary Offset that is passed to the CheckWordList     		  function. */    MyIntegerWrapper tempOffset=new MyIntegerWrapper(0);	ProductionNode result = null;			ProductionNumber = v.productions;	OneFound = false;	RealOffset = MoreOffsetWrapper.getX();	while ((ProductionNumber != null) && !OneFound) {  		tempOffset.setX(RealOffset);  		debugStackDepth += 2;  		if (CheckWordList(tempOffset, ProductionNumber.theWords)) {  		if (debug) { 			WordNode temp = ProductionNumber.theWords;	    		debugPrintln("TokenInVariable found production of "+v.w1+":" + tempOffset+":");    		while (temp != null) {      		   System.out.print(temp.w1);      		   temp = temp.next;    	  	}   			 System.out.println(" ");   		}     		OneFound = true;     		MoreOffsetWrapper.setX(tempOffset.getX()-1);    		result = ProductionNumber;    		}    		  		debugStackDepth -= 2;  		ProductionNumber = ProductionNumber.next; 	 }return result;}		/* This compares the words in the word list with the words in the lookahead   buffer.  If they all match, then BINGO! */ public  boolean CheckWordList(MyIntegerWrapper offset, WordNode www) {	WordNode checkMe = www;	int newOffset = offset.x;	MyIntegerWrapper passItOn=new MyIntegerWrapper(0);	//debugFirstPrint("Offset:"+passItOn.x+" Comparing word:"+checkMe.w1);	while ((newOffset < SoftMaxLookAhead )&& (checkMe != null)) {  		if (checkMe.w1.charAt(0) == Globals.VariableSignifier) {  			passItOn.setX(newOffset);  	//		System.out.println("");  	//		debugPrintln("Offset:"+passItOn.x+" Going down in CheckWordList with :"+checkMe.w1);  			  		debugStackDepth += 2;    		if (TokenInVariable(passItOn, ts.FindVariable(checkMe.w1)) == null) {    //			System.out.println("Offset:"+passItOn.x+"Failing to go deeper in CheckWordList with :"+checkMe.w1);      			offset.setX(passItOn.getX());      			return false;      		}      		  		debugStackDepth -= 2;      		       			offset.setX(passItOn.getX());      //		 debugPrintln("Offset:"+passItOn.x+"Returning Successfully in CheckWordList with :"+checkMe.w1);			   			newOffset= passItOn.getX()+1;    		checkMe = checkMe.next;    	} else if (LookAheadTable[(newOffset + LookAheadOffset) % MaxLookAhead].compareTo(checkMe.w1) != 0) {		//		System.out.println(""+checkMe.w1+"::FAILED");			offset.setX( newOffset);    		return false;    	} else {    	//	System.out.print(""+checkMe.w1);    		newOffset ++;    		checkMe = checkMe.next;    	}	}/* {checkMe = www;printf("CheckWordList: match found (%d:%d), ", *MoreOffset, newOffset);while (checkMe != null) {  printf("%s", checkMe->w1);  this = checkMe -> next;  }printf("\n");}*/ 	offset.setX(newOffset);	//debugPrintln("Found at offset:"+newOffset);return true;}/* THIS IS BROKEN. I haven't fixed the passing convention for using the WRAPPER to pass values. *//* The Serious Version Checks for Parsing Ambiguities.... This is only done on   the first call. You could get rid of this and just let the program choose   the first production it finds. This will be faster, but it might lead to   errors. I've chosen to include this because it is computationally difficult   (at least for now) to ensure that CFLs are non-ambiguous. */ public ProductionNode SeriousTokenInVariable(int MoreOffset, VariableNode v){	ProductionNode ProductionNumber; /* Well not as much a number as a pun. */	boolean OneFound;   		 /* This is just set to look for ambiguities...Problems, you know.... */	int  RealOffset, bestOffset;	MyIntegerWrapper tempOffset=new MyIntegerWrapper(0);  	  /* This holds the temporary Offset that is passed to the CheckWordList     		  function. */	ProductionNode result = null;	ProductionNumber = v.productions;	OneFound = false;	RealOffset = MoreOffset;	 		bestOffset = MoreOffset+1; /// This could be an error????	 		tempOffset.setX(RealOffset);	while (ProductionNumber != null) { 		tempOffset.setX(RealOffset);  		if (OneFound) {    	if (CheckWordList(tempOffset, ProductionNumber.theWords)) {     		if (tempOffset.getX() == bestOffset) {				System.out.println("Parsing Ambiguity Here!!! Try growing the lookahead. ");				FoundAmbiguity = true;				return null;			} else if (tempOffset.getX() > bestOffset) {				bestOffset = tempOffset.x;				result = ProductionNumber;			}    		  /* else ignore shorter match */      	}    	}  else if (CheckWordList(tempOffset, ProductionNumber.theWords)) {    		OneFound = true;    		bestOffset = tempOffset.x;    		result = ProductionNumber;   		}  		ProductionNumber = ProductionNumber.next;  	}  	if (debug) { 		WordNode temp = result.theWords;    	//System.out.print("TokenInVariable found production of "+v.w1+":" + tempOffset+":");    	while (temp != null) {      	   System.out.print(temp.w1);      		temp = temp.next;      	}   	 //System.out.println(" ");   	}return result;}	/* This routine takes the frame and figures out which pointer would match... */ public void DoFrame(MimicParseFrame f){	ProductionNode Prod;  /* This is the location of the pointer... */	MimicParseFrame NewFrame; /* If a new frame is needed... */	int CurrentDepth; /* Used to halt the spread of the search. */	MyIntegerWrapper curDepth=new MyIntegerWrapper(0);		FoundAmbiguity = false;	SoftMaxLookAhead = StandardLookAhead;	CurrentDepth = 0;	//debugPrintln("Looking up variable:"+f.theVariable.w1);	debugStackDepth+=3;	curDepth.setX(CurrentDepth);	Prod = TokenInVariable(curDepth, f.theVariable);	/* I realize that it is a bit of an overkill to use a big hammer like 	  SeriousTokenInVariable, but it is late at night and I don't want to bother  	 writing an elegant method that uses breadth first instead of depth-first. */  	 	debugStackDepth-=3;	if (FoundAmbiguity) { 		 FoundAmbiguity = false;  		SoftMaxLookAhead = MaxLookAhead;      /* This just doubles the lookahead for the fun of it... */  		CurrentDepth = 0;  			curDepth.setX(CurrentDepth);			Prod = TokenInVariable(curDepth, f.theVariable); 	 }	if (Prod == null) { 		 System.out.println("Can't seem to find a production for:"+f.theVariable.w1); 			curDepth.setX(CurrentDepth);			Prod = TokenInVariable(curDepth, f.theVariable);		//longjmp(LABEL_199, true); 	 } else if (!FoundAmbiguity) { /* We've found something.... */  		ProductionToBits(Prod); /* Store the bits... */  	    NewFrame= new MimicParseFrame();  		f.theWordsToMatch = Prod.theWords;  		while (f.theWordsToMatch != null) {    		if (f.theWordsToMatch.w1.charAt(0) == Globals.VariableSignifier) {     		 	NewFrame.theVariable = ts.FindVariable(f.theWordsToMatch.w1);     	//	 	debugPrintln("We're about to go down with :"+f.theWordsToMatch.w1+" Current Depth:"+CurrentDepth);      		    debugStackDepth+=3;      		    DoFrame(NewFrame);      		    debugStackDepth-=3;      	//	    debugPrintln("Coming back from :"+f.theWordsToMatch.w1+" Current Depth:"+CurrentDepth);     		} else {    		  String theOther = TimeDelayNextWord();      		  if (f.theWordsToMatch.w1.compareTo(theOther) != 0) {				System.out.println("Problem in parsing the file.  The Word "+f.theWordsToMatch.w1+" doesn't belong here.");				System.out.println("Supposed to match:"+theOther);				//				longjmp(LABEL_199, true);		    	}     	 	}    		f.theWordsToMatch = f.theWordsToMatch.next;   		 }  }}public String stripSpaces(String  s){	int i=s.length()-1;	while (s.charAt(i)==' ') {		i--;	}	return s.substring(0,i+1);} public void DoItAllLoop(){	MimicParseFrame BaseFrame; /* This is the first frame allocated. */	int i=0;  rb.syncRandomBits();  openOutputFile(); BaseFrame = new MimicParseFrame();  BaseFrame.theVariable = ts.GetStartVariable();  do {    DoFrame(BaseFrame);    i++; // This is a safety net to pull us out of the loop.    } while ((i<10) && !        (ReachedEndOfFile && LookAheadTable[LookAheadOffset].compareTo(Globals.NullWord) == 0));    if (outputLocation!=null){    	outputLocation.setText(stripSpaces(outputStrings.toString()));    }  //  System.out.println("Finished."); //	rb.outputDebugArray();}}