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