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