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