package tests;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import java.util.ArrayList;
import PIANOS.exceptions.SyntaxException;

public class EquationTest{
    public static void main (String[] args) throws SyntaxException{
	if (args.length != 1)
	    System.exit(1);
	
	String equation = args[0];
	while (equation.indexOf(' ') != -1)
	    equation = equation.substring(0, equation.indexOf(' ')) + equation.substring(equation.indexOf(' ')+1);
	
	ArrayList<String> tempString;
	ArrayList<String> variables;
	    

	// now we have
	// EXP(alpha * 12 / LOG(beta - 1.0 * gamma)) ...
	// we are interested in parts alpha, beta, gamma and their starting indices.
	// IF I understand correctly, variable names are
	// the only part here written in lowercase a-z.
	Pattern p = Pattern.compile("[a-z]+");
	Matcher m = p.matcher(equation);	    
	int last = 0;
	int index = 0;
	
	Pattern sum = Pattern.compile("SUM\\(\\&[a-z]+\\)");
	Pattern count = Pattern.compile("COUNT\\(\\&[a-z]+\\)");
	
	Matcher sumM = sum.matcher(equation);
	Matcher countM = count.matcher(equation);
	
	tempString = new ArrayList<String>();
	variables = new ArrayList<String>();
	boolean add = true;
	
	if (!sumM.matches() && equation.contains("SUM("))
	    throw new SyntaxException(": 'SUM(&varname)' must be the only element of an equation if it is used (line 1)");
	if (!countM.matches() && equation.contains("COUNT("))
	    throw new SyntaxException(": 'COUNT(&varname)' must be the only element of an equation if it is used (line 1)");
	
	while (m.find()){
	    add = true;
	    tempString.add(equation.substring(last, m.start()));
	    last = m.end();
	    String newvar = m.group();
	    index++;
	    tempString.add(newvar);
	    for (String var : variables){
		if (var.equals(newvar))
		    add = false;
	    }
	    if (add){
		variables.add(newvar);
	    }
	}
	
	
	if (last != equation.length() -1)
	    tempString.add(equation.substring(last));
	
	for (int i = 0; i < equation.length(); ++i)
	    System.out.print("=");
	System.out.println();
	
	System.out.println("The input String was:");
	System.out.println(equation);
	for (int i = 0; i < equation.length(); ++i)
	    System.out.print("=");
	System.out.println();
	System.out.println("Variables found:");
	for (int i = 0; i < variables.size(); ++i){
	    System.out.print(variables.get(i) + "\t\t");
	    System.out.println();
	}
    }
}
    
    
