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