// File: GraphViewer.java
// Copyright (C) 2006 Gregory D. Weber

import java.io.*; // for FileWriter, IOException, InputStreamReader

public class GraphViewer {

//     public static void view (Graphable obj) {

// 	// Ask the object for its DOT language representation
// 	String dotRepr = obj.toDot();

    public static void view (String dotRepr) {
	// Precondition: dotRepr is the dot program of the object
	// that we want to graph.

	// Write it to a file
	try {
	    FileWriter dotfile = new FileWriter("tmp.dot");
	    dotfile.write(dotRepr);
	    dotfile.close();

	    // Display the file
	    ProcessBuilder pb1 =
 		new ProcessBuilder("/usr/bin/dot", "-Tpng", 
				   "-otmp.png", "tmp.dot");
						   
	    boolean okay = run(pb1);

	    if (okay) {
		ProcessBuilder pb2 =
		    new ProcessBuilder("/usr/bin/display",  "tmp.png");
		okay = run(pb2);
	    }
	}

	catch (IOException e) {
	    System.err.println("GraphViewer.view: I/O error.");
	}
	// We won't clean up the file	
    }

    private static boolean run (ProcessBuilder pb) {
	pb.redirectErrorStream(true);
	try {
	    Process p1 = pb.start();
	    InputStreamReader pin = 
		new InputStreamReader(p1.getInputStream());
	    int chr = pin.read();
	    // System.out.println("SUBPROCESS OUTPUT:");
	    while (chr != -1) {
		System.out.write(chr);
		chr = pin.read();
	    }
	    pin.close();
	    try {
		int retcode = p1.waitFor();
		if (retcode != 0)
		    System.out.println("Subprocess return code: " + retcode);
		return (retcode == 0);
	    }
	    catch (InterruptedException e) {
		System.err.println("Interrupted!");
		return false;
	    }
	}
	catch (IOException e) {
	    System.err.println("I/O exception.");
	    return false;
	}
    }

}

	
