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