import java.io.*;
import java.util.*;
import org.biojava.bio.seq.io.ParseException;
import org.biojavax.bio.phylo.io.nexus.*;
import org.jgrapht.*;
import org.jgrapht.graph.*;

public class Test {

    static String topNode;

    static TreesBlock getTreeNode(NexusFile nexus) {
        Iterator it = nexus.blockIterator();
        NexusBlock block;
        while(it.hasNext()) {
                block = (NexusBlock)it.next();
            if (block.getBlockName().equals("TREES")) {
                        return (TreesBlock)block;
                }
            }
            return null;
    }

    static void printTrees(NexusFile nexus) {
            TreesBlock node = getTreeNode(nexus);
            Map trees = node.getTrees();
            Set keys = trees.keySet();
            System.out.println("Trees:");
            for (Object obj : keys) {
                System.out.println(obj);
            }
    }

    static WeightedGraph<String, DefaultWeightedEdge> getTree(NexusFile nexus, String name)
    throws ParseException {
        TreesBlock node = getTreeNode(nexus);
        WeightedGraph<String, DefaultWeightedEdge> graph = node.getTreeAsWeightedJGraphT(name);
        topNode = node.getTopNode();
        return graph;
    }

    static void dump(WeightedGraph<String, DefaultWeightedEdge> graph,
            String parent, String node, String depth) {
        Set<String> verts = graph.vertexSet();
        String vertex = "";
        for (String candidate : verts) {
            if (candidate.equals(node)) {
                vertex = candidate;
                break;
            }
        }
        System.out.print (depth + vertex);
        if (parent != null) {
            System.out.print (": " + graph.getEdgeWeight(graph.getEdge(parent, vertex)));
        }
        System.out.println();
        for(DefaultWeightedEdge e: graph.edgesOf(vertex)){
            if (graph.getEdgeSource(e).equals(node)) {
                dump(graph, vertex, graph.getEdgeTarget(e), "  "+ depth);
            }
        }
    } 


    public static void main(String[] args) throws Exception {
        String file = args[0];
        String tree = args[1];
        System.out.println("Will process file " + file + " tree " + tree);

        NexusFileBuilder builder = new NexusFileBuilder();
        NexusFileFormat.parseFile(builder, new File(file));
        NexusFile nexus = builder.getNexusFile();

        printTrees(nexus);
        dump(getTree(nexus, tree), null, topNode, "");
    }
}
