import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.junit.Test;
import org.polymodel.x10p.Program;
import org.polymodel.x10p.X10pParser;
import org.polymodel.x10p.analysis.DFAOutput;
import org.polymodel.x10p.analysis.DFAOutput.VERBOSITY;
import org.polymodel.x10p.analysis.DataFlowAnalysis;
import org.polymodel.x10p.util.X10pUnparser;


public class JGFTest {
	private static final String JGF_ROOT = "./x10src/JGF/";
	private static final String JGF_RESULTS = "./dfa-results/JGF/";

	static {
		DataFlowAnalysis.DEBUG = false;
	}
	
	@Test
	public void SOR() {
		test("SOR.x10p");
	}
	@Test
	public void sor1() {
		test("sor1.x10p");
	}
	@Test
	public void CRYPT() {
		test("CRYPT.x10p");
	}
	@Test
	public void crypt1() {
		DataFlowAnalysis.USE_JNIISL = true;
		test("crypt1.x10p");
	}
	@Test
	public void crypt2() {
		DataFlowAnalysis.USE_JNIISL = true;
		test("crypt2.x10p");
	}
	@Test
	public void SERIES() {
		test("SERIES.x10p");
	}
	@Test
	public void series1() {
		test("series1.x10p");
	}
	@Test
	public void lufact1() {
		test("lufact1.x10p");
	}
	@Test
	public void moldyn1() {
		test("moldyn1.x10p");
	}
	@Test
	public void moldyn2() {
		test("moldyn2.x10p");
	}
	@Test
	public void moldyn3() {
		test("moldyn3.x10p");
	}
	@Test
	public void moldyn4() {
		test("moldyn4.x10p");
	}
	@Test
	public void moldyn5() {
		test("moldyn5.x10p");
	}

	private void test(String file) {
		System.out.println(file +":\n");
		try {
			Program prog = X10pParser.loadModel(JGF_ROOT+file);
			System.out.println(X10pUnparser.unparseWithTimeStamps(prog));
			long start = System.currentTimeMillis();
			DFAOutput output = DataFlowAnalysis.analyze(prog);
			long end = System.currentTimeMillis();
			System.out.println(output);
			System.out.println(output.printDFAResults());
			
			StringBuffer content = new StringBuffer();
			content.append(X10pUnparser.unparse(prog));
			content.append("\n/*\n");
			content.append(output.toString(VERBOSITY.DEFAULT));
			content.append(output.printDFAResults());
			content.append("*/\n");
			
			writeToFile(JGF_RESULTS+file, content.toString());
			
			System.out.println("Analysis Time: " + (end - start) * 0.001);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private void writeToFile(String filename, String content) {
		try {
			FileWriter fw = new FileWriter(new File(filename));
			fw.write(content);
			fw.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
