JAL-2541 length check in deleteChars (redoing lost commit 4a4bc78)
[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.println(
156               "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.lastColumnPosition : 0;
727
728     if (residuePos == this.end)
729     {
730       endColumn = column;
731     }
732
733     cursor = new SequenceCursor(this, residuePos, column, startColumn,
734             endColumn, this.changeCount);
735   }
736
737   /**
738    * Answers the aligned column position (1..) for the given residue position
739    * (start..) given a 'hint' of a residue/column location in the neighbourhood.
740    * The hint may be left of, at, or to the right of the required position.
741    * 
742    * @param pos
743    * @param curs
744    * @return
745    */
746   protected int findIndex(int pos, SequenceCursor curs)
747   {
748     if (!isValidCursor(curs))
749     {
750       /*
751        * wrong or invalidated cursor, compute de novo
752        */
753       return findIndex(pos);
754     }
755
756     if (curs.residuePosition == pos)
757     {
758       return curs.columnPosition;
759     }
760
761     /*
762      * move left or right to find pos from hint.position
763      */
764     int col = curs.columnPosition - 1; // convert from base 1 to base 0
765     int newPos = curs.residuePosition;
766     int delta = newPos > pos ? -1 : 1;
767
768     while (newPos != pos)
769     {
770       col += delta; // shift one column left or right
771       if (col < 0 || col == sequence.length)
772       {
773         break;
774       }
775       if (!Comparison.isGap(sequence[col]))
776       {
777         newPos += delta;
778       }
779     }
780
781     col++; // convert back to base 1
782     updateCursor(pos, col, curs.firstColumnPosition);
783
784     return col;
785   }
786
787   /**
788    * {@inheritDoc}
789    */
790   @Override
791   public int findPosition(final int column)
792   {
793     /*
794      * use a valid, hopefully nearby, cursor if available
795      */
796     if (isValidCursor(cursor))
797     {
798       return findPosition(column + 1, cursor);
799     }
800     
801     // TODO recode this more naturally i.e. count residues only
802     // as they are found, not 'in anticipation'
803
804     /*
805      * traverse the sequence counting gaps; note the column position
806      * of the first residue, to save in the cursor
807      */
808     int firstResidueColumn = 0;
809     int lastPosFound = 0;
810     int lastPosFoundColumn = 0;
811     int seqlen = sequence.length;
812
813     if (seqlen > 0 && !Comparison.isGap(sequence[0]))
814     {
815       lastPosFound = start;
816       lastPosFoundColumn = 0;
817     }
818
819     int j = 0;
820     int pos = start;
821
822     while (j < column && j < seqlen)
823     {
824       if (!Comparison.isGap(sequence[j]))
825       {
826         lastPosFound = pos;
827         lastPosFoundColumn = j;
828         if (pos == this.start)
829         {
830           firstResidueColumn = j;
831         }
832         pos++;
833       }
834       j++;
835     }
836     if (j < seqlen && !Comparison.isGap(sequence[j]))
837     {
838       lastPosFound = pos;
839       lastPosFoundColumn = j;
840       if (pos == this.start)
841       {
842         firstResidueColumn = j;
843       }
844     }
845
846     /*
847      * update the cursor to the last residue position found (if any)
848      * (converting column position to base 1)
849      */
850     if (lastPosFound != 0)
851     {
852       updateCursor(lastPosFound, lastPosFoundColumn + 1,
853               firstResidueColumn + 1);
854     }
855
856     return pos;
857   }
858
859   /**
860    * Answers true if the given cursor is not null, is for this sequence object,
861    * and has a token value that matches this object's changeCount, else false.
862    * This allows us to ignore a cursor as 'stale' if the sequence has been
863    * modified since the cursor was created.
864    * 
865    * @param curs
866    * @return
867    */
868   protected boolean isValidCursor(SequenceCursor curs)
869   {
870     if (curs == null || curs.sequence != this || curs.token != changeCount)
871     {
872       return false;
873     }
874     /*
875      * sanity check against range
876      */
877     if (curs.columnPosition < 0 || curs.columnPosition > sequence.length)
878     {
879       return false;
880     }
881     if (curs.residuePosition < start || curs.residuePosition > end)
882     {
883       return false;
884     }
885     return true;
886   }
887
888   /**
889    * Answers the sequence position (start..) for the given aligned column
890    * position (1..), given a hint of a cursor in the neighbourhood. The cursor
891    * may lie left of, at, or to the right of the column position.
892    * 
893    * @param col
894    * @param curs
895    * @return
896    */
897   protected int findPosition(final int col, SequenceCursor curs)
898   {
899     if (!isValidCursor(curs))
900     {
901       /*
902        * wrong or invalidated cursor, compute de novo
903        */
904       return findPosition(col - 1);// ugh back to base 0
905     }
906
907     if (curs.columnPosition == col)
908     {
909       cursor = curs; // in case this method becomes public
910       return curs.residuePosition; // easy case :-)
911     }
912
913     if (curs.lastColumnPosition > 0 && curs.lastColumnPosition < col)
914     {
915       /*
916        * sequence lies entirely to the left of col
917        * - return last residue + 1
918        */
919       return end + 1;
920     }
921
922     if (curs.firstColumnPosition > 0 && curs.firstColumnPosition > col)
923     {
924       /*
925        * sequence lies entirely to the right of col
926        * - return first residue
927        */
928       return start;
929     }
930
931     // todo could choose closest to col out of column,
932     // firstColumnPosition, lastColumnPosition as a start point
933
934     /*
935      * move left or right to find pos from cursor position
936      */
937     int firstResidueColumn = curs.firstColumnPosition;
938     int column = curs.columnPosition - 1; // to base 0
939     int newPos = curs.residuePosition;
940     int delta = curs.columnPosition > col ? -1 : 1;
941     boolean gapped = false;
942     int lastFoundPosition = curs.residuePosition;
943     int lastFoundPositionColumn = curs.columnPosition;
944
945     while (column != col - 1)
946     {
947       column += delta; // shift one column left or right
948       if (column < 0 || column == sequence.length)
949       {
950         break;
951       }
952       gapped = Comparison.isGap(sequence[column]);
953       if (!gapped)
954       {
955         newPos += delta;
956         lastFoundPosition = newPos;
957         lastFoundPositionColumn = column + 1;
958         if (lastFoundPosition == this.start)
959         {
960           firstResidueColumn = column + 1;
961         }
962       }
963     }
964
965     if (cursor == null || lastFoundPosition != cursor.residuePosition)
966     {
967       updateCursor(lastFoundPosition, lastFoundPositionColumn,
968               firstResidueColumn);
969     }
970
971     /*
972      * hack to give position to the right if on a gap
973      * or beyond the length of the sequence (see JAL-2562)
974      */
975     if (delta > 0 && (gapped || column >= sequence.length))
976     {
977       newPos++;
978     }
979
980     return newPos;
981   }
982
983   /**
984    * {@inheritDoc}
985    */
986   @Override
987   public Range findPositions(int fromColumn, int toColumn)
988   {
989     if (toColumn < fromColumn || fromColumn < 1)
990     {
991       return null;
992     }
993
994     /*
995      * find the first non-gapped position, if any
996      */
997     int firstPosition = 0;
998     int col = fromColumn - 1;
999     int length = sequence.length;
1000     while (col < length && col < toColumn)
1001     {
1002       if (!Comparison.isGap(sequence[col]))
1003       {
1004         firstPosition = findPosition(col++);
1005         break;
1006       }
1007       col++;
1008     }
1009
1010     if (firstPosition == 0)
1011     {
1012       return null;
1013     }
1014
1015     /*
1016      * find the last non-gapped position
1017      */
1018     int lastPosition = firstPosition;
1019     while (col < length && col < toColumn)
1020     {
1021       if (!Comparison.isGap(sequence[col++]))
1022       {
1023         lastPosition++;
1024       }
1025     }
1026
1027     return new Range(firstPosition, lastPosition);
1028   }
1029
1030   /**
1031    * Returns an int array where indices correspond to each residue in the
1032    * sequence and the element value gives its position in the alignment
1033    * 
1034    * @return int[SequenceI.getEnd()-SequenceI.getStart()+1] or null if no
1035    *         residues in SequenceI object
1036    */
1037   @Override
1038   public int[] gapMap()
1039   {
1040     String seq = jalview.analysis.AlignSeq.extractGaps(
1041             jalview.util.Comparison.GapChars, new String(sequence));
1042     int[] map = new int[seq.length()];
1043     int j = 0;
1044     int p = 0;
1045
1046     while (j < sequence.length)
1047     {
1048       if (!jalview.util.Comparison.isGap(sequence[j]))
1049       {
1050         map[p++] = j;
1051       }
1052
1053       j++;
1054     }
1055
1056     return map;
1057   }
1058
1059   @Override
1060   public int[] findPositionMap()
1061   {
1062     int map[] = new int[sequence.length];
1063     int j = 0;
1064     int pos = start;
1065     int seqlen = sequence.length;
1066     while ((j < seqlen))
1067     {
1068       map[j] = pos;
1069       if (!jalview.util.Comparison.isGap(sequence[j]))
1070       {
1071         pos++;
1072       }
1073
1074       j++;
1075     }
1076     return map;
1077   }
1078
1079   @Override
1080   public List<int[]> getInsertions()
1081   {
1082     ArrayList<int[]> map = new ArrayList<int[]>();
1083     int lastj = -1, j = 0;
1084     int pos = start;
1085     int seqlen = sequence.length;
1086     while ((j < seqlen))
1087     {
1088       if (jalview.util.Comparison.isGap(sequence[j]))
1089       {
1090         if (lastj == -1)
1091         {
1092           lastj = j;
1093         }
1094       }
1095       else
1096       {
1097         if (lastj != -1)
1098         {
1099           map.add(new int[] { lastj, j - 1 });
1100           lastj = -1;
1101         }
1102       }
1103       j++;
1104     }
1105     if (lastj != -1)
1106     {
1107       map.add(new int[] { lastj, j - 1 });
1108       lastj = -1;
1109     }
1110     return map;
1111   }
1112
1113   @Override
1114   public BitSet getInsertionsAsBits()
1115   {
1116     BitSet map = new BitSet();
1117     int lastj = -1, j = 0;
1118     int pos = start;
1119     int seqlen = sequence.length;
1120     while ((j < seqlen))
1121     {
1122       if (jalview.util.Comparison.isGap(sequence[j]))
1123       {
1124         if (lastj == -1)
1125         {
1126           lastj = j;
1127         }
1128       }
1129       else
1130       {
1131         if (lastj != -1)
1132         {
1133           map.set(lastj, j);
1134           lastj = -1;
1135         }
1136       }
1137       j++;
1138     }
1139     if (lastj != -1)
1140     {
1141       map.set(lastj, j);
1142       lastj = -1;
1143     }
1144     return map;
1145   }
1146
1147   @Override
1148   public void deleteChars(int i, int j)
1149   {
1150     int newstart = start, newend = end;
1151     if (i >= sequence.length || i < 0)
1152     {
1153       return;
1154     }
1155
1156     char[] tmp = StringUtils.deleteChars(sequence, i, j);
1157     boolean createNewDs = false;
1158     // TODO: take a (second look) at the dataset creation validation method for
1159     // the very large sequence case
1160     int eindex = -1, sindex = -1;
1161     boolean ecalc = false, scalc = false;
1162     for (int s = i; s < j && s < sequence.length; s++)
1163     {
1164       if (!Comparison.isGap(sequence[s]))
1165       {
1166         if (createNewDs)
1167         {
1168           newend--;
1169         }
1170         else
1171         {
1172           if (!scalc)
1173           {
1174             sindex = findIndex(start) - 1;
1175             scalc = true;
1176           }
1177           if (sindex == s)
1178           {
1179             // delete characters including start of sequence
1180             newstart = findPosition(j);
1181             break; // don't need to search for any more residue characters.
1182           }
1183           else
1184           {
1185             // delete characters after start.
1186             if (!ecalc)
1187             {
1188               eindex = findIndex(end) - 1;
1189               ecalc = true;
1190             }
1191             if (eindex < j)
1192             {
1193               // delete characters at end of sequence
1194               newend = findPosition(i - 1);
1195               break; // don't need to search for any more residue characters.
1196             }
1197             else
1198             {
1199               createNewDs = true;
1200               newend--; // decrease end position by one for the deleted residue
1201               // and search further
1202             }
1203           }
1204         }
1205       }
1206     }
1207     // deletion occured in the middle of the sequence
1208     if (createNewDs && this.datasetSequence != null)
1209     {
1210       // construct a new sequence
1211       Sequence ds = new Sequence(datasetSequence);
1212       // TODO: remove any non-inheritable properties ?
1213       // TODO: create a sequence mapping (since there is a relation here ?)
1214       ds.deleteChars(i, j);
1215       datasetSequence = ds;
1216     }
1217     start = newstart;
1218     end = newend;
1219     sequence = tmp;
1220     sequenceChanged();
1221   }
1222
1223   @Override
1224   public void insertCharAt(int i, int length, char c)
1225   {
1226     char[] tmp = new char[sequence.length + length];
1227
1228     if (i >= sequence.length)
1229     {
1230       System.arraycopy(sequence, 0, tmp, 0, sequence.length);
1231       i = sequence.length;
1232     }
1233     else
1234     {
1235       System.arraycopy(sequence, 0, tmp, 0, i);
1236     }
1237
1238     int index = i;
1239     while (length > 0)
1240     {
1241       tmp[index++] = c;
1242       length--;
1243     }
1244
1245     if (i < sequence.length)
1246     {
1247       System.arraycopy(sequence, i, tmp, index, sequence.length - i);
1248     }
1249
1250     sequence = tmp;
1251     sequenceChanged();
1252   }
1253
1254   @Override
1255   public void insertCharAt(int i, char c)
1256   {
1257     insertCharAt(i, 1, c);
1258   }
1259
1260   @Override
1261   public String getVamsasId()
1262   {
1263     return vamsasId;
1264   }
1265
1266   @Override
1267   public void setVamsasId(String id)
1268   {
1269     vamsasId = id;
1270   }
1271
1272   @Override
1273   public void setDBRefs(DBRefEntry[] dbref)
1274   {
1275     if (dbrefs == null && datasetSequence != null
1276             && this != datasetSequence)
1277     {
1278       datasetSequence.setDBRefs(dbref);
1279       return;
1280     }
1281     dbrefs = dbref;
1282     if (dbrefs != null)
1283     {
1284       DBRefUtils.ensurePrimaries(this);
1285     }
1286   }
1287
1288   @Override
1289   public DBRefEntry[] getDBRefs()
1290   {
1291     if (dbrefs == null && datasetSequence != null
1292             && this != datasetSequence)
1293     {
1294       return datasetSequence.getDBRefs();
1295     }
1296     return dbrefs;
1297   }
1298
1299   @Override
1300   public void addDBRef(DBRefEntry entry)
1301   {
1302     if (datasetSequence != null)
1303     {
1304       datasetSequence.addDBRef(entry);
1305       return;
1306     }
1307
1308     if (dbrefs == null)
1309     {
1310       dbrefs = new DBRefEntry[0];
1311     }
1312
1313     for (DBRefEntryI dbr : dbrefs)
1314     {
1315       if (dbr.updateFrom(entry))
1316       {
1317         /*
1318          * found a dbref that either matched, or could be
1319          * updated from, the new entry - no need to add it
1320          */
1321         return;
1322       }
1323     }
1324
1325     /*
1326      * extend the array to make room for one more
1327      */
1328     // TODO use an ArrayList instead
1329     int j = dbrefs.length;
1330     DBRefEntry[] temp = new DBRefEntry[j + 1];
1331     System.arraycopy(dbrefs, 0, temp, 0, j);
1332     temp[temp.length - 1] = entry;
1333
1334     dbrefs = temp;
1335
1336     DBRefUtils.ensurePrimaries(this);
1337   }
1338
1339   @Override
1340   public void setDatasetSequence(SequenceI seq)
1341   {
1342     if (seq == this)
1343     {
1344       throw new IllegalArgumentException(
1345               "Implementation Error: self reference passed to SequenceI.setDatasetSequence");
1346     }
1347     if (seq != null && seq.getDatasetSequence() != null)
1348     {
1349       throw new IllegalArgumentException(
1350               "Implementation error: cascading dataset sequences are not allowed.");
1351     }
1352     datasetSequence = seq;
1353   }
1354
1355   @Override
1356   public SequenceI getDatasetSequence()
1357   {
1358     return datasetSequence;
1359   }
1360
1361   @Override
1362   public AlignmentAnnotation[] getAnnotation()
1363   {
1364     return annotation == null ? null
1365             : annotation
1366                     .toArray(new AlignmentAnnotation[annotation.size()]);
1367   }
1368
1369   @Override
1370   public boolean hasAnnotation(AlignmentAnnotation ann)
1371   {
1372     return annotation == null ? false : annotation.contains(ann);
1373   }
1374
1375   @Override
1376   public void addAlignmentAnnotation(AlignmentAnnotation annotation)
1377   {
1378     if (this.annotation == null)
1379     {
1380       this.annotation = new Vector<AlignmentAnnotation>();
1381     }
1382     if (!this.annotation.contains(annotation))
1383     {
1384       this.annotation.addElement(annotation);
1385     }
1386     annotation.setSequenceRef(this);
1387   }
1388
1389   @Override
1390   public void removeAlignmentAnnotation(AlignmentAnnotation annotation)
1391   {
1392     if (this.annotation != null)
1393     {
1394       this.annotation.removeElement(annotation);
1395       if (this.annotation.size() == 0)
1396       {
1397         this.annotation = null;
1398       }
1399     }
1400   }
1401
1402   /**
1403    * test if this is a valid candidate for another sequence's dataset sequence.
1404    * 
1405    */
1406   private boolean isValidDatasetSequence()
1407   {
1408     if (datasetSequence != null)
1409     {
1410       return false;
1411     }
1412     for (int i = 0; i < sequence.length; i++)
1413     {
1414       if (jalview.util.Comparison.isGap(sequence[i]))
1415       {
1416         return false;
1417       }
1418     }
1419     return true;
1420   }
1421
1422   @Override
1423   public SequenceI deriveSequence()
1424   {
1425     Sequence seq = null;
1426     if (datasetSequence == null)
1427     {
1428       if (isValidDatasetSequence())
1429       {
1430         // Use this as dataset sequence
1431         seq = new Sequence(getName(), "", 1, -1);
1432         seq.setDatasetSequence(this);
1433         seq.initSeqFrom(this, getAnnotation());
1434         return seq;
1435       }
1436       else
1437       {
1438         // Create a new, valid dataset sequence
1439         createDatasetSequence();
1440       }
1441     }
1442     return new Sequence(this);
1443   }
1444
1445   private boolean _isNa;
1446
1447   private int _seqhash = 0;
1448
1449   /**
1450    * Answers false if the sequence is more than 85% nucleotide (ACGTU), else
1451    * true
1452    */
1453   @Override
1454   public boolean isProtein()
1455   {
1456     if (datasetSequence != null)
1457     {
1458       return datasetSequence.isProtein();
1459     }
1460     if (_seqhash != sequence.hashCode())
1461     {
1462       _seqhash = sequence.hashCode();
1463       _isNa = Comparison.isNucleotide(this);
1464     }
1465     return !_isNa;
1466   };
1467
1468   /*
1469    * (non-Javadoc)
1470    * 
1471    * @see jalview.datamodel.SequenceI#createDatasetSequence()
1472    */
1473   @Override
1474   public SequenceI createDatasetSequence()
1475   {
1476     if (datasetSequence == null)
1477     {
1478       Sequence dsseq = new Sequence(getName(),
1479               AlignSeq.extractGaps(jalview.util.Comparison.GapChars,
1480                       getSequenceAsString()),
1481               getStart(), getEnd());
1482
1483       datasetSequence = dsseq;
1484
1485       dsseq.setDescription(description);
1486       // move features and database references onto dataset sequence
1487       dsseq.sequenceFeatureStore = sequenceFeatureStore;
1488       sequenceFeatureStore = null;
1489       dsseq.dbrefs = dbrefs;
1490       dbrefs = null;
1491       // TODO: search and replace any references to this sequence with
1492       // references to the dataset sequence in Mappings on dbref
1493       dsseq.pdbIds = pdbIds;
1494       pdbIds = null;
1495       datasetSequence.updatePDBIds();
1496       if (annotation != null)
1497       {
1498         // annotation is cloned rather than moved, to preserve what's currently
1499         // on the alignment
1500         for (AlignmentAnnotation aa : annotation)
1501         {
1502           AlignmentAnnotation _aa = new AlignmentAnnotation(aa);
1503           _aa.sequenceRef = datasetSequence;
1504           _aa.adjustForAlignment(); // uses annotation's own record of
1505                                     // sequence-column mapping
1506           datasetSequence.addAlignmentAnnotation(_aa);
1507         }
1508       }
1509     }
1510     return datasetSequence;
1511   }
1512
1513   /*
1514    * (non-Javadoc)
1515    * 
1516    * @see
1517    * jalview.datamodel.SequenceI#setAlignmentAnnotation(AlignmmentAnnotation[]
1518    * annotations)
1519    */
1520   @Override
1521   public void setAlignmentAnnotation(AlignmentAnnotation[] annotations)
1522   {
1523     if (annotation != null)
1524     {
1525       annotation.removeAllElements();
1526     }
1527     if (annotations != null)
1528     {
1529       for (int i = 0; i < annotations.length; i++)
1530       {
1531         if (annotations[i] != null)
1532         {
1533           addAlignmentAnnotation(annotations[i]);
1534         }
1535       }
1536     }
1537   }
1538
1539   @Override
1540   public AlignmentAnnotation[] getAnnotation(String label)
1541   {
1542     if (annotation == null || annotation.size() == 0)
1543     {
1544       return null;
1545     }
1546
1547     Vector<AlignmentAnnotation> subset = new Vector<AlignmentAnnotation>();
1548     Enumeration<AlignmentAnnotation> e = annotation.elements();
1549     while (e.hasMoreElements())
1550     {
1551       AlignmentAnnotation ann = e.nextElement();
1552       if (ann.label != null && ann.label.equals(label))
1553       {
1554         subset.addElement(ann);
1555       }
1556     }
1557     if (subset.size() == 0)
1558     {
1559       return null;
1560     }
1561     AlignmentAnnotation[] anns = new AlignmentAnnotation[subset.size()];
1562     int i = 0;
1563     e = subset.elements();
1564     while (e.hasMoreElements())
1565     {
1566       anns[i++] = e.nextElement();
1567     }
1568     subset.removeAllElements();
1569     return anns;
1570   }
1571
1572   @Override
1573   public boolean updatePDBIds()
1574   {
1575     if (datasetSequence != null)
1576     {
1577       // TODO: could merge DBRefs
1578       return datasetSequence.updatePDBIds();
1579     }
1580     if (dbrefs == null || dbrefs.length == 0)
1581     {
1582       return false;
1583     }
1584     boolean added = false;
1585     for (DBRefEntry dbr : dbrefs)
1586     {
1587       if (DBRefSource.PDB.equals(dbr.getSource()))
1588       {
1589         /*
1590          * 'Add' any PDB dbrefs as a PDBEntry - add is only performed if the
1591          * PDB id is not already present in a 'matching' PDBEntry
1592          * Constructor parses out a chain code if appended to the accession id
1593          * (a fudge used to 'store' the chain code in the DBRef)
1594          */
1595         PDBEntry pdbe = new PDBEntry(dbr);
1596         added |= addPDBId(pdbe);
1597       }
1598     }
1599     return added;
1600   }
1601
1602   @Override
1603   public void transferAnnotation(SequenceI entry, Mapping mp)
1604   {
1605     if (datasetSequence != null)
1606     {
1607       datasetSequence.transferAnnotation(entry, mp);
1608       return;
1609     }
1610     if (entry.getDatasetSequence() != null)
1611     {
1612       transferAnnotation(entry.getDatasetSequence(), mp);
1613       return;
1614     }
1615     // transfer any new features from entry onto sequence
1616     if (entry.getSequenceFeatures() != null)
1617     {
1618
1619       List<SequenceFeature> sfs = entry.getSequenceFeatures();
1620       for (SequenceFeature feature : sfs)
1621       {
1622        SequenceFeature sf[] = (mp != null) ? mp.locateFeature(feature)
1623                 : new SequenceFeature[] { new SequenceFeature(feature) };
1624         if (sf != null)
1625         {
1626           for (int sfi = 0; sfi < sf.length; sfi++)
1627           {
1628             addSequenceFeature(sf[sfi]);
1629           }
1630         }
1631       }
1632     }
1633
1634     // transfer PDB entries
1635     if (entry.getAllPDBEntries() != null)
1636     {
1637       Enumeration<PDBEntry> e = entry.getAllPDBEntries().elements();
1638       while (e.hasMoreElements())
1639       {
1640         PDBEntry pdb = e.nextElement();
1641         addPDBId(pdb);
1642       }
1643     }
1644     // transfer database references
1645     DBRefEntry[] entryRefs = entry.getDBRefs();
1646     if (entryRefs != null)
1647     {
1648       for (int r = 0; r < entryRefs.length; r++)
1649       {
1650         DBRefEntry newref = new DBRefEntry(entryRefs[r]);
1651         if (newref.getMap() != null && mp != null)
1652         {
1653           // remap ref using our local mapping
1654         }
1655         // we also assume all version string setting is done by dbSourceProxy
1656         /*
1657          * if (!newref.getSource().equalsIgnoreCase(dbSource)) {
1658          * newref.setSource(dbSource); }
1659          */
1660         addDBRef(newref);
1661       }
1662     }
1663   }
1664
1665   /**
1666    * @return The index (zero-based) on this sequence in the MSA. It returns
1667    *         {@code -1} if this information is not available.
1668    */
1669   @Override
1670   public int getIndex()
1671   {
1672     return index;
1673   }
1674
1675   /**
1676    * Defines the position of this sequence in the MSA. Use the value {@code -1}
1677    * if this information is undefined.
1678    * 
1679    * @param The
1680    *          position for this sequence. This value is zero-based (zero for
1681    *          this first sequence)
1682    */
1683   @Override
1684   public void setIndex(int value)
1685   {
1686     index = value;
1687   }
1688
1689   @Override
1690   public void setRNA(RNA r)
1691   {
1692     rna = r;
1693   }
1694
1695   @Override
1696   public RNA getRNA()
1697   {
1698     return rna;
1699   }
1700
1701   @Override
1702   public List<AlignmentAnnotation> getAlignmentAnnotations(String calcId,
1703           String label)
1704   {
1705     List<AlignmentAnnotation> result = new ArrayList<AlignmentAnnotation>();
1706     if (this.annotation != null)
1707     {
1708       for (AlignmentAnnotation ann : annotation)
1709       {
1710         if (ann.calcId != null && ann.calcId.equals(calcId)
1711                 && ann.label != null && ann.label.equals(label))
1712         {
1713           result.add(ann);
1714         }
1715       }
1716     }
1717     return result;
1718   }
1719
1720   @Override
1721   public String toString()
1722   {
1723     return getDisplayId(false);
1724   }
1725
1726   @Override
1727   public PDBEntry getPDBEntry(String pdbIdStr)
1728   {
1729     if (getDatasetSequence() != null)
1730     {
1731       return getDatasetSequence().getPDBEntry(pdbIdStr);
1732     }
1733     if (pdbIds == null)
1734     {
1735       return null;
1736     }
1737     List<PDBEntry> entries = getAllPDBEntries();
1738     for (PDBEntry entry : entries)
1739     {
1740       if (entry.getId().equalsIgnoreCase(pdbIdStr))
1741       {
1742         return entry;
1743       }
1744     }
1745     return null;
1746   }
1747
1748   @Override
1749   public List<DBRefEntry> getPrimaryDBRefs()
1750   {
1751     if (datasetSequence != null)
1752     {
1753       return datasetSequence.getPrimaryDBRefs();
1754     }
1755     if (dbrefs == null || dbrefs.length == 0)
1756     {
1757       return Collections.emptyList();
1758     }
1759     synchronized (dbrefs)
1760     {
1761       List<DBRefEntry> primaries = new ArrayList<DBRefEntry>();
1762       DBRefEntry[] tmp = new DBRefEntry[1];
1763       for (DBRefEntry ref : dbrefs)
1764       {
1765         if (!ref.isPrimaryCandidate())
1766         {
1767           continue;
1768         }
1769         if (ref.hasMap())
1770         {
1771           MapList mp = ref.getMap().getMap();
1772           if (mp.getFromLowest() > start || mp.getFromHighest() < end)
1773           {
1774             // map only involves a subsequence, so cannot be primary
1775             continue;
1776           }
1777         }
1778         // whilst it looks like it is a primary ref, we also sanity check type
1779         if (DBRefUtils.getCanonicalName(DBRefSource.PDB)
1780                 .equals(DBRefUtils.getCanonicalName(ref.getSource())))
1781         {
1782           // PDB dbrefs imply there should be a PDBEntry associated
1783           // TODO: tighten PDB dbrefs
1784           // formally imply Jalview has actually downloaded and
1785           // parsed the pdb file. That means there should be a cached file
1786           // handle on the PDBEntry, and a real mapping between sequence and
1787           // extracted sequence from PDB file
1788           PDBEntry pdbentry = getPDBEntry(ref.getAccessionId());
1789           if (pdbentry != null && pdbentry.getFile() != null)
1790           {
1791             primaries.add(ref);
1792           }
1793           continue;
1794         }
1795         // check standard protein or dna sources
1796         tmp[0] = ref;
1797         DBRefEntry[] res = DBRefUtils.selectDbRefs(!isProtein(), tmp);
1798         if (res != null && res[0] == tmp[0])
1799         {
1800           primaries.add(ref);
1801           continue;
1802         }
1803       }
1804       return primaries;
1805     }
1806   }
1807
1808   /**
1809    * {@inheritDoc}
1810    */
1811   @Override
1812   public List<SequenceFeature> findFeatures(int fromColumn, int toColumn,
1813           String... types)
1814   {
1815     int startPos = findPosition(fromColumn - 1); // convert base 1 to base 0
1816     int endPos = fromColumn == toColumn ? startPos
1817             : findPosition(toColumn - 1);
1818
1819     List<SequenceFeature> result = getFeatures().findFeatures(startPos,
1820             endPos, types);
1821     if (datasetSequence != null)
1822     {
1823       result = datasetSequence.getFeatures().findFeatures(startPos, endPos,
1824               types);
1825     }
1826     else
1827     {
1828       result = sequenceFeatureStore.findFeatures(startPos, endPos, types);
1829     }
1830
1831     /*
1832      * if end column is gapped, endPos may be to the right, 
1833      * and we may have included adjacent or enclosing features;
1834      * remove any that are not enclosing, non-contact features
1835      */
1836     if (endPos > this.end || Comparison.isGap(sequence[toColumn - 1]))
1837     {
1838       ListIterator<SequenceFeature> it = result.listIterator();
1839       while (it.hasNext())
1840       {
1841         SequenceFeature sf = it.next();
1842         int sfBegin = sf.getBegin();
1843         int sfEnd = sf.getEnd();
1844         int featureStartColumn = findIndex(sfBegin);
1845         if (featureStartColumn > toColumn)
1846         {
1847           it.remove();
1848         }
1849         else if (featureStartColumn < fromColumn)
1850         {
1851           int featureEndColumn = sfEnd == sfBegin ? featureStartColumn
1852                   : findIndex(sfEnd);
1853           if (featureEndColumn < fromColumn)
1854           {
1855             it.remove();
1856           }
1857           else if (featureEndColumn > toColumn && sf.isContactFeature())
1858           {
1859             /*
1860              * remove an enclosing feature if it is a contact feature
1861              */
1862             it.remove();
1863           }
1864         }
1865       }
1866     }
1867
1868     return result;
1869   }
1870
1871   /**
1872    * Invalidates any stale cursors (forcing recalculation) by incrementing the
1873    * token that has to match the one presented by the cursor
1874    */
1875   @Override
1876   public void sequenceChanged()
1877   {
1878     changeCount++;
1879   }
1880
1881   /**
1882    * {@inheritDoc}
1883    */
1884   @Override
1885   public int replace(char c1, char c2)
1886   {
1887     if (c1 == c2)
1888     {
1889       return 0;
1890     }
1891     int count = 0;
1892     synchronized (sequence)
1893     {
1894       for (int c = 0; c < sequence.length; c++)
1895       {
1896         if (sequence[c] == c1)
1897         {
1898           sequence[c] = c2;
1899           count++;
1900         }
1901       }
1902     }
1903     if (count > 0)
1904     {
1905       sequenceChanged();
1906     }
1907
1908     return count;
1909   }
1910 }