/* Umer: I modified the program from http://www.biostars.org/p/52895/ that Pierre Lindenbaum wrote, and he be given due credit not me. */ import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.TreeMap; import java.util.regex.Pattern; public class Path2Newick { private static class Node { Map children=new TreeMap(); void fill(String tokens[],int index) { Node c=children.get(tokens[index]); if(c==null) { c=new Node(); this.children.put(tokens[index],c); } if(index+1< tokens.length) c.fill(tokens, index+1); } void printChildren() { boolean first=true; System.out.print("("); for(String childName:this.children.keySet()) { if(!first) System.out.print(","); first=false; Node c=this.children.get(childName); c.print(childName); } System.out.print(")"); } void print(String myName) { if(!this.children.isEmpty()) { printChildren(); } System.out.print(myName); } } private Node root=new Node(); private void parse(BufferedReader in) throws IOException { Pattern semicolon=Pattern.compile("[;]"); String line; while((line=in.readLine())!=null) { if(line.isEmpty()) continue; String tokens[]=semicolon.split(line); root.fill(tokens, 0); } } private void print() { this.root.printChildren(); System.out.println(";"); } public static void main(String[] args) throws IOException { Path2Newick app=new Path2Newick(); app.parse(new BufferedReader(new InputStreamReader(System.in))); app.print(); } }