package javakurs.uebung10;

import java.io.IOException;

/**
 * {@link CharFsaTest} is a test class for {@link CharFsa}.
 *
 * @author Bernd Kiefer, DFKI
 * @author Joerg Steffen, DFKI
 * @version $Id$
 */
public final class CharFsaTest {

  /**
   * This contains the path to the dot.exe delivered with Graphviz.
   */
  private static final String DOT =
    "C:/Programme/Graphviz2.26/bin/dot.exe";


  /**
   * This would create a new instance of {@link CharFsaTest}. Not to be used.
   */
  private CharFsaTest() {

    // private constructor to enforce noninstantiability
  }


  /**
   * This creates a .gif image for the given .dot graph
   *
   * @param dotGraph
   *          the path to the .dot graph
   * @throws IOException
   *           if there is an error when running the conversion
   */
  private static void convertToGif(String dotGraph) throws IOException {

    System.out.println("converting " + dotGraph + " ...");
    String command =
      DOT + " -Tgif " + dotGraph + " -o\"" + dotGraph + ".gif\" -Kdot";
    Process process = Runtime.getRuntime().exec(command);
    try {
      process.waitFor();
    } catch (InterruptedException ie) {
      ie.printStackTrace();
    }
  }


  /**
   * This is the main method. It takes as optional arguments regular expressions
   * for which automatons are created.
   *
   * @param args
   *          an array with the arguments
   */
  public static void main(String[] args) {

    // define test regular expressions
    String[] testRegExps = {
      "X*", "AB", "A|B", "X*|Y", "A*BA", "ABA*", "ABAB(X*|Y)*",
      "(AX|BY)*", "([a-c]a[a-c])*"
      };

    if (args.length > 0) {
      testRegExps = args;
    }
    for (int i = 0; i < testRegExps.length; i++) {
      // init automaton
      CharFsa automaton = CharFsa.compileRegex(testRegExps[i]);
      // process regex
      if (automaton != null) {
        try {
          // dot print result automaton
          String automatonFile = "data/uebung10/graphs/" + i + "-0.dot";
          automaton.dotPrint(automatonFile);
          CharFsaTest.convertToGif(automatonFile);
          // determinize automaton
          CharFsa detAutomaton = automaton.determinize();
          // dot print determinized automaton
          String detAutomatonFile = "data/uebung10/graphs/" + i + "-1.det.dot";
          detAutomaton.dotPrint(detAutomatonFile);
          CharFsaTest.convertToGif(detAutomatonFile);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
}
