8e1730a2da8facb93aa2f252e9e50343c4cba6e7
[jalview.git] / src / jalview / io / AnnotationFile.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 package jalview.io;
22
23 import jalview.analysis.Conservation;
24 import jalview.api.AlignViewportI;
25 import jalview.datamodel.AlignmentAnnotation;
26 import jalview.datamodel.AlignmentI;
27 import jalview.datamodel.Annotation;
28 import jalview.datamodel.ColumnSelection;
29 import jalview.datamodel.GraphLine;
30 import jalview.datamodel.HiddenSequences;
31 import jalview.datamodel.PDBEntry;
32 import jalview.datamodel.PDBEntry.Type;
33 import jalview.datamodel.SequenceGroup;
34 import jalview.datamodel.SequenceI;
35 import jalview.gui.Desktop;
36 import jalview.schemes.ColourSchemeI;
37 import jalview.schemes.ColourSchemeProperty;
38 import jalview.structure.StructureSelectionManager;
39 import jalview.util.ColorUtils;
40
41 import java.awt.Color;
42 import java.io.BufferedReader;
43 import java.io.File;
44 import java.io.FileReader;
45 import java.io.InputStreamReader;
46 import java.io.StringReader;
47 import java.net.URL;
48 import java.util.ArrayList;
49 import java.util.BitSet;
50 import java.util.Enumeration;
51 import java.util.Hashtable;
52 import java.util.List;
53 import java.util.Map;
54 import java.util.StringTokenizer;
55 import java.util.Vector;
56
57 public class AnnotationFile
58 {
59   StringBuffer text;
60
61   SequenceI refSeq = null;
62
63   String refSeqId = null;
64
65   String[] StructModelHeader = null;
66
67   long nlinesread = 0;
68
69   String lastread = "";
70
71   /**
72    * used for resolving absolute references to resources relative to
73    * annotationFile location
74    */
75   String baseUri = "";
76
77   private static String GRAPHLINE = "GRAPHLINE", COMBINE = "COMBINE",
78           STRUCTMODEL = "STRUCTMODEL",
79           HEADER_STRUCT_MODEL = "HEADER_STRUCT_MODEL";
80
81   public AnnotationFile()
82   {
83     init();
84   }
85
86   /**
87    * character used to write newlines
88    */
89   protected String newline = System.getProperty("line.separator");
90
91   /**
92    * set new line string and reset the output buffer
93    * 
94    * @param nl
95    */
96   public void setNewlineString(String nl)
97   {
98     newline = nl;
99     init();
100   }
101
102   public String getNewlineString()
103   {
104     return newline;
105   }
106
107
108   private void init()
109   {
110     text = new StringBuffer("JALVIEW_ANNOTATION" + newline + "# Created: "
111             + new java.util.Date() + newline + newline);
112     refSeq = null;
113     refSeqId = null;
114   }
115
116   /**
117    * convenience method for pre-2.9 annotation files which have no view, hidden
118    * columns or hidden row keywords.
119    * 
120    * @param annotations
121    * @param list
122    * @param properties
123    * @return annotation file as a string.
124    */
125   public String printAnnotations(AlignmentAnnotation[] annotations,
126           List<SequenceGroup> list, Hashtable properties)
127   {
128     return printAnnotations(annotations, list, properties, null, null, null);
129
130   }
131
132   /**
133    * hold all the information about a particular view definition read from or
134    * written out in an annotations file.
135    */
136   public class ViewDef
137   {
138     public String viewname;
139
140     public HiddenSequences hidseqs;
141
142     public ColumnSelection hiddencols;
143
144     public Vector visibleGroups;
145
146     public Hashtable hiddenRepSeqs;
147
148     public ViewDef(String viewname, HiddenSequences hidseqs,
149             ColumnSelection hiddencols, Hashtable hiddenRepSeqs)
150     {
151       this.viewname = viewname;
152       this.hidseqs = hidseqs;
153       this.hiddencols = hiddencols;
154       this.hiddenRepSeqs = hiddenRepSeqs;
155     }
156   }
157
158   /**
159    * Prepare an annotation file given a set of annotations, groups, alignment
160    * properties and views.
161    * 
162    * @param annotations
163    * @param list
164    * @param properties
165    * @param views
166    * @return annotation file
167    */
168   public String printAnnotations(AlignmentAnnotation[] annotations,
169           List<SequenceGroup> list, Hashtable properties,
170           ColumnSelection cs, AlignmentI al, ViewDef view)
171   {
172     if (view != null)
173     {
174       if (view.viewname != null)
175       {
176         text.append("VIEW_DEF\t" + view.viewname + "\n");
177       }
178       if (list == null)
179       {
180         list = view.visibleGroups;
181       }
182       if (cs == null)
183       {
184         cs = view.hiddencols;
185       }
186       if (al == null)
187       {
188         // add hidden rep sequences.
189       }
190     }
191     // first target - store and restore all settings for a view.
192     if (al != null && al.hasSeqrep())
193     {
194       text.append("VIEW_SETREF\t" + al.getSeqrep().getName() + "\n");
195     }
196     if (cs != null && cs.hasHiddenColumns())
197     {
198       text.append("VIEW_HIDECOLS\t");
199       List<int[]> hc = cs.getHiddenColumns();
200       boolean comma = false;
201       for (int[] r : hc)
202       {
203         if (!comma)
204         {
205           comma = true;
206         }
207         else
208         {
209           text.append(",");
210         }
211         text.append(r[0]);
212         text.append("-");
213         text.append(r[1]);
214       }
215       text.append("\n");
216     }
217     // TODO: allow efficient recovery of annotation data shown in several
218     // different views
219     if (annotations != null)
220     {
221       boolean oneColour = true;
222       AlignmentAnnotation row;
223       String comma;
224       SequenceI refSeq = null;
225       SequenceGroup refGroup = null;
226
227       StringBuffer colours = new StringBuffer();
228       StringBuffer graphLine = new StringBuffer();
229       StringBuffer rowprops = new StringBuffer();
230       Hashtable<Integer, String> graphGroup = new Hashtable<Integer, String>();
231       Hashtable<Integer, Object[]> graphGroup_refs = new Hashtable<Integer, Object[]>();
232       BitSet graphGroupSeen = new BitSet();
233
234       java.awt.Color color;
235
236       for (int i = 0; i < annotations.length; i++)
237       {
238         row = annotations[i];
239
240         if (!row.visible
241                 && !row.hasScore()
242                 && !(row.graphGroup > -1 && graphGroupSeen
243                         .get(row.graphGroup)))
244         {
245           continue;
246         }
247
248         color = null;
249         oneColour = true;
250
251         // mark any sequence references for the row
252         writeSequence_Ref(refSeq, row.sequenceRef);
253         refSeq = row.sequenceRef;
254         // mark any group references for the row
255         writeGroup_Ref(refGroup, row.groupRef);
256         refGroup = row.groupRef;
257
258         boolean hasGlyphs = row.hasIcons, hasLabels = row.hasText, hasValues = row.hasScore, hasText = false;
259         // lookahead to check what the annotation row object actually contains.
260         for (int j = 0; row.annotations != null
261                 && j < row.annotations.length
262                 && (!hasGlyphs || !hasLabels || !hasValues); j++)
263         {
264           if (row.annotations[j] != null)
265           {
266             hasLabels |= (row.annotations[j].displayCharacter != null
267                     && row.annotations[j].displayCharacter.length() > 0 && !row.annotations[j].displayCharacter
268                     .equals(" "));
269             hasGlyphs |= (row.annotations[j].secondaryStructure != 0 && row.annotations[j].secondaryStructure != ' ');
270             hasValues |= (!Float.isNaN(row.annotations[j].value)); // NaNs can't
271             // be
272             // rendered..
273             hasText |= (row.annotations[j].description != null && row.annotations[j].description
274                     .length() > 0);
275           }
276         }
277
278         if (row.graph == AlignmentAnnotation.NO_GRAPH)
279         {
280           text.append("NO_GRAPH\t");
281           hasValues = false; // only secondary structure
282           // hasLabels = false; // and annotation description string.
283         }
284         else
285         {
286           if (row.graph == AlignmentAnnotation.BAR_GRAPH)
287           {
288             text.append("BAR_GRAPH\t");
289             hasGlyphs = false; // no secondary structure
290
291           }
292           else if (row.graph == AlignmentAnnotation.LINE_GRAPH)
293           {
294             hasGlyphs = false; // no secondary structure
295             text.append("LINE_GRAPH\t");
296           }
297
298           if (row.getThreshold() != null)
299           {
300             graphLine.append("GRAPHLINE\t");
301             graphLine.append(row.label);
302             graphLine.append("\t");
303             graphLine.append(row.getThreshold().value);
304             graphLine.append("\t");
305             graphLine.append(row.getThreshold().label);
306             graphLine.append("\t");
307             graphLine.append(jalview.util.Format.getHexString(row
308                     .getThreshold().colour));
309             graphLine.append(newline);
310           }
311
312           if (row.graphGroup > -1)
313           {
314             graphGroupSeen.set(row.graphGroup);
315             Integer key = new Integer(row.graphGroup);
316             if (graphGroup.containsKey(key))
317             {
318               graphGroup.put(key, graphGroup.get(key) + "\t" + row.label);
319
320             }
321             else
322             {
323               graphGroup_refs.put(key, new Object[] { refSeq, refGroup });
324               graphGroup.put(key, row.label);
325             }
326           }
327         }
328
329         text.append(row.label + "\t");
330         if (row.description != null)
331         {
332           text.append(row.description + "\t");
333         }
334         for (int j = 0; row.annotations != null
335                 && j < row.annotations.length; j++)
336         {
337           if (refSeq != null
338                   && jalview.util.Comparison.isGap(refSeq.getCharAt(j)))
339           {
340             continue;
341           }
342
343           if (row.annotations[j] != null)
344           {
345             comma = "";
346             if (hasGlyphs) // could be also hasGlyphs || ...
347             {
348
349               text.append(comma);
350               if (row.annotations[j].secondaryStructure != ' ')
351               {
352                 // only write out the field if its not whitespace.
353                 text.append(row.annotations[j].secondaryStructure);
354               }
355               comma = ",";
356             }
357             if (hasValues)
358             {
359               if (!Float.isNaN(row.annotations[j].value))
360               {
361                 text.append(comma + row.annotations[j].value);
362               }
363               else
364               {
365                 // System.err.println("Skipping NaN - not valid value.");
366                 text.append(comma + 0f);// row.annotations[j].value);
367               }
368               comma = ",";
369             }
370             if (hasLabels)
371             {
372               // TODO: labels are emitted after values for bar graphs.
373               if // empty labels are allowed, so
374               (row.annotations[j].displayCharacter != null
375                       && row.annotations[j].displayCharacter.length() > 0
376                       && !row.annotations[j].displayCharacter.equals(" "))
377               {
378                 text.append(comma + row.annotations[j].displayCharacter);
379                 comma = ",";
380               }
381             }
382             if (hasText)
383             {
384               if (row.annotations[j].description != null
385                       && row.annotations[j].description.length() > 0
386                       && !row.annotations[j].description
387                               .equals(row.annotations[j].displayCharacter))
388               {
389                 text.append(comma + row.annotations[j].description);
390                 comma = ",";
391               }
392             }
393             if (color != null && !color.equals(row.annotations[j].colour))
394             {
395               oneColour = false;
396             }
397
398             color = row.annotations[j].colour;
399
400             if (row.annotations[j].colour != null
401                     && row.annotations[j].colour != java.awt.Color.black)
402             {
403               text.append(comma
404                       + "["
405                       + jalview.util.Format
406                               .getHexString(row.annotations[j].colour)
407                       + "]");
408               comma = ",";
409             }
410           }
411           text.append("|");
412         }
413
414         if (row.hasScore())
415         {
416           text.append("\t" + row.score);
417         }
418
419         text.append(newline);
420
421         if (color != null && color != java.awt.Color.black && oneColour)
422         {
423           colours.append("COLOUR\t");
424           colours.append(row.label);
425           colours.append("\t");
426           colours.append(jalview.util.Format.getHexString(color));
427           colours.append(newline);
428         }
429         if (row.scaleColLabel || row.showAllColLabels
430                 || row.centreColLabels)
431         {
432           rowprops.append("ROWPROPERTIES\t");
433           rowprops.append(row.label);
434           rowprops.append("\tscaletofit=");
435           rowprops.append(row.scaleColLabel);
436           rowprops.append("\tshowalllabs=");
437           rowprops.append(row.showAllColLabels);
438           rowprops.append("\tcentrelabs=");
439           rowprops.append(row.centreColLabels);
440           rowprops.append(newline);
441         }
442         if (graphLine.length() > 0)
443         {
444           text.append(graphLine.toString());
445           graphLine.setLength(0);
446         }
447       }
448
449       text.append(newline);
450
451       text.append(colours.toString());
452       if (graphGroup.size() > 0)
453       {
454         SequenceI oldRefSeq = refSeq;
455         SequenceGroup oldRefGroup = refGroup;
456         for (Map.Entry<Integer, String> combine_statement : graphGroup
457                 .entrySet())
458         {
459           Object[] seqRefAndGroup = graphGroup_refs.get(combine_statement
460                   .getKey());
461
462           writeSequence_Ref(refSeq, (SequenceI) seqRefAndGroup[0]);
463           refSeq = (SequenceI) seqRefAndGroup[0];
464
465           writeGroup_Ref(refGroup, (SequenceGroup) seqRefAndGroup[1]);
466           refGroup = (SequenceGroup) seqRefAndGroup[1];
467           text.append("COMBINE\t");
468           text.append(combine_statement.getValue());
469           text.append(newline);
470         }
471         writeSequence_Ref(refSeq, oldRefSeq);
472         refSeq = oldRefSeq;
473
474         writeGroup_Ref(refGroup, oldRefGroup);
475         refGroup = oldRefGroup;
476       }
477       text.append(rowprops.toString());
478     }
479
480     if (list != null)
481     {
482       printGroups(list);
483     }
484
485     if (properties != null)
486     {
487       text.append(newline);
488       text.append(newline);
489       text.append("ALIGNMENT");
490       Enumeration en = properties.keys();
491       while (en.hasMoreElements())
492       {
493         String key = en.nextElement().toString();
494         text.append("\t");
495         text.append(key);
496         text.append("=");
497         text.append(properties.get(key));
498       }
499       // TODO: output alignment visualization settings here if required
500       // iterate through one or more views, defining, marking columns and rows
501       // as visible/hidden, and emmitting view properties.
502       // View specific annotation is
503     }
504
505     return text.toString();
506   }
507
508   private Object writeGroup_Ref(SequenceGroup refGroup,
509           SequenceGroup next_refGroup)
510   {
511     if (next_refGroup == null)
512     {
513
514       if (refGroup != null)
515       {
516         text.append(newline);
517         text.append("GROUP_REF\t");
518         text.append("ALIGNMENT");
519         text.append(newline);
520       }
521       return true;
522     }
523     else
524     {
525       if (refGroup == null || refGroup != next_refGroup)
526       {
527         text.append(newline);
528         text.append("GROUP_REF\t");
529         text.append(next_refGroup.getName());
530         text.append(newline);
531         return true;
532       }
533     }
534     return false;
535   }
536
537   private boolean writeSequence_Ref(SequenceI refSeq, SequenceI next_refSeq)
538   {
539
540     if (next_refSeq == null)
541     {
542       if (refSeq != null)
543       {
544         text.append(newline);
545         text.append("SEQUENCE_REF\t");
546         text.append("ALIGNMENT");
547         text.append(newline);
548         return true;
549       }
550     }
551     else
552     {
553       if (refSeq == null || refSeq != next_refSeq)
554       {
555         text.append(newline);
556         text.append("SEQUENCE_REF\t");
557         text.append(next_refSeq.getName());
558         text.append(newline);
559         return true;
560       }
561     }
562     return false;
563   }
564
565   public void printGroups(List<SequenceGroup> list)
566   {
567     SequenceI seqrep = null;
568     for (SequenceGroup sg : list)
569     {
570       if (!sg.hasSeqrep())
571       {
572         text.append("SEQUENCE_GROUP\t" + sg.getName() + "\t"
573                 + (sg.getStartRes() + 1) + "\t" + (sg.getEndRes() + 1)
574                 + "\t" + "-1\t");
575         seqrep = null;
576       }
577       else
578       {
579         seqrep = sg.getSeqrep();
580         text.append("SEQUENCE_REF\t");
581         text.append(seqrep.getName());
582         text.append(newline);
583         text.append("SEQUENCE_GROUP\t");
584         text.append(sg.getName());
585         text.append("\t");
586         text.append((seqrep.findPosition(sg.getStartRes())));
587         text.append("\t");
588         text.append((seqrep.findPosition(sg.getEndRes())));
589         text.append("\t");
590         text.append("-1\t");
591       }
592       for (int s = 0; s < sg.getSize(); s++)
593       {
594         text.append(sg.getSequenceAt(s).getName());
595         text.append("\t");
596       }
597       text.append(newline);
598       text.append("PROPERTIES\t");
599       text.append(sg.getName());
600       text.append("\t");
601
602       if (sg.getDescription() != null)
603       {
604         text.append("description=");
605         text.append(sg.getDescription());
606         text.append("\t");
607       }
608       if (sg.cs != null)
609       {
610         text.append("colour=");
611         text.append(sg.cs.toString());
612         text.append("\t");
613         if (sg.cs.getThreshold() != 0)
614         {
615           text.append("pidThreshold=");
616           text.append(sg.cs.getThreshold());
617         }
618         if (sg.cs.conservationApplied())
619         {
620           text.append("consThreshold=");
621           text.append(sg.cs.getConservationInc());
622           text.append("\t");
623         }
624       }
625       text.append("outlineColour=");
626       text.append(jalview.util.Format.getHexString(sg.getOutlineColour()));
627       text.append("\t");
628
629       text.append("displayBoxes=");
630       text.append(sg.getDisplayBoxes());
631       text.append("\t");
632       text.append("displayText=");
633       text.append(sg.getDisplayText());
634       text.append("\t");
635       text.append("colourText=");
636       text.append(sg.getColourText());
637       text.append("\t");
638       text.append("showUnconserved=");
639       text.append(sg.getShowNonconserved());
640       text.append("\t");
641       if (sg.textColour != java.awt.Color.black)
642       {
643         text.append("textCol1=");
644         text.append(jalview.util.Format.getHexString(sg.textColour));
645         text.append("\t");
646       }
647       if (sg.textColour2 != java.awt.Color.white)
648       {
649         text.append("textCol2=");
650         text.append(jalview.util.Format.getHexString(sg.textColour2));
651         text.append("\t");
652       }
653       if (sg.thresholdTextColour != 0)
654       {
655         text.append("textColThreshold=");
656         text.append(sg.thresholdTextColour);
657         text.append("\t");
658       }
659       if (sg.idColour != null)
660       {
661         text.append("idColour=");
662         text.append(jalview.util.Format.getHexString(sg.idColour));
663         text.append("\t");
664       }
665       if (sg.isHidereps())
666       {
667         text.append("hide=true\t");
668       }
669       if (sg.isHideCols())
670       {
671         text.append("hidecols=true\t");
672       }
673       if (seqrep != null)
674       {
675         // terminate the last line and clear the sequence ref for the group
676         text.append(newline);
677         text.append("SEQUENCE_REF");
678       }
679       text.append(newline);
680       text.append(newline);
681
682     }
683   }
684
685
686   public boolean annotateAlignmentView(AlignViewportI viewport,
687           String file, DataSourceType protocol)
688   {
689     ColumnSelection colSel = viewport.getColumnSelection();
690     if (colSel == null)
691     {
692       colSel = new ColumnSelection();
693     }
694     boolean rslt = readAnnotationFile(viewport.getAlignment(), colSel,
695             file, protocol);
696     if (rslt && (colSel.hasSelectedColumns() || colSel.hasHiddenColumns()))
697     {
698       viewport.setColumnSelection(colSel);
699     }
700
701     return rslt;
702   }
703
704   public boolean readAnnotationFile(AlignmentI al, String file,
705           DataSourceType sourceType)
706   {
707     return readAnnotationFile(al, null, file, sourceType);
708   }
709
710   public boolean readAnnotationFile(AlignmentI al, ColumnSelection colSel,
711           String file, DataSourceType sourceType)
712   {
713     baseUri = "";
714     BufferedReader in = null;
715     try
716     {
717       if (sourceType == DataSourceType.FILE)
718       {
719         in = new BufferedReader(new FileReader(file));
720         baseUri = new File(file).getParent();
721         if (baseUri == null)
722         {
723           baseUri = "";
724         }
725         else
726         {
727           baseUri += "/";
728         }
729       }
730       else if (sourceType == DataSourceType.URL)
731       {
732         URL url = new URL(file);
733         in = new BufferedReader(new InputStreamReader(url.openStream()));
734         String bs = url.toExternalForm();
735         baseUri = bs.substring(0, bs.indexOf(url.getHost())
736                 + url.getHost().length());
737         baseUri += url.toURI().getPath();
738         if (baseUri.lastIndexOf("/") > -1)
739         {
740           baseUri = baseUri.substring(0, baseUri.lastIndexOf("/")) + "/";
741         }
742       }
743       else if (sourceType == DataSourceType.PASTE)
744       {
745         in = new BufferedReader(new StringReader(file));
746         // TODO - support mimencoded PDBs for a paste.. ?
747         baseUri = "";
748       }
749       else if (sourceType == DataSourceType.CLASSLOADER)
750       {
751         java.io.InputStream is = getClass().getResourceAsStream("/" + file);
752         if (is != null)
753         {
754           in = new BufferedReader(new java.io.InputStreamReader(is));
755           // TODO: this probably doesn't work for classloader - needs a test
756           baseUri = new File("/" + file).getParent() + "/";
757         }
758       }
759       if (in != null)
760       {
761         return parseAnnotationFrom(al, colSel, in);
762       }
763
764     } catch (Exception ex)
765     {
766       ex.printStackTrace();
767       System.out.println("Problem reading annotation file: " + ex);
768       if (nlinesread > 0)
769       {
770         System.out.println("Last read line " + nlinesread + ": '"
771                 + lastread + "' (first 80 chars) ...");
772       }
773       return false;
774     }
775     return false;
776   }
777
778
779   public boolean parseAnnotationFrom(AlignmentI al, ColumnSelection colSel,
780           BufferedReader in) throws Exception
781   {
782     nlinesread = 0;
783     ArrayList<Object[]> combineAnnotation_calls = new ArrayList<Object[]>();
784     ArrayList<Object[]> deferredAnnotation_calls = new ArrayList<Object[]>();
785     boolean modified = false;
786     String groupRef = null;
787     Hashtable groupRefRows = new Hashtable();
788
789     Hashtable autoAnnots = new Hashtable();
790     {
791       String line, label, description, token;
792       int graphStyle, index;
793       int refSeqIndex = 1;
794       int existingAnnotations = 0;
795       // when true - will add new rows regardless of whether they are duplicate
796       // auto-annotation like consensus or conservation graphs
797       boolean overrideAutoAnnot = false;
798       if (al.getAlignmentAnnotation() != null)
799       {
800         existingAnnotations = al.getAlignmentAnnotation().length;
801         if (existingAnnotations > 0)
802         {
803           AlignmentAnnotation[] aa = al.getAlignmentAnnotation();
804           for (int aai = 0; aai < aa.length; aai++)
805           {
806             if (aa[aai].autoCalculated)
807             {
808               // make a note of the name and description
809               autoAnnots.put(
810                       autoAnnotsKey(aa[aai], aa[aai].sequenceRef,
811                               (aa[aai].groupRef == null ? null
812                                       : aa[aai].groupRef.getName())),
813                       new Integer(1));
814             }
815           }
816         }
817       }
818
819       int alWidth = al.getWidth();
820
821       StringTokenizer st;
822       Annotation[] annotations;
823       AlignmentAnnotation annotation = null;
824
825       // First confirm this is an Annotation file
826       boolean jvAnnotationFile = false;
827       while ((line = in.readLine()) != null)
828       {
829         nlinesread++;
830         lastread = new String(line);
831         if (line.indexOf("#") == 0)
832         {
833           continue;
834         }
835
836         if (line.indexOf("JALVIEW_ANNOTATION") > -1)
837         {
838           jvAnnotationFile = true;
839           break;
840         }
841       }
842
843       if (!jvAnnotationFile)
844       {
845         in.close();
846         return false;
847       }
848
849       while ((line = in.readLine()) != null)
850       {
851         nlinesread++;
852         lastread = new String(line);
853         if (line.indexOf("#") == 0
854                 || line.indexOf("JALVIEW_ANNOTATION") > -1
855                 || line.length() == 0)
856         {
857           continue;
858         }
859
860         st = new StringTokenizer(line, "\t");
861         token = st.nextToken();
862         if (token.equalsIgnoreCase("COLOUR"))
863         {
864           // TODO: use graduated colour def'n here too
865           colourAnnotations(al, st.nextToken(), st.nextToken());
866           modified = true;
867           continue;
868         }
869
870         else if (token.equalsIgnoreCase(COMBINE))
871         {
872           // keep a record of current state and resolve groupRef at end
873           combineAnnotation_calls
874                   .add(new Object[] { st, refSeq, groupRef });
875           modified = true;
876           continue;
877         }
878         else if (token.equalsIgnoreCase("ROWPROPERTIES"))
879         {
880           addRowProperties(al, st);
881           modified = true;
882           continue;
883         }
884         else if (token.equalsIgnoreCase(GRAPHLINE))
885         {
886           // resolve at end
887           deferredAnnotation_calls.add(new Object[] { GRAPHLINE, st,
888               refSeq, groupRef });
889           modified = true;
890           continue;
891         }
892
893         else if (token.equalsIgnoreCase("SEQUENCE_REF"))
894         {
895           if (st.hasMoreTokens())
896           {
897             refSeq = al.findName(refSeqId = st.nextToken());
898             if (refSeq == null)
899             {
900               refSeqId = null;
901             }
902             try
903             {
904               refSeqIndex = Integer.parseInt(st.nextToken());
905               if (refSeqIndex < 1)
906               {
907                 refSeqIndex = 1;
908                 System.out
909                         .println("WARNING: SEQUENCE_REF index must be > 0 in AnnotationFile");
910               }
911             } catch (Exception ex)
912             {
913               refSeqIndex = 1;
914             }
915           }
916           else
917           {
918             refSeq = null;
919             refSeqId = null;
920           }
921           continue;
922         }
923         else if (token.equalsIgnoreCase("GROUP_REF"))
924         {
925           // Group references could be forward or backwards, so they are
926           // resolved after the whole file is read in
927           groupRef = null;
928           if (st.hasMoreTokens())
929           {
930             groupRef = st.nextToken();
931             if (groupRef.length() < 1)
932             {
933               groupRef = null; // empty string
934             }
935             else
936             {
937               if (groupRefRows.get(groupRef) == null)
938               {
939                 groupRefRows.put(groupRef, new Vector());
940               }
941             }
942           }
943           continue;
944         }
945         else if (token.equalsIgnoreCase("SEQUENCE_GROUP"))
946         {
947           addGroup(al, st);
948           modified = true;
949           continue;
950         }
951
952         else if (token.equalsIgnoreCase("PROPERTIES"))
953         {
954           addProperties(al, st);
955           modified = true;
956           continue;
957         }
958
959         else if (token.equalsIgnoreCase("BELOW_ALIGNMENT"))
960         {
961           setBelowAlignment(al, st);
962           modified = true;
963           continue;
964         }
965         else if (token.equalsIgnoreCase("ALIGNMENT"))
966         {
967           addAlignmentDetails(al, st);
968           modified = true;
969           continue;
970         }
971         else if (token.equalsIgnoreCase("VIEW_SETREF"))
972         {
973           if (refSeq != null)
974           {
975             al.setSeqrep(refSeq);
976           }
977           modified = true;
978           continue;
979         }
980         else if (token.equalsIgnoreCase("VIEW_HIDECOLS"))
981         {
982           if (st.hasMoreTokens())
983           {
984             if (colSel == null)
985             {
986               colSel = new ColumnSelection();
987             }
988             parseHideCols(colSel, st.nextToken());
989           }
990           modified = true;
991           continue;
992         }
993         else if (token.equalsIgnoreCase("HIDE_INSERTIONS"))
994         {
995           SequenceI sr = refSeq == null ? al.getSeqrep() : refSeq;
996           if (sr == null)
997           {
998             sr = al.getSequenceAt(0);
999           }
1000           if (sr != null)
1001           {
1002             if (colSel == null)
1003             {
1004               System.err
1005                       .println("Cannot process HIDE_INSERTIONS without an alignment view: Ignoring line: "
1006                               + line);
1007             }
1008             else
1009             {
1010               // consider deferring this till after the file has been parsed ?
1011               colSel.hideInsertionsFor(sr);
1012             }
1013           }
1014           modified = true;
1015           continue;
1016         }
1017         else if (token.equalsIgnoreCase(HEADER_STRUCT_MODEL))
1018         {
1019           int hSize = st.countTokens();
1020           StructModelHeader = new String[hSize];
1021           for (int x = 0; x < hSize; x++)
1022           {
1023             StructModelHeader[x] = st.nextToken();
1024           }
1025           continue;
1026         }
1027         else if (token.equalsIgnoreCase(STRUCTMODEL))
1028         {
1029           boolean failedtoadd = true;
1030           // expects STRUCTMODEL <Query> <TemplateSeqId> <ModelFile>
1031           // <FastaMappingFile>
1032           String querySeqId = !st.hasMoreTokens() ? "" : st.nextToken();
1033           SequenceI querySeq = al.findName(querySeqId);
1034           if (st.hasMoreTokens()) {
1035             refSeq = al.findName(refSeqId = st.nextToken());
1036             if (refSeq == null)
1037             {
1038               System.err.println("Couldn't locate " + refSeqId
1039                       + " in the alignment for STRUCTMODEL");
1040               refSeqId = null;
1041             }
1042             else
1043             {
1044               int tSize = st.countTokens() + 2;
1045               String[] rowData = new String[tSize];
1046               rowData[0] = querySeqId;
1047               rowData[1] = refSeqId;
1048               for (int x = 2; x < tSize; x++)
1049               {
1050                 rowData[x] = st.nextToken();
1051               }
1052               if (processStructModel(al, querySeq, refSeq,
1053                       StructModelHeader, rowData, baseUri))
1054               {
1055                 failedtoadd = false;
1056               }
1057             }
1058           }
1059           if (failedtoadd)
1060           {
1061             System.err
1062                     .println("Need minimum of <Query> <TemplateSeqId> <ModelFile> <FastaMappingFile> as tab separated fields after"
1063                             + STRUCTMODEL);
1064           } else {
1065             modified = true;
1066           }
1067           continue;
1068         }
1069         // Parse out the annotation row
1070         graphStyle = AlignmentAnnotation.getGraphValueFromString(token);
1071         label = st.nextToken();
1072
1073         index = 0;
1074         annotations = new Annotation[alWidth];
1075         description = null;
1076         float score = Float.NaN;
1077
1078         if (st.hasMoreTokens())
1079         {
1080           line = st.nextToken();
1081
1082           if (line.indexOf("|") == -1)
1083           {
1084             description = line;
1085             if (st.hasMoreTokens())
1086             {
1087               line = st.nextToken();
1088             }
1089           }
1090
1091           if (st.hasMoreTokens())
1092           {
1093             // This must be the score
1094             score = Float.valueOf(st.nextToken()).floatValue();
1095           }
1096
1097           st = new StringTokenizer(line, "|", true);
1098
1099           boolean emptyColumn = true;
1100           boolean onlyOneElement = (st.countTokens() == 1);
1101
1102           while (st.hasMoreElements() && index < alWidth)
1103           {
1104             token = st.nextToken().trim();
1105
1106             if (onlyOneElement)
1107             {
1108               try
1109               {
1110                 score = Float.valueOf(token).floatValue();
1111                 break;
1112               } catch (NumberFormatException ex)
1113               {
1114               }
1115             }
1116
1117             if (token.equals("|"))
1118             {
1119               if (emptyColumn)
1120               {
1121                 index++;
1122               }
1123
1124               emptyColumn = true;
1125             }
1126             else
1127             {
1128               annotations[index++] = parseAnnotation(token, graphStyle);
1129               emptyColumn = false;
1130             }
1131           }
1132
1133         }
1134
1135         annotation = new AlignmentAnnotation(label, description,
1136                 (index == 0) ? null : annotations, 0, 0, graphStyle);
1137
1138         annotation.score = score;
1139         if (!overrideAutoAnnot
1140                 && autoAnnots.containsKey(autoAnnotsKey(annotation, refSeq,
1141                         groupRef)))
1142         {
1143           // skip - we've already got an automatic annotation of this type.
1144           continue;
1145         }
1146         // otherwise add it!
1147         if (refSeq != null)
1148         {
1149
1150           annotation.belowAlignment = false;
1151           // make a copy of refSeq so we can find other matches in the alignment
1152           SequenceI referedSeq = refSeq;
1153           do
1154           {
1155             // copy before we do any mapping business.
1156             // TODO: verify that undo/redo with 1:many sequence associated
1157             // annotations can be undone correctly
1158             AlignmentAnnotation ann = new AlignmentAnnotation(annotation);
1159             annotation
1160                     .createSequenceMapping(referedSeq, refSeqIndex, false);
1161             annotation.adjustForAlignment();
1162             referedSeq.addAlignmentAnnotation(annotation);
1163             al.addAnnotation(annotation);
1164             al.setAnnotationIndex(annotation,
1165                     al.getAlignmentAnnotation().length
1166                             - existingAnnotations - 1);
1167             if (groupRef != null)
1168             {
1169               ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1170             }
1171             // and recover our virgin copy to use again if necessary.
1172             annotation = ann;
1173
1174           } while (refSeqId != null
1175                   && (referedSeq = al.findName(referedSeq, refSeqId, true)) != null);
1176         }
1177         else
1178         {
1179           al.addAnnotation(annotation);
1180           al.setAnnotationIndex(annotation,
1181                   al.getAlignmentAnnotation().length - existingAnnotations
1182                           - 1);
1183           if (groupRef != null)
1184           {
1185             ((Vector) groupRefRows.get(groupRef)).addElement(annotation);
1186           }
1187         }
1188         // and set modification flag
1189         modified = true;
1190       }
1191       // Resolve the groupRefs
1192       Hashtable<String, SequenceGroup> groupRefLookup = new Hashtable<String, SequenceGroup>();
1193       Enumeration en = groupRefRows.keys();
1194
1195       while (en.hasMoreElements())
1196       {
1197         groupRef = (String) en.nextElement();
1198         boolean matched = false;
1199         // Resolve group: TODO: add a getGroupByName method to alignments
1200         for (SequenceGroup theGroup : al.getGroups())
1201         {
1202           if (theGroup.getName().equals(groupRef))
1203           {
1204             if (matched)
1205             {
1206               // TODO: specify and implement duplication of alignment annotation
1207               // for multiple group references.
1208               System.err
1209                       .println("Ignoring 1:many group reference mappings for group name '"
1210                               + groupRef + "'");
1211             }
1212             else
1213             {
1214               matched = true;
1215               Vector rowset = (Vector) groupRefRows.get(groupRef);
1216               groupRefLookup.put(groupRef, theGroup);
1217               if (rowset != null && rowset.size() > 0)
1218               {
1219                 AlignmentAnnotation alan = null;
1220                 for (int elm = 0, elmSize = rowset.size(); elm < elmSize; elm++)
1221                 {
1222                   alan = (AlignmentAnnotation) rowset.elementAt(elm);
1223                   alan.groupRef = theGroup;
1224                 }
1225               }
1226             }
1227           }
1228         }
1229         ((Vector) groupRefRows.get(groupRef)).removeAllElements();
1230       }
1231       // process any deferred attribute settings for each context
1232       for (Object[] _deferred_args : deferredAnnotation_calls)
1233       {
1234         if (_deferred_args[0] == GRAPHLINE)
1235         {
1236           addLine(al,
1237                   (StringTokenizer) _deferred_args[1], // st
1238                   (SequenceI) _deferred_args[2], // refSeq
1239                   (_deferred_args[3] == null) ? null : groupRefLookup
1240                           .get(_deferred_args[3]) // the reference
1241                                                   // group, or null
1242           );
1243         }
1244       }
1245
1246       // finally, combine all the annotation rows within each context.
1247       /**
1248        * number of combine statements in this annotation file. Used to create
1249        * new groups for combined annotation graphs without disturbing existing
1250        * ones
1251        */
1252       int combinecount = 0;
1253       for (Object[] _combine_args : combineAnnotation_calls)
1254       {
1255         combineAnnotations(al,
1256                 ++combinecount,
1257                 (StringTokenizer) _combine_args[0], // st
1258                 (SequenceI) _combine_args[1], // refSeq
1259                 (_combine_args[2] == null) ? null : groupRefLookup
1260                         .get(_combine_args[2]) // the reference group,
1261                                                // or null
1262         );
1263       }
1264     }
1265     return modified;
1266   }
1267
1268   /**
1269    * Resolve structural model to a reference sequence and register it to
1270    * StructureSelectionManager
1271    * 
1272    * @param al
1273    * @param querySequence
1274    * @param templateSeq
1275    * @param structModelHeader
1276    * @param structModelData
1277    * @return true if model and sequence was added
1278    */
1279   static boolean processStructModel(AlignmentI al, SequenceI querySequence,
1280           SequenceI templateSeq,
1281  String[] structModelHeader,
1282           String[] structModelData, String baseUri)
1283   {
1284     String warningMessage = null;
1285     boolean added = false;
1286     try {
1287       String structureModelFile = resolveAbsolutePath(structModelData[2],
1288               baseUri);
1289       String fastaMappingFile = resolveAbsolutePath(structModelData[3],
1290               baseUri);
1291       // System.out.println("Model File >> " + structureModelFile);
1292       // System.out.println("Fasta File >> " + fastaMappingFile);
1293       String modelName = StructureFile.safeName(structureModelFile);
1294       PDBEntry phyre2PDBEntry = new PDBEntry(modelName, " ",
1295               Type.PDB,
1296               structureModelFile);
1297       String phyre2ModelDesc = generatePhyre2InfoHTMLTable(
1298               structModelHeader, structModelData);
1299       phyre2PDBEntry.setProperty("PHYRE2_MODEL_INFO", phyre2ModelDesc);
1300       templateSeq.getDatasetSequence().addPDBId(phyre2PDBEntry);
1301       if (querySequence != null)
1302       {
1303         querySequence.getDatasetSequence().addPDBId(phyre2PDBEntry);
1304       }
1305       StructureSelectionManager ssm = StructureSelectionManager
1306               .getStructureSelectionManager(Desktop.instance);
1307       ssm.registerPhyre2Template(structureModelFile, fastaMappingFile);
1308       added = true;
1309
1310     } catch (Exception x)
1311     {
1312       warningMessage = x.toString();
1313     } finally {
1314       if (warningMessage !=null)
1315       {
1316         System.err.println("Warnings whilst processing STRUCTMODEL: "+warningMessage);
1317       }
1318     }
1319     return added;
1320   }
1321
1322   static String generatePhyre2InfoHTMLTable(String[] structModelHeader,
1323           String[] structModelData)
1324   {
1325     StringBuilder phyre2InfoBuilder = new StringBuilder();
1326     if (isGenerateStructInfoHtml(structModelHeader, structModelData))
1327     {
1328       phyre2InfoBuilder.append("<html><table border=\"1\" width=100%>")
1329               .append("<tr><td colspan=\"2\"><strong>Phyre2 Template Info</strong></td></tr>");
1330       for (int x = 4; x < structModelData.length; x++)
1331       {
1332         phyre2InfoBuilder.append("<tr><td>").append(structModelHeader[x])
1333                 .append("</td><td>").append(structModelData[x])
1334                 .append("</td></tr>");
1335       }
1336       phyre2InfoBuilder.append("</table></html>");
1337     }
1338     return phyre2InfoBuilder.toString();
1339   }
1340
1341   static boolean isGenerateStructInfoHtml(String[] header, String[] data)
1342   {
1343     boolean generate = true;
1344     if (header == null || data == null)
1345     {
1346       return false;
1347     }
1348     if (header.length < 3 || data.length < 3)
1349     {
1350       generate = false;
1351     }
1352     return generate;
1353   }
1354
1355   static String resolveAbsolutePath(String relURI, String _baseUri)
1356   {
1357     if (relURI.indexOf(":/") > -1 || relURI.startsWith("/")
1358             || "".equals(_baseUri) || relURI.startsWith(_baseUri))
1359     {
1360       return relURI;
1361     }
1362     return _baseUri + relURI;
1363   }
1364
1365   private void parseHideCols(ColumnSelection colSel, String nextToken)
1366   {
1367     StringTokenizer inval = new StringTokenizer(nextToken, ",");
1368     while (inval.hasMoreTokens())
1369     {
1370       String range = inval.nextToken().trim();
1371       int from, to = range.indexOf("-");
1372       if (to == -1)
1373       {
1374         from = to = Integer.parseInt(range);
1375         if (from >= 0)
1376         {
1377           colSel.hideColumns(from, to);
1378         }
1379       }
1380       else
1381       {
1382         from = Integer.parseInt(range.substring(0, to));
1383         if (to < range.length() - 1)
1384         {
1385           to = Integer.parseInt(range.substring(to + 1));
1386         }
1387         else
1388         {
1389           to = from;
1390         }
1391         if (from > 0 && to >= from)
1392         {
1393           colSel.hideColumns(from, to);
1394         }
1395       }
1396     }
1397   }
1398
1399   private Object autoAnnotsKey(AlignmentAnnotation annotation,
1400           SequenceI refSeq, String groupRef)
1401   {
1402     return annotation.graph + "\t" + annotation.label + "\t"
1403             + annotation.description + "\t"
1404             + (refSeq != null ? refSeq.getDisplayId(true) : "");
1405   }
1406
1407   Annotation parseAnnotation(String string, int graphStyle)
1408   {
1409     // don't do the glyph test if we don't want secondary structure
1410     boolean hasSymbols = (graphStyle == AlignmentAnnotation.NO_GRAPH);
1411     String desc = null, displayChar = null;
1412     char ss = ' '; // secondaryStructure
1413     float value = 0;
1414     boolean parsedValue = false, dcset = false;
1415
1416     // find colour here
1417     Color colour = null;
1418     int i = string.indexOf("[");
1419     int j = string.indexOf("]");
1420     if (i > -1 && j > -1)
1421     {
1422       colour = ColorUtils.parseColourString(string.substring(i + 1,
1423               j));
1424       if (i > 0 && string.charAt(i - 1) == ',')
1425       {
1426         // clip the preceding comma as well
1427         i--;
1428       }
1429       string = string.substring(0, i) + string.substring(j + 1);
1430     }
1431
1432     StringTokenizer st = new StringTokenizer(string, ",", true);
1433     String token;
1434     boolean seenContent = false;
1435     int pass = 0;
1436     while (st.hasMoreTokens())
1437     {
1438       pass++;
1439       token = st.nextToken().trim();
1440       if (token.equals(","))
1441       {
1442         if (!seenContent && parsedValue && !dcset)
1443         {
1444           // allow the value below the bar/line to be empty
1445           dcset = true;
1446           displayChar = " ";
1447         }
1448         seenContent = false;
1449         continue;
1450       }
1451       else
1452       {
1453         seenContent = true;
1454       }
1455
1456       if (!parsedValue)
1457       {
1458         try
1459         {
1460           displayChar = token;
1461           // foo
1462           value = new Float(token).floatValue();
1463           parsedValue = true;
1464           continue;
1465         } catch (NumberFormatException ex)
1466         {
1467         }
1468       }
1469       else
1470       {
1471         if (token.length() == 1)
1472         {
1473           displayChar = token;
1474         }
1475       }
1476       if (hasSymbols
1477               && (token.length() == 1 && "()<>[]{}AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz"
1478                       .contains(token)))
1479       {
1480         // Either this character represents a helix or sheet
1481         // or an integer which can be displayed
1482         ss = token.charAt(0);
1483         if (displayChar.equals(token.substring(0, 1)))
1484         {
1485           displayChar = "";
1486         }
1487       }
1488       else if (desc == null || (parsedValue && pass > 2))
1489       {
1490         desc = token;
1491       }
1492
1493     }
1494     // if (!dcset && string.charAt(string.length() - 1) == ',')
1495     // {
1496     // displayChar = " "; // empty display char symbol.
1497     // }
1498     if (displayChar != null && desc != null && desc.length() == 1)
1499     {
1500       if (displayChar.length() > 1)
1501       {
1502         // switch desc and displayChar - legacy support
1503         String tmp = displayChar;
1504         displayChar = desc;
1505         desc = tmp;
1506       }
1507       else
1508       {
1509         if (displayChar.equals(desc))
1510         {
1511           // duplicate label - hangover from the 'robust parser' above
1512           desc = null;
1513         }
1514       }
1515     }
1516     Annotation anot = new Annotation(displayChar, desc, ss, value);
1517
1518     anot.colour = colour;
1519
1520     return anot;
1521   }
1522
1523   void colourAnnotations(AlignmentI al, String label, String colour)
1524   {
1525     Color awtColour = ColorUtils.parseColourString(colour);
1526     Annotation[] annotations;
1527     for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1528     {
1529       if (al.getAlignmentAnnotation()[i].label.equalsIgnoreCase(label))
1530       {
1531         annotations = al.getAlignmentAnnotation()[i].annotations;
1532         for (int j = 0; j < annotations.length; j++)
1533         {
1534           if (annotations[j] != null)
1535           {
1536             annotations[j].colour = awtColour;
1537           }
1538         }
1539       }
1540     }
1541   }
1542
1543   void combineAnnotations(AlignmentI al, int combineCount,
1544           StringTokenizer st, SequenceI seqRef, SequenceGroup groupRef)
1545   {
1546     String group = st.nextToken();
1547     // First make sure we are not overwriting the graphIndex
1548     int graphGroup = 0;
1549     if (al.getAlignmentAnnotation() != null)
1550     {
1551       for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1552       {
1553         AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1554
1555         if (aa.graphGroup > graphGroup)
1556         {
1557           // try to number graphGroups in order of occurence.
1558           graphGroup = aa.graphGroup + 1;
1559         }
1560         if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1561                 && aa.label.equalsIgnoreCase(group))
1562         {
1563           if (aa.graphGroup > -1)
1564           {
1565             graphGroup = aa.graphGroup;
1566           }
1567           else
1568           {
1569             if (graphGroup <= combineCount)
1570             {
1571               graphGroup = combineCount + 1;
1572             }
1573             aa.graphGroup = graphGroup;
1574           }
1575           break;
1576         }
1577       }
1578
1579       // Now update groups
1580       while (st.hasMoreTokens())
1581       {
1582         group = st.nextToken();
1583         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1584         {
1585           AlignmentAnnotation aa = al.getAlignmentAnnotation()[i];
1586           if (aa.sequenceRef == seqRef && aa.groupRef == groupRef
1587                   && aa.label.equalsIgnoreCase(group))
1588           {
1589             aa.graphGroup = graphGroup;
1590             break;
1591           }
1592         }
1593       }
1594     }
1595     else
1596     {
1597       System.err
1598               .println("Couldn't combine annotations. None are added to alignment yet!");
1599     }
1600   }
1601
1602   void addLine(AlignmentI al, StringTokenizer st, SequenceI seqRef,
1603           SequenceGroup groupRef)
1604   {
1605     String group = st.nextToken();
1606     AlignmentAnnotation[] alannot = al.getAlignmentAnnotation();
1607     String nextToken = st.nextToken();
1608     float value = 0f;
1609     try
1610     {
1611       value = Float.valueOf(nextToken);
1612     } catch (NumberFormatException e)
1613     {
1614       System.err.println("line " + nlinesread + ": Threshold '" + nextToken
1615               + "' invalid, setting to zero");
1616     }
1617     String label = st.hasMoreTokens() ? st.nextToken() : null;
1618     Color colour = null;
1619     if (st.hasMoreTokens())
1620     {
1621       colour = ColorUtils.parseColourString(st.nextToken());
1622     }
1623     if (alannot != null)
1624     {
1625       for (int i = 0; i < alannot.length; i++)
1626       {
1627         if (alannot[i].label.equalsIgnoreCase(group)
1628                 && (seqRef == null || alannot[i].sequenceRef == seqRef)
1629                 && (groupRef == null || alannot[i].groupRef == groupRef))
1630         {
1631           alannot[i].setThreshold(new GraphLine(value, label, colour));
1632         }
1633       }
1634     }
1635   }
1636
1637   void addGroup(AlignmentI al, StringTokenizer st)
1638   {
1639     SequenceGroup sg = new SequenceGroup();
1640     sg.setName(st.nextToken());
1641     String rng = "";
1642     try
1643     {
1644       rng = st.nextToken();
1645       if (rng.length() > 0 && !rng.startsWith("*"))
1646       {
1647         sg.setStartRes(Integer.parseInt(rng) - 1);
1648       }
1649       else
1650       {
1651         sg.setStartRes(0);
1652       }
1653       rng = st.nextToken();
1654       if (rng.length() > 0 && !rng.startsWith("*"))
1655       {
1656         sg.setEndRes(Integer.parseInt(rng) - 1);
1657       }
1658       else
1659       {
1660         sg.setEndRes(al.getWidth() - 1);
1661       }
1662     } catch (Exception e)
1663     {
1664       System.err
1665               .println("Couldn't parse Group Start or End Field as '*' or a valid column or sequence index: '"
1666                       + rng + "' - assuming alignment width for group.");
1667       // assume group is full width
1668       sg.setStartRes(0);
1669       sg.setEndRes(al.getWidth() - 1);
1670     }
1671
1672     String index = st.nextToken();
1673     if (index.equals("-1"))
1674     {
1675       while (st.hasMoreElements())
1676       {
1677         sg.addSequence(al.findName(st.nextToken()), false);
1678       }
1679     }
1680     else
1681     {
1682       StringTokenizer st2 = new StringTokenizer(index, ",");
1683
1684       while (st2.hasMoreTokens())
1685       {
1686         String tmp = st2.nextToken();
1687         if (tmp.equals("*"))
1688         {
1689           for (int i = 0; i < al.getHeight(); i++)
1690           {
1691             sg.addSequence(al.getSequenceAt(i), false);
1692           }
1693         }
1694         else if (tmp.indexOf("-") >= 0)
1695         {
1696           StringTokenizer st3 = new StringTokenizer(tmp, "-");
1697
1698           int start = (Integer.parseInt(st3.nextToken()));
1699           int end = (Integer.parseInt(st3.nextToken()));
1700
1701           if (end > start)
1702           {
1703             for (int i = start; i <= end; i++)
1704             {
1705               sg.addSequence(al.getSequenceAt(i - 1), false);
1706             }
1707           }
1708         }
1709         else
1710         {
1711           sg.addSequence(al.getSequenceAt(Integer.parseInt(tmp) - 1), false);
1712         }
1713       }
1714     }
1715
1716     if (refSeq != null)
1717     {
1718       sg.setStartRes(refSeq.findIndex(sg.getStartRes() + 1) - 1);
1719       sg.setEndRes(refSeq.findIndex(sg.getEndRes() + 1) - 1);
1720       sg.setSeqrep(refSeq);
1721     }
1722
1723     if (sg.getSize() > 0)
1724     {
1725       al.addGroup(sg);
1726     }
1727   }
1728
1729   void addRowProperties(AlignmentI al, StringTokenizer st)
1730   {
1731     String label = st.nextToken(), keyValue, key, value;
1732     boolean scaletofit = false, centerlab = false, showalllabs = false;
1733     while (st.hasMoreTokens())
1734     {
1735       keyValue = st.nextToken();
1736       key = keyValue.substring(0, keyValue.indexOf("="));
1737       value = keyValue.substring(keyValue.indexOf("=") + 1);
1738       if (key.equalsIgnoreCase("scaletofit"))
1739       {
1740         scaletofit = Boolean.valueOf(value).booleanValue();
1741       }
1742       if (key.equalsIgnoreCase("showalllabs"))
1743       {
1744         showalllabs = Boolean.valueOf(value).booleanValue();
1745       }
1746       if (key.equalsIgnoreCase("centrelabs"))
1747       {
1748         centerlab = Boolean.valueOf(value).booleanValue();
1749       }
1750       AlignmentAnnotation[] alr = al.getAlignmentAnnotation();
1751       if (alr != null)
1752       {
1753         for (int i = 0; i < alr.length; i++)
1754         {
1755           if (alr[i].label.equalsIgnoreCase(label))
1756           {
1757             alr[i].centreColLabels = centerlab;
1758             alr[i].scaleColLabel = scaletofit;
1759             alr[i].showAllColLabels = showalllabs;
1760           }
1761         }
1762       }
1763     }
1764   }
1765
1766   void addProperties(AlignmentI al, StringTokenizer st)
1767   {
1768
1769     // So far we have only added groups to the annotationHash,
1770     // the idea is in the future properties can be added to
1771     // alignments, other annotations etc
1772     if (al.getGroups() == null)
1773     {
1774       return;
1775     }
1776
1777     String name = st.nextToken();
1778     SequenceGroup sg = null;
1779     for (SequenceGroup _sg : al.getGroups())
1780     {
1781       if ((sg = _sg).getName().equals(name))
1782       {
1783         break;
1784       }
1785       else
1786       {
1787         sg = null;
1788       }
1789     }
1790
1791     if (sg != null)
1792     {
1793       String keyValue, key, value;
1794       ColourSchemeI def = sg.getColourScheme();
1795       while (st.hasMoreTokens())
1796       {
1797         keyValue = st.nextToken();
1798         key = keyValue.substring(0, keyValue.indexOf("="));
1799         value = keyValue.substring(keyValue.indexOf("=") + 1);
1800
1801         if (key.equalsIgnoreCase("description"))
1802         {
1803           sg.setDescription(value);
1804         }
1805         else if (key.equalsIgnoreCase("colour"))
1806         {
1807           sg.cs.setColourScheme(ColourSchemeProperty
1808                   .getColourScheme(al, value));
1809         }
1810         else if (key.equalsIgnoreCase("pidThreshold"))
1811         {
1812           sg.cs.setThreshold(Integer.parseInt(value), true);
1813
1814         }
1815         else if (key.equalsIgnoreCase("consThreshold"))
1816         {
1817           sg.cs.setConservationInc(Integer.parseInt(value));
1818           Conservation c = new Conservation("Group", sg.getSequences(null),
1819                   sg.getStartRes(), sg.getEndRes() + 1);
1820
1821           c.calculate();
1822           c.verdict(false, 25); // TODO: refer to conservation percent threshold
1823
1824           sg.cs.setConservation(c);
1825
1826         }
1827         else if (key.equalsIgnoreCase("outlineColour"))
1828         {
1829           sg.setOutlineColour(ColorUtils.parseColourString(value));
1830         }
1831         else if (key.equalsIgnoreCase("displayBoxes"))
1832         {
1833           sg.setDisplayBoxes(Boolean.valueOf(value).booleanValue());
1834         }
1835         else if (key.equalsIgnoreCase("showUnconserved"))
1836         {
1837           sg.setShowNonconserved(Boolean.valueOf(value).booleanValue());
1838         }
1839         else if (key.equalsIgnoreCase("displayText"))
1840         {
1841           sg.setDisplayText(Boolean.valueOf(value).booleanValue());
1842         }
1843         else if (key.equalsIgnoreCase("colourText"))
1844         {
1845           sg.setColourText(Boolean.valueOf(value).booleanValue());
1846         }
1847         else if (key.equalsIgnoreCase("textCol1"))
1848         {
1849           sg.textColour = ColorUtils.parseColourString(value);
1850         }
1851         else if (key.equalsIgnoreCase("textCol2"))
1852         {
1853           sg.textColour2 = ColorUtils.parseColourString(value);
1854         }
1855         else if (key.equalsIgnoreCase("textColThreshold"))
1856         {
1857           sg.thresholdTextColour = Integer.parseInt(value);
1858         }
1859         else if (key.equalsIgnoreCase("idColour"))
1860         {
1861           Color idColour = ColorUtils.parseColourString(value);
1862           sg.setIdColour(idColour == null ? Color.black : idColour);
1863         }
1864         else if (key.equalsIgnoreCase("hide"))
1865         {
1866           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1867           sg.setHidereps(true);
1868         }
1869         else if (key.equalsIgnoreCase("hidecols"))
1870         {
1871           // see bug https://mantis.lifesci.dundee.ac.uk/view.php?id=25847
1872           sg.setHideCols(true);
1873         }
1874         sg.recalcConservation();
1875       }
1876       if (sg.getColourScheme() == null)
1877       {
1878         sg.setColourScheme(def);
1879       }
1880     }
1881   }
1882
1883   void setBelowAlignment(AlignmentI al, StringTokenizer st)
1884   {
1885     String token;
1886     AlignmentAnnotation aa, ala[] = al.getAlignmentAnnotation();
1887     if (ala == null)
1888     {
1889       System.err
1890               .print("Warning - no annotation to set below for sequence associated annotation:");
1891     }
1892     while (st.hasMoreTokens())
1893     {
1894       token = st.nextToken();
1895       if (ala == null)
1896       {
1897         System.err.print(" " + token);
1898       }
1899       else
1900       {
1901         for (int i = 0; i < al.getAlignmentAnnotation().length; i++)
1902         {
1903           aa = al.getAlignmentAnnotation()[i];
1904           if (aa.sequenceRef == refSeq && aa.label.equals(token))
1905           {
1906             aa.belowAlignment = true;
1907           }
1908         }
1909       }
1910     }
1911     if (ala == null)
1912     {
1913       System.err.print("\n");
1914     }
1915   }
1916
1917   void addAlignmentDetails(AlignmentI al, StringTokenizer st)
1918   {
1919     String keyValue, key, value;
1920     while (st.hasMoreTokens())
1921     {
1922       keyValue = st.nextToken();
1923       key = keyValue.substring(0, keyValue.indexOf("="));
1924       value = keyValue.substring(keyValue.indexOf("=") + 1);
1925       al.setProperty(key, value);
1926     }
1927   }
1928
1929   /**
1930    * Write annotations as a CSV file of the form 'label, value, value, ...' for
1931    * each row.
1932    * 
1933    * @param annotations
1934    * @return CSV file as a string.
1935    */
1936   public String printCSVAnnotations(AlignmentAnnotation[] annotations)
1937   {
1938     if (annotations == null)
1939     {
1940       return "";
1941     }
1942     StringBuffer sp = new StringBuffer();
1943     for (int i = 0; i < annotations.length; i++)
1944     {
1945       String atos = annotations[i].toString();
1946       int p = 0;
1947       do
1948       {
1949         int cp = atos.indexOf("\n", p);
1950         sp.append(annotations[i].label);
1951         sp.append(",");
1952         if (cp > p)
1953         {
1954           sp.append(atos.substring(p, cp + 1));
1955         }
1956         else
1957         {
1958           sp.append(atos.substring(p));
1959           sp.append(newline);
1960         }
1961         p = cp + 1;
1962       } while (p > 0);
1963     }
1964     return sp.toString();
1965   }
1966
1967   public String printAnnotationsForView(AlignViewportI viewport)
1968   {
1969     return printAnnotations(viewport.isShowAnnotation() ? viewport
1970             .getAlignment().getAlignmentAnnotation() : null, viewport
1971             .getAlignment().getGroups(), viewport.getAlignment()
1972             .getProperties(), viewport.getColumnSelection(),
1973             viewport.getAlignment(), null);
1974   }
1975
1976   public String printAnnotationsForAlignment(AlignmentI al)
1977   {
1978     return printAnnotations(al.getAlignmentAnnotation(), al.getGroups(),
1979             al.getProperties(), null, al, null);
1980   }
1981 }