ea7ac70a003831105992b86e0a5dfbf033cb60bf
[jalview.git] / src / jalview / io / FeaturesFile.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package jalview.io;
19
20 import java.io.*;
21 import java.util.*;
22
23 import jalview.analysis.SequenceIdMatcher;
24 import jalview.datamodel.*;
25 import jalview.schemes.*;
26 import jalview.util.Format;
27
28 /**
29  * Parse and create Jalview Features files Detects GFF format features files and
30  * parses. Does not implement standard print() - call specific printFeatures or
31  * printGFF. Uses AlignmentI.findSequence(String id) to find the sequence object
32  * for the features annotation - this normally works on an exact match.
33  * 
34  * @author AMW
35  * @version $Revision$
36  */
37 public class FeaturesFile extends AlignFile
38 {
39   /**
40    * work around for GFF interpretation bug where source string becomes
41    * description rather than a group
42    */
43   private boolean doGffSource = true;
44
45   /**
46    * Creates a new FeaturesFile object.
47    */
48   public FeaturesFile()
49   {
50   }
51
52   /**
53    * Creates a new FeaturesFile object.
54    * 
55    * @param inFile
56    *          DOCUMENT ME!
57    * @param type
58    *          DOCUMENT ME!
59    * 
60    * @throws IOException
61    *           DOCUMENT ME!
62    */
63   public FeaturesFile(String inFile, String type) throws IOException
64   {
65     super(inFile, type);
66   }
67
68   public FeaturesFile(FileParse source) throws IOException
69   {
70     super(source);
71   }
72
73   /**
74    * Parse GFF or sequence features file using case-independent matching,
75    * discarding URLs
76    * 
77    * @param align
78    *          - alignment/dataset containing sequences that are to be annotated
79    * @param colours
80    *          - hashtable to store feature colour definitions
81    * @param removeHTML
82    *          - process html strings into plain text
83    * @return true if features were added
84    */
85   public boolean parse(AlignmentI align, Hashtable colours,
86           boolean removeHTML)
87   {
88     return parse(align, colours, null, removeHTML, false);
89   }
90
91   /**
92    * Parse GFF or sequence features file optionally using case-independent
93    * matching, discarding URLs
94    * 
95    * @param align
96    *          - alignment/dataset containing sequences that are to be annotated
97    * @param colours
98    *          - hashtable to store feature colour definitions
99    * @param removeHTML
100    *          - process html strings into plain text
101    * @param relaxedIdmatching
102    *          - when true, ID matches to compound sequence IDs are allowed
103    * @return true if features were added
104    */
105   public boolean parse(AlignmentI align, Map colours, boolean removeHTML,
106           boolean relaxedIdMatching)
107   {
108     return parse(align, colours, null, removeHTML, relaxedIdMatching);
109   }
110
111   /**
112    * Parse GFF or sequence features file optionally using case-independent
113    * matching
114    * 
115    * @param align
116    *          - alignment/dataset containing sequences that are to be annotated
117    * @param colours
118    *          - hashtable to store feature colour definitions
119    * @param featureLink
120    *          - hashtable to store associated URLs
121    * @param removeHTML
122    *          - process html strings into plain text
123    * @return true if features were added
124    */
125   public boolean parse(AlignmentI align, Map colours, Map featureLink,
126           boolean removeHTML)
127   {
128     return parse(align, colours, featureLink, removeHTML, false);
129   }
130
131   /**
132    * /** Parse GFF or sequence features file
133    * 
134    * @param align
135    *          - alignment/dataset containing sequences that are to be annotated
136    * @param colours
137    *          - hashtable to store feature colour definitions
138    * @param featureLink
139    *          - hashtable to store associated URLs
140    * @param removeHTML
141    *          - process html strings into plain text
142    * @param relaxedIdmatching
143    *          - when true, ID matches to compound sequence IDs are allowed
144    * @return true if features were added
145    */
146   public boolean parse(AlignmentI align, Map colours, Map featureLink,
147           boolean removeHTML, boolean relaxedIdmatching)
148   {
149
150     String line = null;
151     try
152     {
153       SequenceI seq = null;
154       String type, desc, token = null;
155
156       int index, start, end;
157       float score;
158       StringTokenizer st;
159       SequenceFeature sf;
160       String featureGroup = null, groupLink = null;
161       Map typeLink = new Hashtable();
162       /**
163        * when true, assume GFF style features rather than Jalview style.
164        */
165       boolean GFFFile = true;
166       while ((line = nextLine()) != null)
167       {
168         if (line.startsWith("#"))
169         {
170           continue;
171         }
172
173         st = new StringTokenizer(line, "\t");
174         if (st.countTokens() == 1)
175         {
176           if (line.trim().equalsIgnoreCase("GFF"))
177           {
178             // Start parsing file as if it might be GFF again.
179             GFFFile = true;
180             continue;
181           }
182         }
183         if (st.countTokens() > 1 && st.countTokens() < 4)
184         {
185           GFFFile = false;
186           type = st.nextToken();
187           if (type.equalsIgnoreCase("startgroup"))
188           {
189             featureGroup = st.nextToken();
190             if (st.hasMoreElements())
191             {
192               groupLink = st.nextToken();
193               featureLink.put(featureGroup, groupLink);
194             }
195           }
196           else if (type.equalsIgnoreCase("endgroup"))
197           {
198             // We should check whether this is the current group,
199             // but at present theres no way of showing more than 1 group
200             st.nextToken();
201             featureGroup = null;
202             groupLink = null;
203           }
204           else
205           {
206             Object colour = null;
207             String colscheme = st.nextToken();
208             if (colscheme.indexOf("|") > -1
209                     || colscheme.trim().equalsIgnoreCase("label"))
210             {
211               // Parse '|' separated graduated colourscheme fields:
212               // [label|][mincolour|maxcolour|[absolute|]minvalue|maxvalue|thresholdtype|thresholdvalue]
213               // can either provide 'label' only, first is optional, next two
214               // colors are required (but may be
215               // left blank), next is optional, nxt two min/max are required.
216               // first is either 'label'
217               // first/second and third are both hexadecimal or word equivalent
218               // colour.
219               // next two are values parsed as floats.
220               // fifth is either 'above','below', or 'none'.
221               // sixth is a float value and only required when fifth is either
222               // 'above' or 'below'.
223               StringTokenizer gcol = new StringTokenizer(colscheme, "|",
224                       true);
225               // set defaults
226               int threshtype = AnnotationColourGradient.NO_THRESHOLD;
227               float min = Float.MIN_VALUE, max = Float.MAX_VALUE, threshval = Float.NaN;
228               boolean labelCol = false;
229               // Parse spec line
230               String mincol = gcol.nextToken();
231               if (mincol == "|")
232               {
233                 System.err
234                         .println("Expected either 'label' or a colour specification in the line: "
235                                 + line);
236                 continue;
237               }
238               String maxcol = null;
239               if (mincol.toLowerCase().indexOf("label") == 0)
240               {
241                 labelCol = true;
242                 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null); // skip
243                                                                            // '|'
244                 mincol = (gcol.hasMoreTokens() ? gcol.nextToken() : null);
245               }
246               String abso = null, minval, maxval;
247               if (mincol != null)
248               {
249                 // at least four more tokens
250                 if (mincol.equals("|"))
251                 {
252                   mincol = "";
253                 }
254                 else
255                 {
256                   gcol.nextToken(); // skip next '|'
257                 }
258                 // continue parsing rest of line
259                 maxcol = gcol.nextToken();
260                 if (maxcol.equals("|"))
261                 {
262                   maxcol = "";
263                 }
264                 else
265                 {
266                   gcol.nextToken(); // skip next '|'
267                 }
268                 abso = gcol.nextToken();
269                 gcol.nextToken(); // skip next '|'
270                 if (abso.toLowerCase().indexOf("abso") != 0)
271                 {
272                   minval = abso;
273                   abso = null;
274                 }
275                 else
276                 {
277                   minval = gcol.nextToken();
278                   gcol.nextToken(); // skip next '|'
279                 }
280                 maxval = gcol.nextToken();
281                 if (gcol.hasMoreTokens())
282                 {
283                   gcol.nextToken(); // skip next '|'
284                 }
285                 try
286                 {
287                   if (minval.length() > 0)
288                   {
289                     min = new Float(minval).floatValue();
290                   }
291                 } catch (Exception e)
292                 {
293                   System.err
294                           .println("Couldn't parse the minimum value for graduated colour for type ("
295                                   + colscheme
296                                   + ") - did you misspell 'auto' for the optional automatic colour switch ?");
297                   e.printStackTrace();
298                 }
299                 try
300                 {
301                   if (maxval.length() > 0)
302                   {
303                     max = new Float(maxval).floatValue();
304                   }
305                 } catch (Exception e)
306                 {
307                   System.err
308                           .println("Couldn't parse the maximum value for graduated colour for type ("
309                                   + colscheme + ")");
310                   e.printStackTrace();
311                 }
312               }
313               else
314               {
315                 // add in some dummy min/max colours for the label-only
316                 // colourscheme.
317                 mincol = "FFFFFF";
318                 maxcol = "000000";
319               }
320               try
321               {
322                 colour = new jalview.schemes.GraduatedColor(
323                         new UserColourScheme(mincol).findColour('A'),
324                         new UserColourScheme(maxcol).findColour('A'), min,
325                         max);
326               } catch (Exception e)
327               {
328                 System.err
329                         .println("Couldn't parse the graduated colour scheme ("
330                                 + colscheme + ")");
331                 e.printStackTrace();
332               }
333               if (colour != null)
334               {
335                 ((jalview.schemes.GraduatedColor) colour)
336                         .setColourByLabel(labelCol);
337                 ((jalview.schemes.GraduatedColor) colour)
338                         .setAutoScaled(abso == null);
339                 // add in any additional parameters
340                 String ttype = null, tval = null;
341                 if (gcol.hasMoreTokens())
342                 {
343                   // threshold type and possibly a threshold value
344                   ttype = gcol.nextToken();
345                   if (ttype.toLowerCase().startsWith("below"))
346                   {
347                     ((jalview.schemes.GraduatedColor) colour)
348                             .setThreshType(AnnotationColourGradient.BELOW_THRESHOLD);
349                   }
350                   else if (ttype.toLowerCase().startsWith("above"))
351                   {
352                     ((jalview.schemes.GraduatedColor) colour)
353                             .setThreshType(AnnotationColourGradient.ABOVE_THRESHOLD);
354                   }
355                   else
356                   {
357                     ((jalview.schemes.GraduatedColor) colour)
358                             .setThreshType(AnnotationColourGradient.NO_THRESHOLD);
359                     if (!ttype.toLowerCase().startsWith("no"))
360                     {
361                       System.err
362                               .println("Ignoring unrecognised threshold type : "
363                                       + ttype);
364                     }
365                   }
366                 }
367                 if (((GraduatedColor) colour).getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
368                 {
369                   try
370                   {
371                     gcol.nextToken();
372                     tval = gcol.nextToken();
373                     ((jalview.schemes.GraduatedColor) colour)
374                             .setThresh(new Float(tval).floatValue());
375                   } catch (Exception e)
376                   {
377                     System.err
378                             .println("Couldn't parse threshold value as a float: ("
379                                     + tval + ")");
380                     e.printStackTrace();
381                   }
382                 }
383                 // parse the thresh-is-min token ?
384                 if (gcol.hasMoreTokens())
385                 {
386                   System.err
387                           .println("Ignoring additional tokens in parameters in graduated colour specification\n");
388                   while (gcol.hasMoreTokens())
389                   {
390                     System.err.println("|" + gcol.nextToken());
391                   }
392                   System.err.println("\n");
393                 }
394               }
395             }
396             else
397             {
398               UserColourScheme ucs = new UserColourScheme(colscheme);
399               colour = ucs.findColour('A');
400             }
401             if (colour != null)
402             {
403               colours.put(type, colour);
404             }
405             if (st.hasMoreElements())
406             {
407               String link = st.nextToken();
408               typeLink.put(type, link);
409               if (featureLink == null)
410               {
411                 featureLink = new Hashtable();
412               }
413               featureLink.put(type, link);
414             }
415           }
416           continue;
417         }
418         String seqId = "";
419         while (st.hasMoreElements())
420         {
421
422           if (GFFFile)
423           {
424             // Still possible this is an old Jalview file,
425             // which does not have type colours at the beginning
426             seqId = token = st.nextToken();
427             seq = findName(align, seqId, relaxedIdmatching);
428             if (seq != null)
429             {
430               desc = st.nextToken();
431               String group = null;
432               if (doGffSource && desc.indexOf(' ') == -1)
433               {
434                 // could also be a source term rather than description line
435                 group = new String(desc);
436               }
437               type = st.nextToken();
438               try
439               {
440                 String stt = st.nextToken();
441                 if (stt.length() == 0 || stt.equals("-"))
442                 {
443                   start = 0;
444                 }
445                 else
446                 {
447                   start = Integer.parseInt(stt);
448                 }
449               } catch (NumberFormatException ex)
450               {
451                 start = 0;
452               }
453               try
454               {
455                 String stt = st.nextToken();
456                 if (stt.length() == 0 || stt.equals("-"))
457                 {
458                   end = 0;
459                 }
460                 else
461                 {
462                   end = Integer.parseInt(stt);
463                 }
464               } catch (NumberFormatException ex)
465               {
466                 end = 0;
467               }
468               // TODO: decide if non positional feature assertion for input data
469               // where end==0 is generally valid
470               if (end == 0)
471               {
472                 // treat as non-positional feature, regardless.
473                 start = 0;
474               }
475               try
476               {
477                 score = new Float(st.nextToken()).floatValue();
478               } catch (NumberFormatException ex)
479               {
480                 score = 0;
481               }
482
483               sf = new SequenceFeature(type, desc, start, end, score, group);
484
485               try
486               {
487                 sf.setValue("STRAND", st.nextToken());
488                 sf.setValue("FRAME", st.nextToken());
489               } catch (Exception ex)
490               {
491               }
492
493               if (st.hasMoreTokens())
494               {
495                 StringBuffer attributes = new StringBuffer();
496                 while (st.hasMoreTokens())
497                 {
498                   attributes.append("\t" + st.nextElement());
499                 }
500                 // TODO validate and split GFF2 attributes field ? parse out
501                 // ([A-Za-z][A-Za-z0-9_]*) <value> ; and add as
502                 // sf.setValue(attrib, val);
503                 sf.setValue("ATTRIBUTES", attributes.toString());
504               }
505
506               seq.addSequenceFeature(sf);
507               while ((seq = align.findName(seq, seqId, true)) != null)
508               {
509                 seq.addSequenceFeature(new SequenceFeature(sf));
510               }
511               break;
512             }
513           }
514
515           if (GFFFile && seq == null)
516           {
517             desc = token;
518           }
519           else
520           {
521             desc = st.nextToken();
522           }
523           if (!st.hasMoreTokens())
524           {
525             System.err
526                     .println("DEBUG: Run out of tokens when trying to identify the destination for the feature.. giving up.");
527             // in all probability, this isn't a file we understand, so bail
528             // quietly.
529             return false;
530           }
531
532           token = st.nextToken();
533
534           if (!token.equals("ID_NOT_SPECIFIED"))
535           {
536             seq = findName(align, seqId = token, relaxedIdmatching);
537             st.nextToken();
538           }
539           else
540           {
541             seqId = null;
542             try
543             {
544               index = Integer.parseInt(st.nextToken());
545               seq = align.getSequenceAt(index);
546             } catch (NumberFormatException ex)
547             {
548               seq = null;
549             }
550           }
551
552           if (seq == null)
553           {
554             System.out.println("Sequence not found: " + line);
555             break;
556           }
557
558           start = Integer.parseInt(st.nextToken());
559           end = Integer.parseInt(st.nextToken());
560
561           type = st.nextToken();
562
563           if (!colours.containsKey(type))
564           {
565             // Probably the old style groups file
566             UserColourScheme ucs = new UserColourScheme(type);
567             colours.put(type, ucs.findColour('A'));
568           }
569           sf = new SequenceFeature(type, desc, "", start, end, featureGroup);
570           if (st.hasMoreTokens())
571           {
572             try
573             {
574               score = new Float(st.nextToken()).floatValue();
575               // update colourgradient bounds if allowed to
576             } catch (NumberFormatException ex)
577             {
578               score = 0;
579             }
580             sf.setScore(score);
581           }
582           if (groupLink != null && removeHTML)
583           {
584             sf.addLink(groupLink);
585             sf.description += "%LINK%";
586           }
587           if (typeLink.containsKey(type) && removeHTML)
588           {
589             sf.addLink(typeLink.get(type).toString());
590             sf.description += "%LINK%";
591           }
592
593           parseDescriptionHTML(sf, removeHTML);
594
595           seq.addSequenceFeature(sf);
596
597           while (seqId != null
598                   && (seq = align.findName(seq, seqId, false)) != null)
599           {
600             seq.addSequenceFeature(new SequenceFeature(sf));
601           }
602           // If we got here, its not a GFFFile
603           GFFFile = false;
604         }
605       }
606       resetMatcher();
607     } catch (Exception ex)
608     {
609       System.out.println(line);
610       System.out.println("Error parsing feature file: " + ex + "\n" + line);
611       ex.printStackTrace(System.err);
612       resetMatcher();
613       return false;
614     }
615
616     return true;
617   }
618
619   private AlignmentI lastmatchedAl = null;
620
621   private SequenceIdMatcher matcher = null;
622
623   /**
624    * clear any temporary handles used to speed up ID matching
625    */
626   private void resetMatcher()
627   {
628     lastmatchedAl = null;
629     matcher = null;
630   }
631
632   private SequenceI findName(AlignmentI align, String seqId,
633           boolean relaxedIdMatching)
634   {
635     SequenceI match = null;
636     if (relaxedIdMatching)
637     {
638       if (lastmatchedAl != align)
639       {
640         matcher = new SequenceIdMatcher(
641                 (lastmatchedAl = align).getSequencesArray());
642       }
643       match = matcher.findIdMatch(seqId);
644     }
645     else
646     {
647       match = align.findName(seqId, true);
648     }
649     return match;
650   }
651
652   public void parseDescriptionHTML(SequenceFeature sf, boolean removeHTML)
653   {
654     if (sf.getDescription() == null)
655     {
656       return;
657     }
658     jalview.util.ParseHtmlBodyAndLinks parsed = new jalview.util.ParseHtmlBodyAndLinks(
659             sf.getDescription(), removeHTML, newline);
660
661     sf.description = (removeHTML) ? parsed.getNonHtmlContent()
662             : sf.description;
663     for (String link : parsed.getLinks())
664     {
665       sf.addLink(link);
666     }
667
668   }
669
670   /**
671    * generate a features file for seqs includes non-pos features by default.
672    * 
673    * @param seqs
674    *          source of sequence features
675    * @param visible
676    *          hash of feature types and colours
677    * @return features file contents
678    */
679   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible)
680   {
681     return printJalviewFormat(seqs, visible, true, true);
682   }
683
684   /**
685    * generate a features file for seqs with colours from visible (if any)
686    * 
687    * @param seqs
688    *          source of features
689    * @param visible
690    *          hash of Colours for each feature type
691    * @param visOnly
692    *          when true only feature types in 'visible' will be output
693    * @param nonpos
694    *          indicates if non-positional features should be output (regardless
695    *          of group or type)
696    * @return features file contents
697    */
698   public String printJalviewFormat(SequenceI[] seqs, Hashtable visible,
699           boolean visOnly, boolean nonpos)
700   {
701     StringBuffer out = new StringBuffer();
702     SequenceFeature[] next;
703     boolean featuresGen = false;
704     if (visOnly && !nonpos && (visible == null || visible.size() < 1))
705     {
706       // no point continuing.
707       return "No Features Visible";
708     }
709
710     if (visible != null && visOnly)
711     {
712       // write feature colours only if we're given them and we are generating
713       // viewed features
714       // TODO: decide if feature links should also be written here ?
715       Enumeration en = visible.keys();
716       String type, color;
717       while (en.hasMoreElements())
718       {
719         type = en.nextElement().toString();
720
721         if (visible.get(type) instanceof GraduatedColor)
722         {
723           GraduatedColor gc = (GraduatedColor) visible.get(type);
724           color = (gc.isColourByLabel() ? "label|" : "")
725                   + Format.getHexString(gc.getMinColor()) + "|"
726                   + Format.getHexString(gc.getMaxColor())
727                   + (gc.isAutoScale() ? "|" : "|abso|") + gc.getMin() + "|"
728                   + gc.getMax() + "|";
729           if (gc.getThreshType() != AnnotationColourGradient.NO_THRESHOLD)
730           {
731             if (gc.getThreshType() == AnnotationColourGradient.BELOW_THRESHOLD)
732             {
733               color += "below";
734             }
735             else
736             {
737               if (gc.getThreshType() != AnnotationColourGradient.ABOVE_THRESHOLD)
738               {
739                 System.err.println("WARNING: Unsupported threshold type ("
740                         + gc.getThreshType() + ") : Assuming 'above'");
741               }
742               color += "above";
743             }
744             // add the value
745             color += "|" + gc.getThresh();
746           }
747           else
748           {
749             color += "none";
750           }
751         }
752         else if (visible.get(type) instanceof java.awt.Color)
753         {
754           color = Format.getHexString((java.awt.Color) visible.get(type));
755         }
756         else
757         {
758           // legacy support for integer objects containing colour triplet values
759           color = Format.getHexString(new java.awt.Color(Integer
760                   .parseInt(visible.get(type).toString())));
761         }
762         out.append(type);
763         out.append("\t");
764         out.append(color);
765         out.append(newline);
766       }
767     }
768     // Work out which groups are both present and visible
769     Vector groups = new Vector();
770     int groupIndex = 0;
771     boolean isnonpos = false;
772
773     for (int i = 0; i < seqs.length; i++)
774     {
775       next = seqs[i].getSequenceFeatures();
776       if (next != null)
777       {
778         for (int j = 0; j < next.length; j++)
779         {
780           isnonpos = next[j].begin == 0 && next[j].end == 0;
781           if ((!nonpos && isnonpos)
782                   || (!isnonpos && visOnly && !visible
783                           .containsKey(next[j].type)))
784           {
785             continue;
786           }
787
788           if (next[j].featureGroup != null
789                   && !groups.contains(next[j].featureGroup))
790           {
791             groups.addElement(next[j].featureGroup);
792           }
793         }
794       }
795     }
796
797     String group = null;
798     do
799     {
800
801       if (groups.size() > 0 && groupIndex < groups.size())
802       {
803         group = groups.elementAt(groupIndex).toString();
804         out.append(newline);
805         out.append("STARTGROUP\t");
806         out.append(group);
807         out.append(newline);
808       }
809       else
810       {
811         group = null;
812       }
813
814       for (int i = 0; i < seqs.length; i++)
815       {
816         next = seqs[i].getSequenceFeatures();
817         if (next != null)
818         {
819           for (int j = 0; j < next.length; j++)
820           {
821             isnonpos = next[j].begin == 0 && next[j].end == 0;
822             if ((!nonpos && isnonpos)
823                     || (!isnonpos && visOnly && !visible
824                             .containsKey(next[j].type)))
825             {
826               // skip if feature is nonpos and we ignore them or if we only
827               // output visible and it isn't non-pos and it's not visible
828               continue;
829             }
830
831             if (group != null
832                     && (next[j].featureGroup == null || !next[j].featureGroup
833                             .equals(group)))
834             {
835               continue;
836             }
837
838             if (group == null && next[j].featureGroup != null)
839             {
840               continue;
841             }
842             // we have features to output
843             featuresGen = true;
844             if (next[j].description == null
845                     || next[j].description.equals(""))
846             {
847               out.append(next[j].type + "\t");
848             }
849             else
850             {
851               if (next[j].links != null
852                       && next[j].getDescription().indexOf("<html>") == -1)
853               {
854                 out.append("<html>");
855               }
856
857               out.append(next[j].description + " ");
858               if (next[j].links != null)
859               {
860                 for (int l = 0; l < next[j].links.size(); l++)
861                 {
862                   String label = next[j].links.elementAt(l).toString();
863                   String href = label.substring(label.indexOf("|") + 1);
864                   label = label.substring(0, label.indexOf("|"));
865
866                   if (next[j].description.indexOf(href) == -1)
867                   {
868                     out.append("<a href=\"" + href + "\">" + label + "</a>");
869                   }
870                 }
871
872                 if (next[j].getDescription().indexOf("</html>") == -1)
873                 {
874                   out.append("</html>");
875                 }
876               }
877
878               out.append("\t");
879             }
880             out.append(seqs[i].getName());
881             out.append("\t-1\t");
882             out.append(next[j].begin);
883             out.append("\t");
884             out.append(next[j].end);
885             out.append("\t");
886             out.append(next[j].type);
887             if (next[j].score != Float.NaN)
888             {
889               out.append("\t");
890               out.append(next[j].score);
891             }
892             out.append(newline);
893           }
894         }
895       }
896
897       if (group != null)
898       {
899         out.append("ENDGROUP\t");
900         out.append(group);
901         out.append(newline);
902         groupIndex++;
903       }
904       else
905       {
906         break;
907       }
908
909     } while (groupIndex < groups.size() + 1);
910
911     if (!featuresGen)
912     {
913       return "No Features Visible";
914     }
915
916     return out.toString();
917   }
918
919   /**
920    * generate a gff file for sequence features includes non-pos features by
921    * default.
922    * 
923    * @param seqs
924    * @param visible
925    * @return
926    */
927   public String printGFFFormat(SequenceI[] seqs, Hashtable visible)
928   {
929     return printGFFFormat(seqs, visible, true, true);
930   }
931
932   public String printGFFFormat(SequenceI[] seqs, Hashtable visible,
933           boolean visOnly, boolean nonpos)
934   {
935     StringBuffer out = new StringBuffer();
936     SequenceFeature[] next;
937     String source;
938     boolean isnonpos;
939     for (int i = 0; i < seqs.length; i++)
940     {
941       if (seqs[i].getSequenceFeatures() != null)
942       {
943         next = seqs[i].getSequenceFeatures();
944         for (int j = 0; j < next.length; j++)
945         {
946           isnonpos = next[j].begin == 0 && next[j].end == 0;
947           if ((!nonpos && isnonpos)
948                   || (!isnonpos && visOnly && !visible
949                           .containsKey(next[j].type)))
950           {
951             continue;
952           }
953
954           source = next[j].featureGroup;
955           if (source == null)
956           {
957             source = next[j].getDescription();
958           }
959
960           out.append(seqs[i].getName());
961           out.append("\t");
962           out.append(source);
963           out.append("\t");
964           out.append(next[j].type);
965           out.append("\t");
966           out.append(next[j].begin);
967           out.append("\t");
968           out.append(next[j].end);
969           out.append("\t");
970           out.append(next[j].score);
971           out.append("\t");
972
973           if (next[j].getValue("STRAND") != null)
974           {
975             out.append(next[j].getValue("STRAND"));
976             out.append("\t");
977           }
978           else
979           {
980             out.append(".\t");
981           }
982
983           if (next[j].getValue("FRAME") != null)
984           {
985             out.append(next[j].getValue("FRAME"));
986           }
987           else
988           {
989             out.append(".");
990           }
991           // TODO: verify/check GFF - should there be a /t here before attribute
992           // output ?
993
994           if (next[j].getValue("ATTRIBUTES") != null)
995           {
996             out.append(next[j].getValue("ATTRIBUTES"));
997           }
998
999           out.append(newline);
1000
1001         }
1002       }
1003     }
1004
1005     return out.toString();
1006   }
1007
1008   /**
1009    * this is only for the benefit of object polymorphism - method does nothing.
1010    */
1011   public void parse()
1012   {
1013     // IGNORED
1014   }
1015
1016   /**
1017    * this is only for the benefit of object polymorphism - method does nothing.
1018    * 
1019    * @return error message
1020    */
1021   public String print()
1022   {
1023     return "USE printGFFFormat() or printJalviewFormat()";
1024   }
1025
1026 }