JAL-2574 renamed findFeatures as findOverlappingFeatures to minimise
[jalview.git] / src / jalview / datamodel / Sequence.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.datamodel;
22
23 import jalview.analysis.AlignSeq;
24 import jalview.api.DBRefEntryI;
25 import jalview.datamodel.features.SequenceFeatures;
26 import jalview.datamodel.features.SequenceFeaturesI;
27 import jalview.util.Comparison;
28 import jalview.util.DBRefUtils;
29 import jalview.util.MapList;
30 import jalview.util.StringUtils;
31
32 import java.util.ArrayList;
33 import java.util.Arrays;
34 import java.util.BitSet;
35 import java.util.Collections;
36 import java.util.Enumeration;
37 import java.util.List;
38 import java.util.ListIterator;
39 import java.util.Vector;
40
41 import com.stevesoft.pat.Regex;
42
43 import fr.orsay.lri.varna.models.rna.RNA;
44
45 /**
46  * 
47  * Implements the SequenceI interface for a char[] based sequence object
48  */
49 public class Sequence extends ASequence implements SequenceI
50 {
51   private static final Regex limitrx = new Regex(
52           "[/][0-9]{1,}[-][0-9]{1,}$");
53
54   private static final Regex endrx = new Regex("[0-9]{1,}$");
55
56   SequenceI datasetSequence;
57
58   String name;
59
60   private char[] sequence;
61
62   String description;
63
64   int start;
65
66   int end;
67
68   Vector<PDBEntry> pdbIds;
69
70   String vamsasId;
71
72   DBRefEntry[] dbrefs;
73
74   RNA rna;
75
76   /**
77    * This annotation is displayed below the alignment but the positions are tied
78    * to the residues of this sequence
79    *
80    * TODO: change to List<>
81    */
82   Vector<AlignmentAnnotation> annotation;
83
84   /**
85    * The index of the sequence in a MSA
86    */
87   int index = -1;
88
89   private SequenceFeatures sequenceFeatureStore;
90
91   /*
92    * A cursor holding the approximate current view position to the sequence,
93    * as determined by findIndex or findPosition or findPositions.
94    * Using a cursor as a hint allows these methods to be more performant for
95    * large sequences.
96    */
97   private SequenceCursor cursor;
98
99   /*
100    * A number that should be incremented whenever the sequence is edited.
101    * If the value matches the cursor token, then we can trust the cursor,
102    * if not then it should be recomputed. 
103    */
104   private int changeCount;
105
106   /**
107    * Creates a new Sequence object.
108    * 
109    * @param name
110    *          display name string
111    * @param sequence
112    *          string to form a possibly gapped sequence out of
113    * @param start
114    *          first position of non-gap residue in the sequence
115    * @param end
116    *          last position of ungapped residues (nearly always only used for
117    *          display purposes)
118    */
119   public Sequence(String name, String sequence, int start, int end)
120   {
121     this();
122     initSeqAndName(name, sequence.toCharArray(), start, end);
123   }
124
125   public Sequence(String name, char[] sequence, int start, int end)
126   {
127     this();
128     initSeqAndName(name, sequence, start, end);
129   }
130
131   /**
132    * Stage 1 constructor - assign name, sequence, and set start and end fields.
133    * start and end are updated values from name2 if it ends with /start-end
134    * 
135    * @param name2
136    * @param sequence2
137    * @param start2
138    * @param end2
139    */
140   protected void initSeqAndName(String name2, char[] sequence2, int start2,
141           int end2)
142   {
143     this.name = name2;
144     this.sequence = sequence2;
145     this.start = start2;
146     this.end = end2;
147     parseId();
148     checkValidRange();
149   }
150
151   void parseId()
152   {
153     if (name == null)
154     {
155       System.err
156               .println("POSSIBLE IMPLEMENTATION ERROR: null sequence name passed to constructor.");
157       name = "";
158     }
159     // Does sequence have the /start-end signature?
160     if (limitrx.search(name))
161     {
162       name = limitrx.left();
163       endrx.search(limitrx.stringMatched());
164       setStart(Integer.parseInt(limitrx.stringMatched().substring(1,
165               endrx.matchedFrom() - 1)));
166       setEnd(Integer.parseInt(endrx.stringMatched()));
167     }
168   }
169
170   void checkValidRange()
171   {
172     // Note: JAL-774 :
173     // http://issues.jalview.org/browse/JAL-774?focusedCommentId=11239&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-11239
174     {
175       int endRes = 0;
176       for (int j = 0; j < sequence.length; j++)
177       {
178         if (!jalview.util.Comparison.isGap(sequence[j]))
179         {
180           endRes++;
181         }
182       }
183       if (endRes > 0)
184       {
185         endRes += start - 1;
186       }
187
188       if (end < endRes)
189       {
190         end = endRes;
191       }
192     }
193
194   }
195
196   /**
197    * default constructor
198    */
199   private Sequence()
200   {
201     sequenceFeatureStore = new SequenceFeatures();
202   }
203
204   /**
205    * Creates a new Sequence object.
206    * 
207    * @param name
208    *          DOCUMENT ME!
209    * @param sequence
210    *          DOCUMENT ME!
211    */
212   public Sequence(String name, String sequence)
213   {
214     this(name, sequence, 1, -1);
215   }
216
217   /**
218    * Creates a new Sequence object with new AlignmentAnnotations but inherits
219    * any existing dataset sequence reference. If non exists, everything is
220    * copied.
221    * 
222    * @param seq
223    *          if seq is a dataset sequence, behaves like a plain old copy
224    *          constructor
225    */
226   public Sequence(SequenceI seq)
227   {
228     this(seq, seq.getAnnotation());
229   }
230
231   /**
232    * Create a new sequence object with new features, DBRefEntries, and PDBIds
233    * but inherits any existing dataset sequence reference, and duplicate of any
234    * annotation that is present in the given annotation array.
235    * 
236    * @param seq
237    *          the sequence to be copied
238    * @param alAnnotation
239    *          an array of annotation including some associated with seq
240    */
241   public Sequence(SequenceI seq, AlignmentAnnotation[] alAnnotation)
242   {
243     this();
244     initSeqFrom(seq, alAnnotation);
245   }
246
247   /**
248    * does the heavy lifting when cloning a dataset sequence, or coping data from
249    * dataset to a new derived sequence.
250    * 
251    * @param seq
252    *          - source of attributes.
253    * @param alAnnotation
254    *          - alignment annotation present on seq that should be copied onto
255    *          this sequence
256    */
257   protected void initSeqFrom(SequenceI seq,
258           AlignmentAnnotation[] alAnnotation)
259   {
260     char[] oseq = seq.getSequence(); // returns a copy of the array
261     initSeqAndName(seq.getName(), oseq, seq.getStart(), seq.getEnd());
262
263     description = seq.getDescription();
264     if (seq != datasetSequence)
265     {
266       setDatasetSequence(seq.getDatasetSequence());
267     }
268     
269     /*
270      * only copy DBRefs and seqfeatures if we really are a dataset sequence
271      */
272     if (datasetSequence == null)
273     {
274       if (seq.getDBRefs() != null)
275       {
276         DBRefEntry[] dbr = seq.getDBRefs();
277         for (int i = 0; i < dbr.length; i++)
278         {
279           addDBRef(new DBRefEntry(dbr[i]));
280         }
281       }
282
283       /*
284        * make copies of any sequence features
285        */
286       for (SequenceFeature sf : seq.getSequenceFeatures())
287       {
288         addSequenceFeature(new SequenceFeature(sf));
289       }
290     }
291
292     if (seq.getAnnotation() != null)
293     {
294       AlignmentAnnotation[] sqann = seq.getAnnotation();
295       for (int i = 0; i < sqann.length; i++)
296       {
297         if (sqann[i] == null)
298         {
299           continue;
300         }
301         boolean found = (alAnnotation == null);
302         if (!found)
303         {
304           for (int apos = 0; !found && apos < alAnnotation.length; apos++)
305           {
306             found = (alAnnotation[apos] == sqann[i]);
307           }
308         }
309         if (found)
310         {
311           // only copy the given annotation
312           AlignmentAnnotation newann = new AlignmentAnnotation(sqann[i]);
313           addAlignmentAnnotation(newann);
314         }
315       }
316     }
317     if (seq.getAllPDBEntries() != null)
318     {
319       Vector<PDBEntry> ids = seq.getAllPDBEntries();
320       for (PDBEntry pdb : ids)
321       {
322         this.addPDBId(new PDBEntry(pdb));
323       }
324     }
325   }
326
327   @Override
328   public void setSequenceFeatures(List<SequenceFeature> features)
329   {
330     if (datasetSequence != null)
331     {
332       datasetSequence.setSequenceFeatures(features);
333       return;
334     }
335     sequenceFeatureStore = new SequenceFeatures(features);
336   }
337
338   @Override
339   public synchronized boolean addSequenceFeature(SequenceFeature sf)
340   {
341     if (sf.getType() == null)
342     {
343       System.err.println("SequenceFeature type may not be null: "
344               + sf.toString());
345       return false;
346     }
347
348     if (datasetSequence != null)
349     {
350       return datasetSequence.addSequenceFeature(sf);
351     }
352
353     return sequenceFeatureStore.add(sf);
354   }
355
356   @Override
357   public void deleteFeature(SequenceFeature sf)
358   {
359     if (datasetSequence != null)
360     {
361       datasetSequence.deleteFeature(sf);
362     }
363     else
364     {
365       sequenceFeatureStore.delete(sf);
366     }
367   }
368
369   /**
370    * {@inheritDoc}
371    * 
372    * @return
373    */
374   @Override
375   public List<SequenceFeature> getSequenceFeatures()
376   {
377     if (datasetSequence != null)
378     {
379       return datasetSequence.getSequenceFeatures();
380     }
381     return sequenceFeatureStore.getAllFeatures();
382   }
383
384   @Override
385   public SequenceFeaturesI getFeatures()
386   {
387     return datasetSequence != null ? datasetSequence.getFeatures()
388             : sequenceFeatureStore;
389   }
390
391   @Override
392   public boolean addPDBId(PDBEntry entry)
393   {
394     if (pdbIds == null)
395     {
396       pdbIds = new Vector<PDBEntry>();
397       pdbIds.add(entry);
398       return true;
399     }
400
401     for (PDBEntry pdbe : pdbIds)
402     {
403       if (pdbe.updateFrom(entry))
404       {
405         return false;
406       }
407     }
408     pdbIds.addElement(entry);
409     return true;
410   }
411
412   /**
413    * DOCUMENT ME!
414    * 
415    * @param id
416    *          DOCUMENT ME!
417    */
418   @Override
419   public void setPDBId(Vector<PDBEntry> id)
420   {
421     pdbIds = id;
422   }
423
424   /**
425    * DOCUMENT ME!
426    * 
427    * @return DOCUMENT ME!
428    */
429   @Override
430   public Vector<PDBEntry> getAllPDBEntries()
431   {
432     return pdbIds == null ? new Vector<PDBEntry>() : pdbIds;
433   }
434
435   /**
436    * DOCUMENT ME!
437    * 
438    * @return DOCUMENT ME!
439    */
440   @Override
441   public String getDisplayId(boolean jvsuffix)
442   {
443     StringBuffer result = new StringBuffer(name);
444     if (jvsuffix)
445     {
446       result.append("/" + start + "-" + end);
447     }
448
449     return result.toString();
450   }
451
452   /**
453    * DOCUMENT ME!
454    * 
455    * @param name
456    *          DOCUMENT ME!
457    */
458   @Override
459   public void setName(String name)
460   {
461     this.name = name;
462     this.parseId();
463   }
464
465   /**
466    * DOCUMENT ME!
467    * 
468    * @return DOCUMENT ME!
469    */
470   @Override
471   public String getName()
472   {
473     return this.name;
474   }
475
476   /**
477    * DOCUMENT ME!
478    * 
479    * @param start
480    *          DOCUMENT ME!
481    */
482   @Override
483   public void setStart(int start)
484   {
485     this.start = start;
486   }
487
488   /**
489    * DOCUMENT ME!
490    * 
491    * @return DOCUMENT ME!
492    */
493   @Override
494   public int getStart()
495   {
496     return this.start;
497   }
498
499   /**
500    * DOCUMENT ME!
501    * 
502    * @param end
503    *          DOCUMENT ME!
504    */
505   @Override
506   public void setEnd(int end)
507   {
508     this.end = end;
509   }
510
511   /**
512    * DOCUMENT ME!
513    * 
514    * @return DOCUMENT ME!
515    */
516   @Override
517   public int getEnd()
518   {
519     return this.end;
520   }
521
522   /**
523    * DOCUMENT ME!
524    * 
525    * @return DOCUMENT ME!
526    */
527   @Override
528   public int getLength()
529   {
530     return this.sequence.length;
531   }
532
533   /**
534    * DOCUMENT ME!
535    * 
536    * @param seq
537    *          DOCUMENT ME!
538    */
539   @Override
540   public void setSequence(String seq)
541   {
542     this.sequence = seq.toCharArray();
543     checkValidRange();
544     sequenceChanged();
545   }
546
547   @Override
548   public String getSequenceAsString()
549   {
550     return new String(sequence);
551   }
552
553   @Override
554   public String getSequenceAsString(int start, int end)
555   {
556     return new String(getSequence(start, end));
557   }
558
559   @Override
560   public char[] getSequence()
561   {
562     // return sequence;
563     return sequence == null ? null : Arrays.copyOf(sequence,
564             sequence.length);
565   }
566
567   /*
568    * (non-Javadoc)
569    * 
570    * @see jalview.datamodel.SequenceI#getSequence(int, int)
571    */
572   @Override
573   public char[] getSequence(int start, int end)
574   {
575     if (start < 0)
576     {
577       start = 0;
578     }
579     // JBPNote - left to user to pad the result here (TODO:Decide on this
580     // policy)
581     if (start >= sequence.length)
582     {
583       return new char[0];
584     }
585
586     if (end >= sequence.length)
587     {
588       end = sequence.length;
589     }
590
591     char[] reply = new char[end - start];
592     System.arraycopy(sequence, start, reply, 0, end - start);
593
594     return reply;
595   }
596
597   @Override
598   public SequenceI getSubSequence(int start, int end)
599   {
600     if (start < 0)
601     {
602       start = 0;
603     }
604     char[] seq = getSequence(start, end);
605     if (seq.length == 0)
606     {
607       return null;
608     }
609     int nstart = findPosition(start);
610     int nend = findPosition(end) - 1;
611     // JBPNote - this is an incomplete copy.
612     SequenceI nseq = new Sequence(this.getName(), seq, nstart, nend);
613     nseq.setDescription(description);
614     if (datasetSequence != null)
615     {
616       nseq.setDatasetSequence(datasetSequence);
617     }
618     else
619     {
620       nseq.setDatasetSequence(this);
621     }
622     return nseq;
623   }
624
625   /**
626    * Returns the character of the aligned sequence at the given position (base
627    * zero), or space if the position is not within the sequence's bounds
628    * 
629    * @return
630    */
631   @Override
632   public char getCharAt(int i)
633   {
634     if (i >= 0 && i < sequence.length)
635     {
636       return sequence[i];
637     }
638     else
639     {
640       return ' ';
641     }
642   }
643
644   /**
645    * DOCUMENT ME!
646    * 
647    * @param desc
648    *          DOCUMENT ME!
649    */
650   @Override
651   public void setDescription(String desc)
652   {
653     this.description = desc;
654   }
655
656   /**
657    * DOCUMENT ME!
658    * 
659    * @return DOCUMENT ME!
660    */
661   @Override
662   public String getDescription()
663   {
664     return this.description;
665   }
666
667   /**
668    * {@inheritDoc}
669    */
670   @Override
671   public int findIndex(int pos)
672   {
673     /*
674      * use a valid, hopefully nearby, cursor if available
675      */
676     if (isValidCursor(cursor))
677     {
678       return findIndex(pos, cursor);
679     }
680
681     int j = start;
682     int i = 0;
683     int startColumn = 0;
684
685     /*
686      * traverse sequence from the start counting gaps; make a note of
687      * the column of the first residue to save in the cursor
688      */
689     while ((i < sequence.length) && (j <= end) && (j <= pos))
690     {
691       if (!Comparison.isGap(sequence[i]))
692       {
693         if (j == start)
694         {
695           startColumn = i;
696         }
697         j++;
698       }
699       i++;
700     }
701
702     if (j == end && j < pos)
703     {
704       return end + 1;
705     }
706
707     updateCursor(pos, i, startColumn);
708     return i;
709   }
710
711   /**
712    * Updates the cursor to the latest found residue and column position
713    * 
714    * @param residuePos
715    *          (start..)
716    * @param column
717    *          (1..)
718    * @param startColumn
719    *          column position of the first sequence residue
720    */
721   protected void updateCursor(int residuePos, int column, int startColumn)
722   {
723     /*
724      * preserve end residue column provided cursor was valid
725      */
726     int endColumn = isValidCursor(cursor) ? cursor.lastResidueColumn : 0;
727     if (residuePos == this.end)
728     {
729       endColumn = column;
730     }
731
732     cursor = new SequenceCursor(this, residuePos, column, startColumn,
733             endColumn, this.changeCount);
734   }
735
736   /**
737    * Answers the aligned column position (1..) for the given residue position
738    * (start..) given a 'hint' of a residue/column location in the neighbourhood.
739    * The hint may be left of, at, or to the right of the required position.
740    * 
741    * @param pos
742    * @param curs
743    * @return
744    */
745   protected int findIndex(int pos, SequenceCursor curs)
746   {
747     if (!isValidCursor(curs))
748     {
749       /*
750        * wrong or invalidated cursor, compute de novo
751        */
752       return findIndex(pos);
753     }
754
755     if (curs.residuePosition == pos)
756     {
757       return curs.columnPosition;
758     }
759
760     /*
761      * move left or right to find pos from hint.position
762      */
763     int col = curs.columnPosition - 1; // convert from base 1 to base 0
764     int newPos = curs.residuePosition;
765     int delta = newPos > pos ? -1 : 1;
766
767     while (newPos != pos)
768     {
769       col += delta; // shift one column left or right
770       if (col < 0 || col == sequence.length)
771       {
772         break;
773       }
774       if (!Comparison.isGap(sequence[col]))
775       {
776         newPos += delta;
777       }
778     }
779
780     col++; // convert back to base 1
781     updateCursor(pos, col, curs.firstResidueColumn);
782
783     return col;
784   }
785
786   /**
787    * {@inheritDoc}
788    */
789   @Override
790   public Range findPositions(int fromColumn, int toColumn)
791   {
792     if (toColumn < fromColumn || fromColumn < 1)
793     {
794       return null;
795     }
796
797     /*
798      * find the first non-gapped position, if any
799      */
800     int firstPosition = 0;
801     int col = fromColumn - 1;
802     int length = sequence.length;
803     while (col < length && col < toColumn)
804     {
805       if (!Comparison.isGap(sequence[col]))
806       {
807         firstPosition = findPosition(col++);
808         break;
809       }
810       col++;
811     }
812
813     if (firstPosition == 0)
814     {
815       return null;
816     }
817
818     /*
819      * find the last non-gapped position
820      */
821     int lastPosition = firstPosition;
822     while (col < length && col < toColumn)
823     {
824       if (!Comparison.isGap(sequence[col++]))
825       {
826         lastPosition++;
827       }
828     }
829
830     return new Range(firstPosition, lastPosition);
831   }
832
833   /**
834    * {@inheritDoc}
835    */
836   @Override
837   public int findPosition(final int column)
838   {
839     /*
840      * use a valid, hopefully nearby, cursor if available
841      */
842     if (isValidCursor(cursor))
843     {
844       return findPosition(column + 1, cursor);
845     }
846     
847     // TODO recode this more naturally i.e. count residues only
848     // as they are found, not 'in anticipation'
849
850     /*
851      * traverse the sequence counting gaps; note the column position
852      * of the first residue, to save in the cursor
853      */
854     int firstResidueColumn = 0;
855     int lastPosFound = 0;
856     int lastPosFoundColumn = 0;
857     int seqlen = sequence.length;
858
859     if (seqlen > 0 && !Comparison.isGap(sequence[0]))
860     {
861       lastPosFound = start;
862       lastPosFoundColumn = 0;
863     }
864
865     int j = 0;
866     int pos = start;
867
868     while (j < column && j < seqlen)
869     {
870       if (!Comparison.isGap(sequence[j]))
871       {
872         lastPosFound = pos;
873         lastPosFoundColumn = j;
874         if (pos == this.start)
875         {
876           firstResidueColumn = j;
877         }
878         pos++;
879       }
880       j++;
881     }
882     if (j < seqlen && !Comparison.isGap(sequence[j]))
883     {
884       lastPosFound = pos;
885       lastPosFoundColumn = j;
886       if (pos == this.start)
887       {
888         firstResidueColumn = j;
889       }
890     }
891
892     /*
893      * update the cursor to the last residue position found (if any)
894      * (converting column position to base 1)
895      */
896     if (lastPosFound != 0)
897     {
898       updateCursor(lastPosFound, lastPosFoundColumn + 1,
899               firstResidueColumn + 1);
900     }
901
902     return pos;
903   }
904
905   /**
906    * Answers true if the given cursor is not null, is for this sequence object,
907    * and has a token value that matches this object's changeCount, else false.
908    * This allows us to ignore a cursor as 'stale' if the sequence has been
909    * modified since the cursor was created.
910    * 
911    * @param curs
912    * @return
913    */
914   protected boolean isValidCursor(SequenceCursor curs)
915   {
916     if (curs == null || curs.sequence != this || curs.token != changeCount)
917     {
918       return false;
919     }
920     /*
921      * sanity check against range
922      */
923     if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
924     {
925       return false;
926     }
927     if (curs.residuePosition < start || curs.residuePosition > end)
928     {
929       return false;
930     }
931     return true;
932   }
933
934   /**
935    * Answers the sequence position (start..) for the given aligned column
936    * position (1..), given a hint of a cursor in the neighbourhood. The cursor
937    * may lie left of, at, or to the right of the column position.
938    * 
939    * @param col
940    * @param curs
941    * @return
942    */
943   protected int findPosition(final int col, SequenceCursor curs)
944   {
945     if (!isValidCursor(curs))
946     {
947       /*
948        * wrong or invalidated cursor, compute de novo
949        */
950       return findPosition(col - 1);// ugh back to base 0
951     }
952
953     if (curs.columnPosition == col)
954     {
955       cursor = curs; // in case this method becomes public
956       return curs.residuePosition; // easy case :-)
957     }
958
959     if (curs.lastResidueColumn > 0 && curs.lastResidueColumn < col)
960     {
961       /*
962        * sequence lies entirely to the left of col
963        * - return last residue + 1
964        */
965       return end + 1;
966     }
967
968     if (curs.firstResidueColumn > 0 && curs.firstResidueColumn > col)
969     {
970       /*
971        * sequence lies entirely to the right of col
972        * - return first residue
973        */
974       return start;
975     }
976
977     // todo could choose closest to col out of column,
978     // firstColumnPosition, lastColumnPosition as a start point
979
980     /*
981      * move left or right to find pos from cursor position
982      */
983     int firstResidueColumn = curs.firstResidueColumn;
984     int column = curs.columnPosition - 1; // to base 0
985     int newPos = curs.residuePosition;
986     int delta = curs.columnPosition > col ? -1 : 1;
987     boolean gapped = false;
988     int lastFoundPosition = curs.residuePosition;
989     int lastFoundPositionColumn = curs.columnPosition;
990
991     while (column != col - 1)
992     {
993       column += delta; // shift one column left or right
994       if (column < 0 || column == sequence.length)
995       {
996         break;
997       }
998       gapped = Comparison.isGap(sequence[column]);
999       if (!gapped)
1000       {
1001         newPos += delta;
1002         lastFoundPosition = newPos;
1003         lastFoundPositionColumn = column + 1;
1004         if (lastFoundPosition == this.start)
1005         {
1006           firstResidueColumn = column + 1;
1007         }
1008       }
1009     }
1010
1011     if (cursor == null || lastFoundPosition != cursor.residuePosition)
1012     {
1013       updateCursor(lastFoundPosition, lastFoundPositionColumn,
1014               firstResidueColumn);
1015     }
1016
1017     /*
1018      * hack to give position to the right if on a gap
1019      * or beyond the length of the sequence (see JAL-2562)
1020      */
1021     if (delta > 0 && (gapped || column >= sequence.length))
1022     {
1023       newPos++;
1024     }
1025
1026     return newPos;
1027   }
1028
1029   /**
1030    * Returns an int array where indices correspond to each residue in the
1031    * sequence and the element value gives its position in the alignment
1032    * 
1033    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1034    *         residues in SequenceI object
1035    */
1036   @Override
1037   public int[] gapMap()
1038   {
1039     String seq = jalview.analysis.AlignSeq.extractGaps(
1040             jalview.util.Comparison.GapChars, new String(sequence));
1041     int[] map = new int[seq.length()];
1042     int j = 0;
1043     int p = 0;
1044
1045     while (j < sequence.length)
1046     {
1047       if (!jalview.util.Comparison.isGap(sequence[j]))
1048       {
1049         map[p++] = j;
1050       }
1051
1052       j++;
1053     }
1054
1055     return map;
1056   }
1057
1058   @Override
1059   public int[] findPositionMap()
1060   {
1061     int map[] = new int[sequence.length];
1062     int j = 0;
1063     int pos = start;
1064     int seqlen = sequence.length;
1065     while ((j < seqlen))
1066     {
1067       map[j] = pos;
1068       if (!jalview.util.Comparison.isGap(sequence[j]))
1069       {
1070         pos++;
1071       }
1072
1073       j++;
1074     }
1075     return map;
1076   }
1077
1078   @Override
1079   public List<int[]> getInsertions()
1080   {
1081     ArrayList<int[]> map = new ArrayList<int[]>();
1082     int lastj = -1, j = 0;
1083     int pos = start;
1084     int seqlen = sequence.length;
1085     while ((j < seqlen))
1086     {
1087       if (jalview.util.Comparison.isGap(sequence[j]))
1088       {
1089         if (lastj == -1)
1090         {
1091           lastj = j;
1092         }
1093       }
1094       else
1095       {
1096         if (lastj != -1)
1097         {
1098           map.add(new int[] { lastj, j - 1 });
1099           lastj = -1;
1100         }
1101       }
1102       j++;
1103     }
1104     if (lastj != -1)
1105     {
1106       map.add(new int[] { lastj, j - 1 });
1107       lastj = -1;
1108     }
1109     return map;
1110   }
1111
1112   @Override
1113   public BitSet getInsertionsAsBits()
1114   {
1115     BitSet map = new BitSet();
1116     int lastj = -1, j = 0;
1117     int pos = start;
1118     int seqlen = sequence.length;
1119     while ((j < seqlen))
1120     {
1121       if (jalview.util.Comparison.isGap(sequence[j]))
1122       {
1123         if (lastj == -1)
1124         {
1125           lastj = j;
1126         }
1127       }
1128       else
1129       {
1130         if (lastj != -1)
1131         {
1132           map.set(lastj, j);
1133           lastj = -1;
1134         }
1135       }
1136       j++;
1137     }
1138     if (lastj != -1)
1139     {
1140       map.set(lastj, j);
1141       lastj = -1;
1142     }
1143     return map;
1144   }
1145
1146   @Override
1147   public void deleteChars(int i, int j)
1148   {
1149     int newstart = start, newend = end;
1150     if (i >= sequence.length || i < 0)
1151     {
1152       return;
1153     }
1154
1155     char[] tmp = StringUtils.deleteChars(sequence, i, j);
1156     boolean createNewDs = false;
1157     // TODO: take a (second look) at the dataset creation validation method for
1158     // the very large sequence case
1159     int eindex = -1, sindex = -1;
1160     boolean ecalc = false, scalc = false;
1161     for (int s = i; s < j && s < sequence.length; s++)
1162     {
1163       if (!Comparison.isGap(sequence[s]))
1164       {
1165         if (createNewDs)
1166         {
1167           newend--;
1168         }
1169         else
1170         {
1171           if (!scalc)
1172           {
1173             sindex = findIndex(start) - 1;
1174             scalc = true;
1175           }
1176           if (sindex == s)
1177           {
1178             // delete characters including start of sequence
1179             newstart = findPosition(j);
1180             break; // don't need to search for any more residue characters.
1181           }
1182           else
1183           {
1184             // delete characters after start.
1185             if (!ecalc)
1186             {
1187               eindex = findIndex(end) - 1;
1188               ecalc = true;
1189             }
1190             if (eindex < j)
1191             {
1192               // delete characters at end of sequence
1193               newend = findPosition(i - 1);
1194               break; // don't need to search for any more residue characters.
1195             }
1196             else
1197             {
1198               createNewDs = true;
1199               newend--; // decrease end position by one for the deleted residue
1200               // and search further
1201             }
1202           }
1203         }
1204       }
1205     }
1206     // deletion occured in the middle of the sequence
1207     if (createNewDs && this.datasetSequence != null)
1208     {
1209       // construct a new sequence
1210       Sequence ds = new Sequence(datasetSequence);
1211       // TODO: remove any non-inheritable properties ?
1212       // TODO: create a sequence mapping (since there is a relation here ?)
1213       ds.deleteChars(i, j);
1214       datasetSequence = ds;
1215     }
1216     start = newstart;
1217     end = newend;
1218     sequence = tmp;
1219     sequenceChanged();
1220   }
1221
1222   @Override
1223   public void insertCharAt(int i, int length, char c)
1224   {
1225     char[] tmp = new char[sequence.length + length];
1226
1227     if (i >= sequence.length)
1228     {
1229       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1230       i = sequence.length;
1231     }
1232     else
1233     {
1234       System.arraycopy(sequence, 0, tmp, 0, i);
1235     }
1236
1237     int index = i;
1238     while (length > 0)
1239     {
1240       tmp[index++] = c;
1241       length--;
1242     }
1243
1244     if (i < sequence.length)
1245     {
1246       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1247     }
1248
1249     sequence = tmp;
1250     sequenceChanged();
1251   }
1252
1253   @Override
1254   public void insertCharAt(int i, char c)
1255   {
1256     insertCharAt(i, 1, c);
1257   }
1258
1259   @Override
1260   public String getVamsasId()
1261   {
1262     return vamsasId;
1263   }
1264
1265   @Override
1266   public void setVamsasId(String id)
1267   {
1268     vamsasId = id;
1269   }
1270
1271   @Override
1272   public void setDBRefs(DBRefEntry[] dbref)
1273   {
1274     if (dbrefs == null && datasetSequence != null
1275             && this != datasetSequence)
1276     {
1277       datasetSequence.setDBRefs(dbref);
1278       return;
1279     }
1280     dbrefs = dbref;
1281     if (dbrefs != null)
1282     {
1283       DBRefUtils.ensurePrimaries(this);
1284     }
1285   }
1286
1287   @Override
1288   public DBRefEntry[] getDBRefs()
1289   {
1290     if (dbrefs == null && datasetSequence != null
1291             && this != datasetSequence)
1292     {
1293       return datasetSequence.getDBRefs();
1294     }
1295     return dbrefs;
1296   }
1297
1298   @Override
1299   public void addDBRef(DBRefEntry entry)
1300   {
1301     if (datasetSequence != null)
1302     {
1303       datasetSequence.addDBRef(entry);
1304       return;
1305     }
1306
1307     if (dbrefs == null)
1308     {
1309       dbrefs = new DBRefEntry[0];
1310     }
1311
1312     for (DBRefEntryI dbr : dbrefs)
1313     {
1314       if (dbr.updateFrom(entry))
1315       {
1316         /*
1317          * found a dbref that either matched, or could be
1318          * updated from, the new entry - no need to add it
1319          */
1320         return;
1321       }
1322     }
1323
1324     /*
1325      * extend the array to make room for one more
1326      */
1327     // TODO use an ArrayList instead
1328     int j = dbrefs.length;
1329     DBRefEntry[] temp = new DBRefEntry[j + 1];
1330     System.arraycopy(dbrefs, 0, temp, 0, j);
1331     temp[temp.length - 1] = entry;
1332
1333     dbrefs = temp;
1334
1335     DBRefUtils.ensurePrimaries(this);
1336   }
1337
1338   @Override
1339   public void setDatasetSequence(SequenceI seq)
1340   {
1341     if (seq == this)
1342     {
1343       throw new IllegalArgumentException(
1344               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1345     }
1346     if (seq != null && seq.getDatasetSequence() != null)
1347     {
1348       throw new IllegalArgumentException(
1349               "Implementation error: cascading dataset sequences are not allowed.");
1350     }
1351     datasetSequence = seq;
1352   }
1353
1354   @Override
1355   public SequenceI getDatasetSequence()
1356   {
1357     return datasetSequence;
1358   }
1359
1360   @Override
1361   public AlignmentAnnotation[] getAnnotation()
1362   {
1363     return annotation == null ? null : annotation
1364             .toArray(new AlignmentAnnotation[annotation.size()]);
1365   }
1366
1367   @Override
1368   public boolean hasAnnotation(AlignmentAnnotation ann)
1369   {
1370     return annotation == null ? false : annotation.contains(ann);
1371   }
1372
1373   @Override
1374   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1375   {
1376     if (this.annotation == null)
1377     {
1378       this.annotation = new Vector<AlignmentAnnotation>();
1379     }
1380     if (!this.annotation.contains(annotation))
1381     {
1382       this.annotation.addElement(annotation);
1383     }
1384     annotation.setSequenceRef(this);
1385   }
1386
1387   @Override
1388   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1389   {
1390     if (this.annotation != null)
1391     {
1392       this.annotation.removeElement(annotation);
1393       if (this.annotation.size() == 0)
1394       {
1395         this.annotation = null;
1396       }
1397     }
1398   }
1399
1400   /**
1401    * test if this is a valid candidate for another sequence's dataset sequence.
1402    * 
1403    */
1404   private boolean isValidDatasetSequence()
1405   {
1406     if (datasetSequence != null)
1407     {
1408       return false;
1409     }
1410     for (int i = 0; i < sequence.length; i++)
1411     {
1412       if (jalview.util.Comparison.isGap(sequence[i]))
1413       {
1414         return false;
1415       }
1416     }
1417     return true;
1418   }
1419
1420   @Override
1421   public SequenceI deriveSequence()
1422   {
1423     Sequence seq = null;
1424     if (datasetSequence == null)
1425     {
1426       if (isValidDatasetSequence())
1427       {
1428         // Use this as dataset sequence
1429         seq = new Sequence(getName(), "", 1, -1);
1430         seq.setDatasetSequence(this);
1431         seq.initSeqFrom(this, getAnnotation());
1432         return seq;
1433       }
1434       else
1435       {
1436         // Create a new, valid dataset sequence
1437         createDatasetSequence();
1438       }
1439     }
1440     return new Sequence(this);
1441   }
1442
1443   private boolean _isNa;
1444
1445   private int _seqhash = 0;
1446
1447   /**
1448    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1449    * true
1450    */
1451   @Override
1452   public boolean isProtein()
1453   {
1454     if (datasetSequence != null)
1455     {
1456       return datasetSequence.isProtein();
1457     }
1458     if (_seqhash != sequence.hashCode())
1459     {
1460       _seqhash = sequence.hashCode();
1461       _isNa = Comparison.isNucleotide(this);
1462     }
1463     return !_isNa;
1464   };
1465
1466   /*
1467    * (non-Javadoc)
1468    * 
1469    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1470    */
1471   @Override
1472   public SequenceI createDatasetSequence()
1473   {
1474     if (datasetSequence == null)
1475     {
1476       Sequence dsseq = new Sequence(getName(), AlignSeq.extractGaps(
1477               jalview.util.Comparison.GapChars, getSequenceAsString()),
1478               getStart(), getEnd());
1479
1480       datasetSequence = dsseq;
1481
1482       dsseq.setDescription(description);
1483       // move features and database references onto dataset sequence
1484       dsseq.sequenceFeatureStore = sequenceFeatureStore;
1485       sequenceFeatureStore = null;
1486       dsseq.dbrefs = dbrefs;
1487       dbrefs = null;
1488       // TODO: search and replace any references to this sequence with
1489       // references to the dataset sequence in Mappings on dbref
1490       dsseq.pdbIds = pdbIds;
1491       pdbIds = null;
1492       datasetSequence.updatePDBIds();
1493       if (annotation != null)
1494       {
1495         // annotation is cloned rather than moved, to preserve what's currently
1496         // on the alignment
1497         for (AlignmentAnnotation aa : annotation)
1498         {
1499           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1500           _aa.sequenceRef = datasetSequence;
1501           _aa.adjustForAlignment(); // uses annotation's own record of
1502                                     // sequence-column mapping
1503           datasetSequence.addAlignmentAnnotation(_aa);
1504         }
1505       }
1506     }
1507     return datasetSequence;
1508   }
1509
1510   /*
1511    * (non-Javadoc)
1512    * 
1513    * @see
1514    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1515    * annotations)
1516    */
1517   @Override
1518   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1519   {
1520     if (annotation != null)
1521     {
1522       annotation.removeAllElements();
1523     }
1524     if (annotations != null)
1525     {
1526       for (int i = 0; i < annotations.length; i++)
1527       {
1528         if (annotations[i] != null)
1529         {
1530           addAlignmentAnnotation(annotations[i]);
1531         }
1532       }
1533     }
1534   }
1535
1536   @Override
1537   public AlignmentAnnotation[] getAnnotation(String label)
1538   {
1539     if (annotation == null || annotation.size() == 0)
1540     {
1541       return null;
1542     }
1543
1544     Vector<AlignmentAnnotation> subset = new Vector<AlignmentAnnotation>();
1545     Enumeration<AlignmentAnnotation> e = annotation.elements();
1546     while (e.hasMoreElements())
1547     {
1548       AlignmentAnnotation ann = e.nextElement();
1549       if (ann.label != null && ann.label.equals(label))
1550       {
1551         subset.addElement(ann);
1552       }
1553     }
1554     if (subset.size() == 0)
1555     {
1556       return null;
1557     }
1558     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1559     int i = 0;
1560     e = subset.elements();
1561     while (e.hasMoreElements())
1562     {
1563       anns[i++] = e.nextElement();
1564     }
1565     subset.removeAllElements();
1566     return anns;
1567   }
1568
1569   @Override
1570   public boolean updatePDBIds()
1571   {
1572     if (datasetSequence != null)
1573     {
1574       // TODO: could merge DBRefs
1575       return datasetSequence.updatePDBIds();
1576     }
1577     if (dbrefs == null || dbrefs.length == 0)
1578     {
1579       return false;
1580     }
1581     boolean added = false;
1582     for (DBRefEntry dbr : dbrefs)
1583     {
1584       if (DBRefSource.PDB.equals(dbr.getSource()))
1585       {
1586         /*
1587          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1588          * PDB id is not already present in a 'matching' PDBEntry
1589          * Constructor parses out a chain code if appended to the accession id
1590          * (a fudge used to 'store' the chain code in the DBRef)
1591          */
1592         PDBEntry pdbe = new PDBEntry(dbr);
1593         added |= addPDBId(pdbe);
1594       }
1595     }
1596     return added;
1597   }
1598
1599   @Override
1600   public void transferAnnotation(SequenceI entry, Mapping mp)
1601   {
1602     if (datasetSequence != null)
1603     {
1604       datasetSequence.transferAnnotation(entry, mp);
1605       return;
1606     }
1607     if (entry.getDatasetSequence() != null)
1608     {
1609       transferAnnotation(entry.getDatasetSequence(), mp);
1610       return;
1611     }
1612     // transfer any new features from entry onto sequence
1613     if (entry.getSequenceFeatures() != null)
1614     {
1615
1616       List<SequenceFeature> sfs = entry.getSequenceFeatures();
1617       for (SequenceFeature feature : sfs)
1618       {
1619         SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1620                 : new SequenceFeature[] { new SequenceFeature(feature) };
1621         if (sf != null)
1622         {
1623           for (int sfi = 0; sfi < sf.length; sfi++)
1624           {
1625             addSequenceFeature(sf[sfi]);
1626           }
1627         }
1628       }
1629     }
1630
1631     // transfer PDB entries
1632     if (entry.getAllPDBEntries() != null)
1633     {
1634       Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1635       while (e.hasMoreElements())
1636       {
1637         PDBEntry pdb = e.nextElement();
1638         addPDBId(pdb);
1639       }
1640     }
1641     // transfer database references
1642     DBRefEntry[] entryRefs = entry.getDBRefs();
1643     if (entryRefs != null)
1644     {
1645       for (int r = 0; r < entryRefs.length; r++)
1646       {
1647         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1648         if (newref.getMap() != null && mp != null)
1649         {
1650           // remap ref using our local mapping
1651         }
1652         // we also assume all version string setting is done by dbSourceProxy
1653         /*
1654          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1655          * newref.setSource(dbSource); }
1656          */
1657         addDBRef(newref);
1658       }
1659     }
1660   }
1661
1662   /**
1663    * @return The index (zero-based) on this sequence in the MSA. It returns
1664    *         {@code -1} if this information is not available.
1665    */
1666   @Override
1667   public int getIndex()
1668   {
1669     return index;
1670   }
1671
1672   /**
1673    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1674    * if this information is undefined.
1675    * 
1676    * @param The
1677    *          position for this sequence. This value is zero-based (zero for
1678    *          this first sequence)
1679    */
1680   @Override
1681   public void setIndex(int value)
1682   {
1683     index = value;
1684   }
1685
1686   @Override
1687   public void setRNA(RNA r)
1688   {
1689     rna = r;
1690   }
1691
1692   @Override
1693   public RNA getRNA()
1694   {
1695     return rna;
1696   }
1697
1698   @Override
1699   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1700           String label)
1701   {
1702     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1703     if (this.annotation != null)
1704     {
1705       for (AlignmentAnnotation ann : annotation)
1706       {
1707         if (ann.calcId != null && ann.calcId.equals(calcId)
1708                 && ann.label != null && ann.label.equals(label))
1709         {
1710           result.add(ann);
1711         }
1712       }
1713     }
1714     return result;
1715   }
1716
1717   @Override
1718   public String toString()
1719   {
1720     return getDisplayId(false);
1721   }
1722
1723   @Override
1724   public PDBEntry getPDBEntry(String pdbIdStr)
1725   {
1726     if (getDatasetSequence() != null)
1727     {
1728       return getDatasetSequence().getPDBEntry(pdbIdStr);
1729     }
1730     if (pdbIds == null)
1731     {
1732       return null;
1733     }
1734     List<PDBEntry> entries = getAllPDBEntries();
1735     for (PDBEntry entry : entries)
1736     {
1737       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1738       {
1739         return entry;
1740       }
1741     }
1742     return null;
1743   }
1744
1745   @Override
1746   public List<DBRefEntry> getPrimaryDBRefs()
1747   {
1748     if (datasetSequence != null)
1749     {
1750       return datasetSequence.getPrimaryDBRefs();
1751     }
1752     if (dbrefs == null || dbrefs.length == 0)
1753     {
1754       return Collections.emptyList();
1755     }
1756     synchronized (dbrefs)
1757     {
1758       List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1759       DBRefEntry[] tmp = new DBRefEntry[1];
1760       for (DBRefEntry ref : dbrefs)
1761       {
1762         if (!ref.isPrimaryCandidate())
1763         {
1764           continue;
1765         }
1766         if (ref.hasMap())
1767         {
1768           MapList mp = ref.getMap().getMap();
1769           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1770           {
1771             // map only involves a subsequence, so cannot be primary
1772             continue;
1773           }
1774         }
1775         // whilst it looks like it is a primary ref, we also sanity check type
1776         if (DBRefUtils.getCanonicalName(DBRefSource.PDB).equals(
1777                 DBRefUtils.getCanonicalName(ref.getSource())))
1778         {
1779           // PDB dbrefs imply there should be a PDBEntry associated
1780           // TODO: tighten PDB dbrefs
1781           // formally imply Jalview has actually downloaded and
1782           // parsed the pdb file. That means there should be a cached file
1783           // handle on the PDBEntry, and a real mapping between sequence and
1784           // extracted sequence from PDB file
1785           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1786           if (pdbentry != null && pdbentry.getFile() != null)
1787           {
1788             primaries.add(ref);
1789           }
1790           continue;
1791         }
1792         // check standard protein or dna sources
1793         tmp[0] = ref;
1794         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1795         if (res != null && res[0] == tmp[0])
1796         {
1797           primaries.add(ref);
1798           continue;
1799         }
1800       }
1801       return primaries;
1802     }
1803   }
1804
1805   /**
1806    * {@inheritDoc}
1807    */
1808   @Override
1809   public List<SequenceFeature> findOverlappingFeatures(int fromColumn, int toColumn,
1810           String... types)
1811   {
1812     int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1813     int endPos = fromColumn == toColumn ? startPos
1814             : findPosition(toColumn - 1);
1815
1816     List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1817             endPos, types);
1818
1819     /*
1820      * if end column is gapped, endPos may be to the right, 
1821      * and we may have included adjacent or enclosing features;
1822      * remove any that are not enclosing, non-contact features
1823      */
1824     if (endPos > this.end || Comparison.isGap(sequence[toColumn - 1]))
1825     {
1826       ListIterator<SequenceFeature> it = result.listIterator();
1827       while (it.hasNext())
1828       {
1829         SequenceFeature sf = it.next();
1830         int sfBegin = sf.getBegin();
1831         int sfEnd = sf.getEnd();
1832         int featureStartColumn = findIndex(sfBegin);
1833         if (featureStartColumn > toColumn)
1834         {
1835           it.remove();
1836         }
1837         else if (featureStartColumn < fromColumn)
1838         {
1839           int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1840                   : findIndex(sfEnd);
1841           if (featureEndColumn < fromColumn)
1842           {
1843             it.remove();
1844           }
1845           else if (featureEndColumn > toColumn && sf.isContactFeature())
1846           {
1847             /*
1848              * remove an enclosing feature if it is a contact feature
1849              */
1850             it.remove();
1851           }
1852         }
1853       }
1854     }
1855
1856     return result;
1857   }
1858
1859   /**
1860    * Invalidates any stale cursors (forcing recalculation) by incrementing the
1861    * token that has to match the one presented by the cursor
1862    */
1863   @Override
1864   public void sequenceChanged()
1865   {
1866     changeCount++;
1867   }
1868
1869   /**
1870    * {@inheritDoc}
1871    */
1872   @Override
1873   public int replace(char c1, char c2)
1874   {
1875     if (c1 == c2)
1876     {
1877       return 0;
1878     }
1879     int count = 0;
1880     synchronized (sequence)
1881     {
1882       for (int c = 0; c < sequence.length; c++)
1883       {
1884         if (sequence[c] == c1)
1885         {
1886           sequence[c] = c2;
1887           count++;
1888         }
1889       }
1890     }
1891     if (count > 0)
1892     {
1893       sequenceChanged();
1894     }
1895
1896     return count;
1897   }
1898 }