// Addition Parser

public class AddParser {

    private static CS211In  fIn;   // input source
    private static CS211Out fOut;  // output target
    private static String report;  // legality of expr

    // Evaluate arithmetic expression:
    public static void main(String[] args) {
	setIO(args);   // set input/output devices
        checkExpr();   // evaluate addition expr
	cleanUp();     // close open I/O devices
    }
    
    // Set input device to System.in for no CL args
    // or a particular file:
    private static void setIO(String[] args) {

	switch (args.length) {
	case 2: // file input, file output
	    fIn = new CS211In(args[0]);
	    fOut = new CS211Out(args[1]);
	    break;
	case 1: // file input, screen output
	    fIn = new CS211In(args[0]);
	    fOut = new CS211Out();
	    break;
	case 0: // screen input, screen output
	    fIn = new CS211In();
	    fOut = new CS211Out();
	    promptUser();
	    break;
	default:
	    fOut.println("Something is wrong with I/O!");
	    System.exit(0);
	}

    }
    



    // Prompt user for expr if using command-line:
    private static void promptUser() {
	fOut.println("Enter an expression:");
    }

    // Find sum of input expr and label it:
    private static void checkExpr() {
 	fOut.println("Result: "+checkSum());
    }
    
    // Find sum of expression:
    private static boolean checkSum() {

	// Inspect current character from input stream:
	switch( fIn.peekAtKind() ) {

	case CS211In.INTEGER: // E -> int
	    fIn.getInt();     // remove int from stream
            return true;
	    
	case CS211In.OPERATOR: // E -> (E1 + E2)
	    return fIn.check('(') && checkSum() && 
		fIn.check('+') && checkSum() && 
		fIn.check(')');

	default: // Unknown E
	    return false;

	} // end switch
    }
    
    // Cleanup for opened I/O devices
    private static void cleanUp() {
	fIn.close();
	fOut.close();
    }
    
} // class AddParser