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