ec5d267bc70fde34932b668ed2faeed91ae69893
[jalview.git] / src / jalview / io / NewickFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ The Jalview Authors
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3
10  * of the License, or (at your option) any later version.
11  *  
12  * Jalview is distributed in the hope that it will be useful, but 
13  * WITHOUT ANY WARRANTY; without even the implied warranty 
14  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
15  * PURPOSE.  See the GNU General Public License for more details.
16  * 
17  * You should have received a copy of the GNU General Public License
18  * along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
19  * The Jalview Authors are detailed in the 'AUTHORS' file.
20  */
21 // NewickFile.java
22 // Tree I/O
23 // http://evolution.genetics.washington.edu/phylip/newick_doc.html
24 // TODO: Implement Basic NHX tag parsing and preservation
25 // TODO: http://evolution.genetics.wustl.edu/eddy/forester/NHX.html
26 // TODO: Extended SequenceNodeI to hold parsed NHX strings
27 package jalview.io;
28
29 import java.util.Locale;
30
31 import jalview.datamodel.SequenceNode;
32 import jalview.util.MessageManager;
33
34 import java.io.BufferedReader;
35 import java.io.File;
36 import java.io.FileReader;
37 import java.io.IOException;
38 import java.util.StringTokenizer;
39
40 import com.stevesoft.pat.Regex;
41
42 /**
43  * Parse a new hanpshire style tree Caveats: NHX files are NOT supported and the
44  * tree distances and topology are unreliable when they are parsed. TODO: on
45  * this: NHX codes are appended in comments beginning with &&NHX. The codes are
46  * given below (from http://www.phylosoft.org/forester/NHX.html): Element Type
47  * Description Corresponding phyloXML element (parent element in parentheses) no
48  * tag string name of this node/clade (MUST BE FIRST, IF ASSIGNED)
49  * <name>(<clade>) : decimal branch length to parent node (MUST BE SECOND, IF
50  * ASSIGNED) <branch_length>(<clade>) :GN= string gene name <name>(<sequence>)
51  * :AC= string sequence accession <accession>(<sequence>) :ND= string node
52  * identifier - if this is being used, it has to be unique within each phylogeny
53  * <node_id>(<clade>) :B= decimal confidence value for parent branch
54  * <confidence>(<clade>) :D= 'T', 'F', or '?' 'T' if this node represents a
55  * duplication event - 'F' if this node represents a speciation event, '?' if
56  * this node represents an unknown event (D= tag should be replaced by Ev= tag)
57  * n/a :Ev=duplications>speciations>gene losses>event type>duplication type int
58  * int int string string event (replaces the =D tag), number of duplication,
59  * speciation, and gene loss events, type of event (transfer, fusion, root,
60  * unknown, other, speciation_duplication_loss, unassigned) <events>(<clade>)
61  * :E= string EC number at this node <annotation>(<sequence>) :Fu= string
62  * function at this node <annotation>(<sequence>)
63  * :DS=protein-length>from>to>support>name>from>... int int int double string
64  * int ... domain structure at this node <domain_architecture>(<sequence>) :S=
65  * string species name of the species/phylum at this node <taxonomy>(<clade>)
66  * :T= integer taxonomy ID of the species/phylum at this node <id>(<taxonomy>)
67  * :W= integer width of parent branch <width>(<clade>) :C=rrr.ggg.bbb
68  * integer.integer.integer color of parent branch <color>(<clade>) :Co= 'Y' or
69  * 'N' collapse this node when drawing the tree (default is not to collapse) n/a
70  * :XB= string custom data associated with a branch <property>(<clade>) :XN=
71  * string custom data associated with a node <property>(<clade>) :O= integer
72  * orthologous to this external node n/a :SN= integer subtree neighbors n/a :SO=
73  * integer super orthologous (no duplications on paths) to this external node
74  * n/a
75  * 
76  * @author Jim Procter
77  * @version $Revision$
78  */
79 public class NewickFile extends FileParse
80 {
81   SequenceNode root;
82
83   private boolean HasBootstrap = false;
84
85   private boolean HasDistances = false;
86
87   private boolean RootHasDistance = false;
88
89   // File IO Flags
90   boolean ReplaceUnderscores = false;
91
92   boolean printRootInfo = true;
93
94   private Regex[] NodeSafeName = new Regex[] {
95       new Regex().perlCode("m/[\\[,:'()]/"), // test for
96       // requiring
97       // quotes
98       new Regex().perlCode("s/'/''/"), // escaping quote
99       // characters
100       new Regex().perlCode("s/\\/w/_/") // unqoted whitespace
101       // transformation
102   };
103
104   char QuoteChar = '\'';
105
106   /**
107    * Creates a new NewickFile object.
108    * 
109    * @param inStr
110    *          DOCUMENT ME!
111    * 
112    * @throws IOException
113    *           DOCUMENT ME!
114    */
115   public NewickFile(String inStr) throws IOException
116   {
117     super(inStr, DataSourceType.PASTE);
118   }
119
120   /**
121    * Creates a new NewickFile object.
122    * 
123    * @param inFile
124    *          DOCUMENT ME!
125    * @param protocol
126    *          DOCUMENT ME!
127    * 
128    * @throws IOException
129    *           DOCUMENT ME!
130    */
131   public NewickFile(String inFile, DataSourceType protocol)
132           throws IOException
133   {
134     super(inFile, protocol);
135   }
136
137   public NewickFile(FileParse source) throws IOException
138   {
139     super(source);
140   }
141
142   /**
143    * Creates a new NewickFile object.
144    * 
145    * @param newtree
146    *          DOCUMENT ME!
147    */
148   public NewickFile(SequenceNode newtree)
149   {
150     root = newtree;
151   }
152
153   /**
154    * Creates a new NewickFile object.
155    * 
156    * @param newtree
157    *          DOCUMENT ME!
158    * @param bootstrap
159    *          DOCUMENT ME!
160    */
161   public NewickFile(SequenceNode newtree, boolean bootstrap)
162   {
163     HasBootstrap = bootstrap;
164     root = newtree;
165   }
166
167   /**
168    * Creates a new NewickFile object.
169    * 
170    * @param newtree
171    *          DOCUMENT ME!
172    * @param bootstrap
173    *          DOCUMENT ME!
174    * @param distances
175    *          DOCUMENT ME!
176    */
177   public NewickFile(SequenceNode newtree, boolean bootstrap,
178           boolean distances)
179   {
180     root = newtree;
181     HasBootstrap = bootstrap;
182     HasDistances = distances;
183   }
184
185   /**
186    * Creates a new NewickFile object.
187    * 
188    * @param newtree
189    *          DOCUMENT ME!
190    * @param bootstrap
191    *          DOCUMENT ME!
192    * @param distances
193    *          DOCUMENT ME!
194    * @param rootdistance
195    *          DOCUMENT ME!
196    */
197   public NewickFile(SequenceNode newtree, boolean bootstrap,
198           boolean distances, boolean rootdistance)
199   {
200     root = newtree;
201     HasBootstrap = bootstrap;
202     HasDistances = distances;
203     RootHasDistance = rootdistance;
204   }
205
206   /**
207    * DOCUMENT ME!
208    * 
209    * @param Error
210    *          DOCUMENT ME!
211    * @param Er
212    *          DOCUMENT ME!
213    * @param r
214    *          DOCUMENT ME!
215    * @param p
216    *          DOCUMENT ME!
217    * @param s
218    *          DOCUMENT ME!
219    * 
220    * @return DOCUMENT ME!
221    */
222   private String ErrorStringrange(String Error, String Er, int r, int p,
223           String s)
224   {
225     return ((Error == null) ? "" : Error) + Er + " at position " + p + " ( "
226             + s.substring(((p - r) < 0) ? 0 : (p - r),
227                     ((p + r) > s.length()) ? s.length() : (p + r))
228             + " )\n";
229   }
230
231   // @tree annotations
232   // These are set automatically by the reader
233   public boolean HasBootstrap()
234   {
235     return HasBootstrap;
236   }
237
238   /**
239    * DOCUMENT ME!
240    * 
241    * @return DOCUMENT ME!
242    */
243   public boolean HasDistances()
244   {
245     return HasDistances;
246   }
247
248   public boolean HasRootDistance()
249   {
250     return RootHasDistance;
251   }
252
253   /**
254    * parse the filesource as a newick file (new hampshire and/or extended)
255    * 
256    * @throws IOException
257    *           with a line number and character position for badly formatted NH
258    *           strings
259    */
260   public void parse() throws IOException
261   {
262     String nf;
263
264     { // fill nf with complete tree file
265
266       StringBuffer file = new StringBuffer();
267
268       while ((nf = nextLine()) != null)
269       {
270         file.append(nf);
271       }
272
273       nf = file.toString();
274     }
275
276     root = new SequenceNode();
277
278     SequenceNode realroot = null;
279     SequenceNode c = root;
280
281     int d = -1;
282     int cp = 0;
283     // int flen = nf.length();
284
285     String Error = null;
286     String nodename = null;
287     String commentString2 = null; // comments after simple node props
288
289     float DefDistance = (float) 0.001; // @param Default distance for a node -
290     // very very small
291     int DefBootstrap = -1; // @param Default bootstrap for a node
292
293     float distance = DefDistance;
294     int bootstrap = DefBootstrap;
295
296     boolean ascending = false; // flag indicating that we are leaving the
297     // current node
298
299     Regex majorsyms = new Regex(
300             "[(\\['),;]");
301
302     int nextcp = 0;
303     int ncp = cp;
304     boolean parsednodename = false;
305     while (majorsyms.searchFrom(nf, cp) && (Error == null))
306     {
307       int fcp = majorsyms.matchedFrom();
308       char schar;
309       switch (schar = nf.charAt(fcp))
310       {
311       case '(':
312
313         // ascending should not be set
314         // New Internal node
315         if (ascending)
316         {
317           Error = ErrorStringrange(Error, "Unexpected '('", 7, fcp, nf);
318
319           continue;
320         }
321         d++;
322
323         if (c.right() == null)
324         {
325           c.setRight(new SequenceNode(null, c, null, DefDistance,
326                   DefBootstrap, false));
327           c = (SequenceNode) c.right();
328         }
329         else
330         {
331           if (c.left() != null)
332           {
333             // Dummy node for polytomy - keeps c.left free for new node
334             SequenceNode tmpn = new SequenceNode(null, c, null, 0, 0, true);
335             tmpn.SetChildren(c.left(), c.right());
336             c.setRight(tmpn);
337           }
338
339           c.setLeft(new SequenceNode(null, c, null, DefDistance,
340                   DefBootstrap, false));
341           c = (SequenceNode) c.left();
342         }
343
344         if (realroot == null)
345         {
346           realroot = c;
347         }
348
349         nodename = null;
350         distance = DefDistance;
351         bootstrap = DefBootstrap;
352         cp = fcp + 1;
353
354         break;
355
356       // Deal with quoted fields
357       case '\'':
358
359         Regex qnodename = new Regex(
360                 "'([^']|'')+'");
361
362         if (qnodename.searchFrom(nf, fcp))
363         {
364           int nl = qnodename.stringMatched().length();
365           nodename = new String(
366                   qnodename.stringMatched().substring(1, nl - 1));
367           // unpack any escaped colons
368           Regex xpandquotes = Regex
369                   .perlCode("s/''/'/");
370           String widernodename = xpandquotes.replaceAll(nodename);
371           nodename = widernodename;
372           // jump to after end of quoted nodename
373           nextcp = fcp + nl + 1;
374           parsednodename = true;
375         }
376         else
377         {
378           Error = ErrorStringrange(Error,
379                   "Unterminated quotes for nodename", 7, fcp, nf);
380         }
381
382         break;
383
384       default:
385         if (schar == ';')
386         {
387           if (d != -1)
388           {
389             Error = ErrorStringrange(Error,
390                     "Wayward semicolon (depth=" + d + ")", 7, fcp, nf);
391           }
392           // cp advanced at the end of default
393         }
394         if (schar == '[')
395         {
396           // node string contains Comment or structured/extended NH format info
397           /*
398            * if ((fcp-cp>1 && nf.substring(cp,fcp).trim().length()>1)) { // will
399            * process in remains System.err.println("skipped text:
400            * '"+nf.substring(cp,fcp)+"'"); }
401            */
402           // verify termination.
403           Regex comment = new Regex(
404                   "]");
405           if (comment.searchFrom(nf, fcp))
406           {
407             // Skip the comment field
408             nextcp = comment.matchedFrom() + 1;
409             warningMessage = "Tree file contained comments which may confuse input algorithm.";
410             break;
411
412             // cp advanced at the end of default to nextcp, ncp is unchanged so
413             // any node info can be read.
414           }
415           else
416           {
417             Error = ErrorStringrange(Error, "Unterminated comment", 3, fcp,
418                     nf);
419           }
420         }
421         // Parse simpler field strings
422         String fstring = nf.substring(ncp, fcp);
423         // remove any comments before we parse the node info
424         // TODO: test newick file with quoted square brackets in node name (is
425         // this allowed?)
426         while (fstring.indexOf(']') > -1)
427         {
428           int cstart = fstring.indexOf('[');
429           int cend = fstring.indexOf(']');
430           commentString2 = fstring.substring(cstart + 1, cend);
431           fstring = fstring.substring(0, cstart)
432                   + fstring.substring(cend + 1);
433
434         }
435         Regex uqnodename = new Regex(
436                 "\\b([^' :;\\](),]+)");
437         Regex nbootstrap = new Regex(
438                 "\\s*([0-9+]+)\\s*:");
439         Regex ndist = new Regex(
440                 ":([-0-9Ee.+]+)");
441
442         if (!parsednodename && uqnodename.search(fstring)
443                 && ((uqnodename.matchedFrom(1) == 0) || (fstring
444                         .charAt(uqnodename.matchedFrom(1) - 1) != ':'))) // JBPNote
445         // HACK!
446         {
447           if (nodename == null)
448           {
449             if (ReplaceUnderscores)
450             {
451               nodename = uqnodename.stringMatched(1).replace('_', ' ');
452             }
453             else
454             {
455               nodename = uqnodename.stringMatched(1);
456             }
457           }
458           else
459           {
460             Error = ErrorStringrange(Error,
461                     "File has broken algorithm - overwritten nodename", 10,
462                     fcp, nf);
463           }
464         }
465         // get comment bootstraps
466
467         if (nbootstrap.search(fstring))
468         {
469           if (nbootstrap.stringMatched(1)
470                   .equals(uqnodename.stringMatched(1)))
471           {
472             nodename = null; // no nodename here.
473           }
474           if (nodename == null || nodename.length() == 0
475                   || nbootstrap.matchedFrom(1) > (uqnodename.matchedFrom(1)
476                           + uqnodename.stringMatched().length()))
477           {
478             try
479             {
480               bootstrap = (Integer.valueOf(nbootstrap.stringMatched(1)))
481                       .intValue();
482               HasBootstrap = true;
483             } catch (Exception e)
484             {
485               Error = ErrorStringrange(Error, "Can't parse bootstrap value",
486                       4, ncp + nbootstrap.matchedFrom(), nf);
487             }
488           }
489         }
490
491         boolean nodehasdistance = false;
492
493         if (ndist.search(fstring))
494         {
495           try
496           {
497             distance = (Float.valueOf(ndist.stringMatched(1))).floatValue();
498             HasDistances = true;
499             nodehasdistance = true;
500           } catch (Exception e)
501           {
502             Error = ErrorStringrange(Error,
503                     "Can't parse node distance value", 7,
504                     ncp + ndist.matchedFrom(), nf);
505           }
506         }
507
508         if (ascending)
509         {
510           // Write node info here
511           c.setName(nodename);
512           // Trees without distances still need a render distance
513           c.dist = (HasDistances) ? distance : DefDistance;
514           // be consistent for internal bootstrap defaults too
515           c.setBootstrap((HasBootstrap) ? bootstrap : DefBootstrap);
516           if (c == realroot)
517           {
518             RootHasDistance = nodehasdistance; // JBPNote This is really
519             // UGLY!!! Ensure root node gets
520             // its given distance
521           }
522           parseNHXNodeProps(c, commentString2);
523           commentString2 = null;
524         }
525         else
526         {
527           // Find a place to put the leaf
528           SequenceNode newnode = new SequenceNode(null, c, nodename,
529                   (HasDistances) ? distance : DefDistance,
530                   (HasBootstrap) ? bootstrap : DefBootstrap, false);
531           parseNHXNodeProps(c, commentString2);
532           commentString2 = null;
533
534           if (c.right() == null)
535           {
536             c.setRight(newnode);
537           }
538           else
539           {
540             if (c.left() == null)
541             {
542               c.setLeft(newnode);
543             }
544             else
545             {
546               // Insert a dummy node for polytomy
547               // dummy nodes have distances
548               SequenceNode newdummy = new SequenceNode(null, c, null,
549                       (HasDistances ? 0 : DefDistance), 0, true);
550               newdummy.SetChildren(c.left(), newnode);
551               c.setLeft(newdummy);
552             }
553           }
554         }
555
556         if (ascending)
557         {
558           // move back up the tree from preceding closure
559           c = c.AscendTree();
560
561           if ((d > -1) && (c == null))
562           {
563             Error = ErrorStringrange(Error,
564                     "File broke algorithm: Lost place in tree (is there an extra ')' ?)",
565                     7, fcp, nf);
566           }
567         }
568
569         if (nf.charAt(fcp) == ')')
570         {
571           d--;
572           ascending = true;
573         }
574         else
575         {
576           if (nf.charAt(fcp) == ',')
577           {
578             if (ascending)
579             {
580               ascending = false;
581             }
582             else
583             {
584               // Just advance focus, if we need to
585               if ((c.left() != null) && (!c.left().isLeaf()))
586               {
587                 c = (SequenceNode) c.left();
588               }
589             }
590           }
591         }
592
593         // Reset new node properties to obvious fakes
594         nodename = null;
595         distance = DefDistance;
596         bootstrap = DefBootstrap;
597         commentString2 = null;
598         parsednodename = false;
599       }
600       if (nextcp == 0)
601       {
602         ncp = cp = fcp + 1;
603       }
604       else
605       {
606         cp = nextcp;
607         nextcp = 0;
608       }
609     }
610
611     if (Error != null)
612     {
613       throw (new IOException(
614               MessageManager.formatMessage("exception.newfile", new String[]
615               { Error.toString() })));
616     }
617     if (root == null)
618     {
619       throw (new IOException(
620               MessageManager.formatMessage("exception.newfile", new String[]
621               { MessageManager.getString("label.no_tree_read_in") })));
622     }
623     // THe next line is failing for topali trees - not sure why yet. if
624     // (root.right()!=null && root.isDummy())
625     root = (SequenceNode) root.right().detach(); // remove the imaginary root.
626
627     if (!RootHasDistance)
628     {
629       root.dist = (HasDistances) ? 0 : DefDistance;
630     }
631   }
632
633   /**
634    * parse NHX codes in comment strings and update NewickFile state flags for
635    * distances and bootstraps, and add any additional properties onto the node.
636    * 
637    * @param c
638    * @param commentString
639    * @param commentString2
640    */
641   private void parseNHXNodeProps(SequenceNode c, String commentString)
642   {
643     // TODO: store raw comment on the sequenceNode so it can be recovered when
644     // tree is output
645     if (commentString != null && commentString.startsWith("&&NHX"))
646     {
647       StringTokenizer st = new StringTokenizer(commentString.substring(5),
648               ":");
649       while (st.hasMoreTokens())
650       {
651         String tok = st.nextToken();
652         int colpos = tok.indexOf("=");
653
654         if (colpos > -1)
655         {
656           String code = tok.substring(0, colpos);
657           String value = tok.substring(colpos + 1);
658           try
659           {
660             // parse out code/value pairs
661             if (code.toLowerCase(Locale.ROOT).equals("b"))
662             {
663               int v = -1;
664               Float iv = Float.valueOf(value);
665               v = iv.intValue(); // jalview only does integer bootstraps
666               // currently
667               c.setBootstrap(v);
668               HasBootstrap = true;
669             }
670             // more codes here.
671           } catch (Exception e)
672           {
673             System.err.println(
674                     "Couldn't parse code '" + code + "' = '" + value + "'");
675             e.printStackTrace(System.err);
676           }
677         }
678       }
679     }
680
681   }
682
683   /**
684    * DOCUMENT ME!
685    * 
686    * @return DOCUMENT ME!
687    */
688   public SequenceNode getTree()
689   {
690     return root;
691   }
692
693   /**
694    * Generate a newick format tree according to internal flags for bootstraps,
695    * distances and root distances.
696    * 
697    * @return new hampshire tree in a single line
698    */
699   public String print()
700   {
701     synchronized (this)
702     {
703       StringBuffer tf = new StringBuffer();
704       print(tf, root);
705
706       return (tf.append(";").toString());
707     }
708   }
709
710   /**
711    * 
712    * 
713    * Generate a newick format tree according to internal flags for distances and
714    * root distances and user specificied writing of bootstraps.
715    * 
716    * @param withbootstraps
717    *          controls if bootstrap values are explicitly written.
718    * 
719    * @return new hampshire tree in a single line
720    */
721   public String print(boolean withbootstraps)
722   {
723     synchronized (this)
724     {
725       boolean boots = this.HasBootstrap;
726       this.HasBootstrap = withbootstraps;
727
728       String rv = print();
729       this.HasBootstrap = boots;
730
731       return rv;
732     }
733   }
734
735   /**
736    * 
737    * Generate newick format tree according to internal flags for writing root
738    * node distances.
739    * 
740    * @param withbootstraps
741    *          explicitly write bootstrap values
742    * @param withdists
743    *          explicitly write distances
744    * 
745    * @return new hampshire tree in a single line
746    */
747   public String print(boolean withbootstraps, boolean withdists)
748   {
749     synchronized (this)
750     {
751       boolean dists = this.HasDistances;
752       this.HasDistances = withdists;
753
754       String rv = print(withbootstraps);
755       this.HasDistances = dists;
756
757       return rv;
758     }
759   }
760
761   /**
762    * Generate newick format tree according to user specified flags
763    * 
764    * @param withbootstraps
765    *          explicitly write bootstrap values
766    * @param withdists
767    *          explicitly write distances
768    * @param printRootInfo
769    *          explicitly write root distance
770    * 
771    * @return new hampshire tree in a single line
772    */
773   public String print(boolean withbootstraps, boolean withdists,
774           boolean printRootInfo)
775   {
776     synchronized (this)
777     {
778       boolean rootinfo = printRootInfo;
779       this.printRootInfo = printRootInfo;
780
781       String rv = print(withbootstraps, withdists);
782       this.printRootInfo = rootinfo;
783
784       return rv;
785     }
786   }
787
788   /**
789    * DOCUMENT ME!
790    * 
791    * @return DOCUMENT ME!
792    */
793   char getQuoteChar()
794   {
795     return QuoteChar;
796   }
797
798   /**
799    * DOCUMENT ME!
800    * 
801    * @param c
802    *          DOCUMENT ME!
803    * 
804    * @return DOCUMENT ME!
805    */
806   char setQuoteChar(char c)
807   {
808     char old = QuoteChar;
809     QuoteChar = c;
810
811     return old;
812   }
813
814   /**
815    * DOCUMENT ME!
816    * 
817    * @param name
818    *          DOCUMENT ME!
819    * 
820    * @return DOCUMENT ME!
821    */
822   private String nodeName(String name)
823   {
824     if (NodeSafeName[0].search(name))
825     {
826       return QuoteChar + NodeSafeName[1].replaceAll(name) + QuoteChar;
827     }
828     else
829     {
830       return NodeSafeName[2].replaceAll(name);
831     }
832   }
833
834   /**
835    * DOCUMENT ME!
836    * 
837    * @param c
838    *          DOCUMENT ME!
839    * 
840    * @return DOCUMENT ME!
841    */
842   private String printNodeField(SequenceNode c)
843   {
844     return ((c.getName() == null) ? "" : nodeName(c.getName()))
845             + ((HasBootstrap) ? ((c.getBootstrap() > -1)
846                     ? ((c.getName() != null ? " " : "") + c.getBootstrap())
847                     : "") : "")
848             + ((HasDistances) ? (":" + c.dist) : "");
849   }
850
851   /**
852    * DOCUMENT ME!
853    * 
854    * @param root
855    *          DOCUMENT ME!
856    * 
857    * @return DOCUMENT ME!
858    */
859   private String printRootField(SequenceNode root)
860   {
861     return (printRootInfo)
862             ? (((root.getName() == null) ? "" : nodeName(root.getName()))
863                     + ((HasBootstrap)
864                             ? ((root.getBootstrap() > -1)
865                                     ? ((root.getName() != null ? " " : "")
866                                             + +root.getBootstrap())
867                                     : "")
868                             : "")
869                     + ((RootHasDistance) ? (":" + root.dist) : ""))
870             : "";
871   }
872
873   // Non recursive call deals with root node properties
874   public void print(StringBuffer tf, SequenceNode root)
875   {
876     if (root != null)
877     {
878       if (root.isLeaf() && printRootInfo)
879       {
880         tf.append(printRootField(root));
881       }
882       else
883       {
884         if (root.isDummy())
885         {
886           _print(tf, (SequenceNode) root.right());
887           _print(tf, (SequenceNode) root.left());
888         }
889         else
890         {
891           tf.append("(");
892           _print(tf, (SequenceNode) root.right());
893
894           if (root.left() != null)
895           {
896             tf.append(",");
897           }
898
899           _print(tf, (SequenceNode) root.left());
900           tf.append(")" + printRootField(root));
901         }
902       }
903     }
904   }
905
906   // Recursive call for non-root nodes
907   public void _print(StringBuffer tf, SequenceNode c)
908   {
909     if (c != null)
910     {
911       if (c.isLeaf())
912       {
913         tf.append(printNodeField(c));
914       }
915       else
916       {
917         if (c.isDummy())
918         {
919           _print(tf, (SequenceNode) c.left());
920           if (c.left() != null)
921           {
922             tf.append(",");
923           }
924           _print(tf, (SequenceNode) c.right());
925         }
926         else
927         {
928           tf.append("(");
929           _print(tf, (SequenceNode) c.right());
930
931           if (c.left() != null)
932           {
933             tf.append(",");
934           }
935
936           _print(tf, (SequenceNode) c.left());
937           tf.append(")" + printNodeField(c));
938         }
939       }
940     }
941   }
942
943   /**
944    * 
945    * @param args
946    * @j2sIgnore
947    */
948   public static void main(String[] args)
949   {
950     try
951     {
952       if (args == null || args.length != 1)
953       {
954         System.err.println(
955                 "Takes one argument - file name of a newick tree file.");
956         System.exit(0);
957       }
958
959       File fn = new File(args[0]);
960
961       StringBuffer newickfile = new StringBuffer();
962       BufferedReader treefile = new BufferedReader(new FileReader(fn));
963       String l;
964
965       while ((l = treefile.readLine()) != null)
966       {
967         newickfile.append(l);
968       }
969
970       treefile.close();
971       System.out.println("Read file :\n");
972
973       NewickFile trf = new NewickFile(args[0], DataSourceType.FILE);
974       trf.parse();
975       System.out.println("Original file :\n");
976
977       Regex nonl = new Regex("\n+", "");
978       System.out.println(nonl.replaceAll(newickfile.toString()) + "\n");
979
980       System.out.println("Parsed file.\n");
981       System.out.println("Default output type for original input.\n");
982       System.out.println(trf.print());
983       System.out.println("Without bootstraps.\n");
984       System.out.println(trf.print(false));
985       System.out.println("Without distances.\n");
986       System.out.println(trf.print(true, false));
987       System.out.println("Without bootstraps but with distanecs.\n");
988       System.out.println(trf.print(false, true));
989       System.out.println("Without bootstraps or distanecs.\n");
990       System.out.println(trf.print(false, false));
991       System.out.println("With bootstraps and with distances.\n");
992       System.out.println(trf.print(true, true));
993     } catch (java.io.IOException e)
994     {
995       System.err.println("Exception\n" + e);
996       e.printStackTrace();
997     }
998   }
999 }