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