JAL-2674 iterator updates
[jalview.git] / src / jalview / datamodel / HiddenColumns.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 java.util.ArrayList;
24 import java.util.BitSet;
25 import java.util.Iterator;
26 import java.util.List;
27 import java.util.NoSuchElementException;
28 import java.util.concurrent.locks.ReentrantReadWriteLock;
29
30 public class HiddenColumns
31 {
32   private static final int HASH_MULTIPLIER = 31;
33
34   private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
35
36   /*
37    * list of hidden column [start, end] ranges; the list is maintained in
38    * ascending start column order
39    */
40   private ArrayList<int[]> hiddenColumns;
41
42   /**
43    * Constructor
44    */
45   public HiddenColumns()
46   {
47   }
48
49   /**
50    * Copy constructor
51    * 
52    * @param copy
53    */
54   public HiddenColumns(HiddenColumns copy)
55   {
56     try
57     {
58       LOCK.writeLock().lock();
59       if (copy != null)
60       {
61         if (copy.hiddenColumns != null)
62         {
63           hiddenColumns = new ArrayList<>();
64           Iterator<int[]> it = copy.iterator();
65           while (it.hasNext())
66           {
67             hiddenColumns.add(it.next());
68           }
69         }
70       }
71     } finally
72     {
73       LOCK.writeLock().unlock();
74     }
75   }
76
77   /**
78    * Copy constructor within bounds and with offset. Copies hidden column
79    * regions fully contained between start and end, and offsets positions by
80    * subtracting offset.
81    * 
82    * @param copy
83    *          HiddenColumns instance to copy from
84    * @param start
85    *          lower bound to copy from
86    * @param end
87    *          upper bound to copy to
88    * @param offset
89    *          offset to subtract from each region boundary position
90    * 
91    */
92   public HiddenColumns(HiddenColumns copy, int start, int end, int offset)
93   {
94     try
95     {
96       LOCK.writeLock().lock();
97       if (copy != null)
98       {
99         hiddenColumns = new ArrayList<>();
100         Iterator<int[]> it = copy.getBoundedIterator(start, end);
101         while (it.hasNext())
102         {
103           int[] region = it.next();
104           // still need to check boundaries because iterator returns
105           // all overlapping regions and we need contained regions
106           if (region[0] >= start && region[1] <= end)
107           {
108             hiddenColumns.add(
109                     new int[]
110             { region[0] - offset, region[1] - offset });
111           }
112         }
113       }
114     } finally
115     {
116       LOCK.writeLock().unlock();
117     }
118   }
119
120   /**
121    * Output regions data as a string. String is in the format:
122    * reg0[0]<between>reg0[1]<delimiter>reg1[0]<between>reg1[1] ... regn[1]
123    * 
124    * @param delimiter
125    *          string to delimit regions
126    * @param betweenstring
127    *          to put between start and end region values
128    * @return regions formatted according to delimiter and between strings
129    */
130   public String regionsToString(String delimiter, String between)
131   {
132     try
133     {
134       LOCK.readLock().lock();
135       StringBuilder regionBuilder = new StringBuilder();
136       if (hiddenColumns != null)
137       {
138         Iterator<int[]> it = hiddenColumns.iterator();
139         while (it.hasNext())
140         {
141           int[] range = it.next();
142           regionBuilder.append(delimiter).append(range[0]).append(between)
143                   .append(range[1]);
144           if (!it.hasNext())
145           {
146             regionBuilder.deleteCharAt(0);
147           }
148         }
149       }
150       return regionBuilder.toString();
151     } finally
152     {
153       LOCK.readLock().unlock();
154     }
155   }
156
157   /**
158    * Find the number of hidden columns
159    * 
160    * @return number of hidden columns
161    */
162   public int getSize()
163   {
164     try
165     {
166       LOCK.readLock().lock();
167       int size = 0;
168       if (hiddenColumns != null)
169       {
170         Iterator<int[]> it = hiddenColumns.iterator();
171         while (it.hasNext())
172         {
173           int[] range = it.next();
174           size += range[1] - range[0] + 1;
175         }
176       }
177       return size;
178     } finally
179     {
180       LOCK.readLock().unlock();
181     }
182   }
183
184   /**
185    * Get the number of distinct hidden regions
186    * 
187    * @return number of regions
188    */
189   public int getNumberOfRegions()
190   {
191     try
192     {
193       LOCK.readLock().lock();
194       int num = 0;
195       if (hasHiddenColumns())
196       {
197         num = hiddenColumns.size();
198       }
199       return num;
200     } finally
201     {
202       LOCK.readLock().unlock();
203     }
204   }
205
206   @Override
207   public boolean equals(Object obj)
208   {
209     try
210     {
211       LOCK.readLock().lock();
212
213       if (!(obj instanceof HiddenColumns))
214       {
215         return false;
216       }
217       HiddenColumns that = (HiddenColumns) obj;
218
219       /*
220        * check hidden columns are either both null, or match
221        */
222       if (this.hiddenColumns == null)
223       {
224         return (that.hiddenColumns == null);
225       }
226       if (that.hiddenColumns == null
227               || that.hiddenColumns.size() != this.hiddenColumns.size())
228       {
229         return false;
230       }
231
232       Iterator<int[]> it = hiddenColumns.iterator();
233       Iterator<int[]> thatit = that.iterator();
234       while (it.hasNext())
235       {
236         int[] thisRange = it.next();
237         int[] thatRange = thatit.next();
238         if (thisRange[0] != thatRange[0] || thisRange[1] != thatRange[1])
239         {
240           return false;
241         }
242       }
243       return true;
244     } finally
245     {
246       LOCK.readLock().unlock();
247     }
248   }
249
250   /**
251    * Return absolute column index for a visible column index
252    * 
253    * @param column
254    *          int column index in alignment view (count from zero)
255    * @return alignment column index for column
256    */
257   public int adjustForHiddenColumns(int column)
258   {
259     try
260     {
261       LOCK.readLock().lock();
262       int result = column;
263
264       if (hiddenColumns != null)
265       {
266         Iterator<int[]> it = hiddenColumns.iterator();
267         while (it.hasNext())
268         {
269           int[] region = it.next();
270           if (result >= region[0])
271           {
272             result += region[1] - region[0] + 1;
273           }
274         }
275       }
276
277       return result;
278     } finally
279     {
280       LOCK.readLock().unlock();
281     }
282   }
283
284   /**
285    * Use this method to find out where a column will appear in the visible
286    * alignment when hidden columns exist. If the column is not visible, then the
287    * left-most visible column will always be returned.
288    * 
289    * @param hiddenColumn
290    *          the column index in the full alignment including hidden columns
291    * @return the position of the column in the visible alignment
292    */
293   public int findColumnPosition(int hiddenColumn)
294   {
295     try
296     {
297       LOCK.readLock().lock();
298       int result = hiddenColumn;
299       int[] region = null;
300       if (hiddenColumns != null)
301       {
302         Iterator<int[]> it = new RegionsIterator(0,
303                 hiddenColumn);
304         while (it.hasNext())
305         {
306           region = it.next();
307           if (hiddenColumn > region[1])
308           {
309             result -= region[1] + 1 - region[0];
310           }
311         }
312
313         if (region != null && hiddenColumn >= region[0]
314                 && hiddenColumn <= region[1])
315         {
316           // Here the hidden column is within a region, so
317           // we want to return the position of region[0]-1, adjusted for any
318           // earlier hidden columns.
319           // Calculate the difference between the actual hidden col position
320           // and region[0]-1, and then subtract from result to convert result
321           // from the adjusted hiddenColumn value to the adjusted region[0]-1
322           // value.
323
324           // However, if the region begins at 0 we cannot return region[0]-1
325           // just return 0
326           if (region[0] == 0)
327           {
328             return 0;
329           }
330           else
331           {
332             return result - (hiddenColumn - region[0] + 1);
333           }
334         }
335       }
336       return result; // return the shifted position after removing hidden
337                      // columns.
338     } finally
339     {
340       LOCK.readLock().unlock();
341     }
342   }
343
344   /**
345    * Find the visible column which is a given visible number of columns to the
346    * left of another visible column. i.e. for a startColumn x, the column which
347    * is distance 1 away will be column x-1.
348    * 
349    * @param visibleDistance
350    *          the number of visible columns to offset by
351    * @param startColumn
352    *          the column to start from
353    * @return the position of the column in the visible alignment
354    */
355   public int subtractVisibleColumns(int visibleDistance, int startColumn)
356   {
357     try
358     {
359       LOCK.readLock().lock();
360       int distance = visibleDistance;
361
362       // in case startColumn is in a hidden region, move it to the left
363       int start = adjustForHiddenColumns(findColumnPosition(startColumn));
364
365       Iterator<int[]> it = new ReverseRegionsIterator(0, start);
366
367       while (it.hasNext() && (distance > 0))
368       {
369         int[] region = it.next();
370
371         if (start > region[1])
372         {
373           // subtract the gap to right of region from distance
374           if (start - region[1] <= distance)
375           {
376             distance -= start - region[1];
377             start = region[0] - 1;
378           }
379           else
380           {
381             start = start - distance;
382             distance = 0;
383           }
384         }
385       }
386
387       return start - distance;
388
389     } finally
390     {
391       LOCK.readLock().unlock();
392     }
393   }
394
395   /**
396    * This method returns the rightmost limit of a region of an alignment with
397    * hidden columns. In otherwords, the next hidden column.
398    * 
399    * @param alPos
400    *          the (visible) alignmentPosition to find the next hidden column for
401    */
402   public int getHiddenBoundaryRight(int alPos)
403   {
404     try
405     {
406       LOCK.readLock().lock();
407       if (hiddenColumns != null)
408       {
409         Iterator<int[]> it = hiddenColumns.iterator();
410         while (it.hasNext())
411         {
412           int[] region = it.next();
413           if (alPos < region[0])
414           {
415             return region[0];
416           }
417         }
418       }
419       return alPos;
420     } finally
421     {
422       LOCK.readLock().unlock();
423     }
424   }
425
426   /**
427    * This method returns the leftmost limit of a region of an alignment with
428    * hidden columns. In otherwords, the previous hidden column.
429    * 
430    * @param alPos
431    *          the (visible) alignmentPosition to find the previous hidden column
432    *          for
433    */
434   public int getHiddenBoundaryLeft(int alPos)
435   {
436     try
437     {
438       LOCK.readLock().lock();
439
440       Iterator<int[]> it = new ReverseRegionsIterator(0, alPos);
441       while (it.hasNext())
442       {
443         int[] region = it.next();
444         if (alPos > region[1])
445         {
446           return region[1];
447         }
448       }
449
450       return alPos;
451     } finally
452     {
453       LOCK.readLock().unlock();
454     }
455   }
456
457   /**
458    * Adds the specified column range to the hidden columns collection
459    * 
460    * @param start
461    *          start of range to add (absolute position in alignment)
462    * @param end
463    *          end of range to add (absolute position in alignment)
464    */
465   public void hideColumns(int start, int end)
466   {
467     boolean wasAlreadyLocked = false;
468     try
469     {
470       // check if the write lock was already locked by this thread,
471       // as this method can be called internally in loops within HiddenColumns
472       if (!LOCK.isWriteLockedByCurrentThread())
473       {
474         LOCK.writeLock().lock();
475       }
476       else
477       {
478         wasAlreadyLocked = true;
479       }
480
481       if (hiddenColumns == null)
482       {
483         hiddenColumns = new ArrayList<>();
484       }
485
486       /*
487        * new range follows everything else; check first to avoid looping over whole hiddenColumns collection
488        */
489       if (hiddenColumns.isEmpty()
490               || start > hiddenColumns.get(hiddenColumns.size() - 1)[1])
491       {
492         hiddenColumns.add(new int[] { start, end });
493       }
494       else
495       {
496         /*
497          * traverse existing hidden ranges and insert / amend / append as
498          * appropriate
499          */
500         boolean added = false;
501         for (int i = 0; !added && i < hiddenColumns.size(); i++)
502         {
503           added = insertRangeAtRegion(i, start, end);
504         } // for
505       }
506     } finally
507     {
508       if (!wasAlreadyLocked)
509       {
510         LOCK.writeLock().unlock();
511       }
512     }
513   }
514
515   /**
516    * Insert [start, range] at the region at index i in hiddenColumns, if
517    * feasible
518    * 
519    * @param i
520    *          index to insert at
521    * @param start
522    *          start of range to insert
523    * @param end
524    *          end of range to insert
525    * @return true if range was successfully inserted
526    */
527   private boolean insertRangeAtRegion(int i, int start, int end)
528   {
529     boolean added = false;
530
531     int[] region = hiddenColumns.get(i);
532     if (end < region[0] - 1)
533     {
534       /*
535        * insert discontiguous preceding range
536        */
537       hiddenColumns.add(i, new int[] { start, end });
538       added = true;
539     }
540     else if (end <= region[1])
541     {
542       /*
543        * new range overlaps existing, or is contiguous preceding it - adjust
544        * start column
545        */
546       region[0] = Math.min(region[0], start);
547       added = true;
548     }
549     else if (start <= region[1] + 1)
550     {
551       /*
552        * new range overlaps existing, or is contiguous following it - adjust
553        * start and end columns
554        */
555       region[0] = Math.min(region[0], start);
556       region[1] = Math.max(region[1], end);
557
558       /*
559        * also update or remove any subsequent ranges 
560        * that are overlapped
561        */
562       while (i < hiddenColumns.size() - 1)
563       {
564         int[] nextRegion = hiddenColumns.get(i + 1);
565         if (nextRegion[0] > end + 1)
566         {
567           /*
568            * gap to next hidden range - no more to update
569            */
570           break;
571         }
572         region[1] = Math.max(nextRegion[1], end);
573         hiddenColumns.subList(i + 1, i + 2).clear();
574       }
575       added = true;
576     }
577     return added;
578   }
579
580   /**
581    * Answers if a column in the alignment is visible
582    * 
583    * @param column
584    *          absolute position of column in the alignment
585    * @return true if column is visible
586    */
587   public boolean isVisible(int column)
588   {
589     try
590     {
591       LOCK.readLock().lock();
592
593       Iterator<int[]> it = new RegionsIterator(column, column);
594       while (it.hasNext())
595       {
596         int[] region = it.next();
597         if (column >= region[0] && column <= region[1])
598         {
599           return false;
600         }
601       }
602
603       return true;
604     } finally
605     {
606       LOCK.readLock().unlock();
607     }
608   }
609
610   /**
611    * Get the visible sections of a set of sequences
612    * 
613    * @param start
614    *          sequence position to start from
615    * @param end
616    *          sequence position to end at
617    * @param seqs
618    *          an array of sequences
619    * @return an array of strings encoding the visible parts of each sequence
620    */
621   public String[] getVisibleSequenceStrings(int start, int end,
622           SequenceI[] seqs)
623   {
624     try
625     {
626       LOCK.readLock().lock();
627       int iSize = seqs.length;
628       String[] selections = new String[iSize];
629       if (hiddenColumns != null && hiddenColumns.size() > 0)
630       {
631         for (int i = 0; i < iSize; i++)
632         {
633           StringBuffer visibleSeq = new StringBuffer();
634
635           Iterator<int[]> blocks = new VisibleContigsIterator(start,
636                   end + 1, false);
637
638           while (blocks.hasNext())
639           {
640             int[] block = blocks.next();
641             if (blocks.hasNext())
642             {
643               visibleSeq
644                       .append(seqs[i].getSequence(block[0], block[1] + 1));
645             }
646             else
647             {
648               visibleSeq
649                       .append(seqs[i].getSequence(block[0], block[1]));
650             }
651           }
652
653           selections[i] = visibleSeq.toString();
654         }
655       }
656       else
657       {
658         for (int i = 0; i < iSize; i++)
659         {
660           selections[i] = seqs[i].getSequenceAsString(start, end);
661         }
662       }
663
664       return selections;
665     } finally
666     {
667       LOCK.readLock().unlock();
668     }
669   }
670
671   /**
672    * Locate the first position visible for this sequence. If seq isn't visible
673    * then return the position of the left side of the hidden boundary region.
674    * 
675    * @param seq
676    *          sequence to find position for
677    * @return visible start position
678    */
679   public int locateVisibleStartOfSequence(SequenceI seq)
680   {
681     try
682     {
683       LOCK.readLock().lock();
684       int start = 0;
685
686       if (hiddenColumns == null || hiddenColumns.size() == 0)
687       {
688         return seq.findIndex(seq.getStart()) - 1;
689       }
690
691       // Simply walk along the sequence whilst watching for hidden column
692       // boundaries
693       Iterator<int[]> regions = hiddenColumns.iterator();
694       int hideStart = seq.getLength();
695       int hideEnd = -1;
696       int visPrev = 0;
697       int visNext = 0;
698       boolean foundStart = false;
699
700       // step through the non-gapped positions of the sequence
701       for (int i = seq.getStart(); i <= seq.getEnd() && (!foundStart); i++)
702       {
703         // get alignment position of this residue in the sequence
704         int p = seq.findIndex(i) - 1;
705
706         // update hidden region start/end
707         while (hideEnd < p && regions.hasNext())
708         {
709           int[] region = regions.next();
710           visPrev = visNext;
711           visNext += region[0] - visPrev;
712           hideStart = region[0];
713           hideEnd = region[1];
714         }
715         if (hideEnd < p)
716         {
717           hideStart = seq.getLength();
718         }
719         // update visible boundary for sequence
720         if (p < hideStart)
721         {
722           start = p;
723           foundStart = true;
724         }
725       }
726
727       if (foundStart)
728       {
729         return findColumnPosition(start);
730       }
731       // otherwise, sequence was completely hidden
732       return visPrev;
733     } finally
734     {
735       LOCK.readLock().unlock();
736     }
737   }
738
739   /**
740    * delete any columns in alignmentAnnotation that are hidden (including
741    * sequence associated annotation).
742    * 
743    * @param alignmentAnnotation
744    */
745   public void makeVisibleAnnotation(AlignmentAnnotation alignmentAnnotation)
746   {
747     makeVisibleAnnotation(0, alignmentAnnotation.annotations.length,
748             alignmentAnnotation);
749   }
750
751   /**
752    * delete any columns in alignmentAnnotation that are hidden (including
753    * sequence associated annotation).
754    * 
755    * @param start
756    *          remove any annotation to the right of this column
757    * @param end
758    *          remove any annotation to the left of this column
759    * @param alignmentAnnotation
760    *          the annotation to operate on
761    */
762   public void makeVisibleAnnotation(int start, int end,
763           AlignmentAnnotation alignmentAnnotation)
764   {
765     try
766     {
767       LOCK.readLock().lock();
768
769       int startFrom = start;
770       int endAt = end;
771
772       if (alignmentAnnotation.annotations != null)
773       {
774         if (hiddenColumns != null && hiddenColumns.size() > 0)
775         {
776           removeHiddenAnnotation(startFrom, endAt, alignmentAnnotation);
777         }
778         else
779         {
780           alignmentAnnotation.restrict(startFrom, endAt);
781         }
782       }
783     } finally
784     {
785       LOCK.readLock().unlock();
786     }
787   }
788
789   private void removeHiddenAnnotation(int start, int end,
790           AlignmentAnnotation alignmentAnnotation)
791   {
792     // mangle the alignmentAnnotation annotation array
793     ArrayList<Annotation[]> annels = new ArrayList<>();
794     Annotation[] els = null;
795
796     int w = 0;
797     
798     Iterator<int[]> blocks = new VisibleContigsIterator(start, end + 1,
799             false);
800
801     int copylength;
802     int annotationLength;
803     while (blocks.hasNext())
804     {
805       int[] block = blocks.next();
806       annotationLength = block[1] - block[0] + 1;
807     
808       if (blocks.hasNext())
809       {
810         // copy just the visible segment of the annotation row
811         copylength = annotationLength;
812       }
813       else
814       {
815         if (annotationLength + block[0] <= alignmentAnnotation.annotations.length)
816         {
817           // copy just the visible segment of the annotation row
818           copylength = annotationLength;
819         }
820         else
821         {
822           // copy to the end of the annotation row
823           copylength = alignmentAnnotation.annotations.length - block[0];
824         }
825       }
826       
827       els = new Annotation[annotationLength];
828       annels.add(els);
829       System.arraycopy(alignmentAnnotation.annotations, block[0], els, 0,
830               copylength);
831       w += annotationLength;
832     }
833     
834     if (w != 0)
835     {
836       alignmentAnnotation.annotations = new Annotation[w];
837
838       w = 0;
839       for (Annotation[] chnk : annels)
840       {
841         System.arraycopy(chnk, 0, alignmentAnnotation.annotations, w,
842                 chnk.length);
843         w += chnk.length;
844       }
845     }
846   }
847
848   /**
849    * 
850    * @return true if there are columns hidden
851    */
852   public boolean hasHiddenColumns()
853   {
854     try
855     {
856       LOCK.readLock().lock();
857       return hiddenColumns != null && hiddenColumns.size() > 0;
858     } finally
859     {
860       LOCK.readLock().unlock();
861     }
862   }
863
864   /**
865    * 
866    * @return true if there are more than one set of columns hidden
867    */
868   public boolean hasManyHiddenColumns()
869   {
870     try
871     {
872       LOCK.readLock().lock();
873       return hiddenColumns != null && hiddenColumns.size() > 1;
874     } finally
875     {
876       LOCK.readLock().unlock();
877     }
878   }
879
880   /**
881    * mark the columns corresponding to gap characters as hidden in the column
882    * selection
883    * 
884    * @param sr
885    */
886   public void hideInsertionsFor(SequenceI sr)
887   {
888     try
889     {
890       LOCK.writeLock().lock();
891       List<int[]> inserts = sr.getInsertions();
892       for (int[] r : inserts)
893       {
894         hideColumns(r[0], r[1]);
895       }
896     } finally
897     {
898       LOCK.writeLock().unlock();
899     }
900   }
901
902   /**
903    * Unhides, and adds to the selection list, all hidden columns
904    */
905   public void revealAllHiddenColumns(ColumnSelection sel)
906   {
907     try
908     {
909       LOCK.writeLock().lock();
910       Iterator<int[]> it = hiddenColumns.iterator();
911       while (it.hasNext())
912       {
913         int[] region = it.next();
914         for (int j = region[0]; j < region[1] + 1; j++)
915         {
916           sel.addElement(j);
917         }
918       }
919       hiddenColumns = null;
920     } finally
921     {
922       LOCK.writeLock().unlock();
923     }
924   }
925
926   /**
927    * Reveals, and marks as selected, the hidden column range with the given
928    * start column
929    * 
930    * @param start
931    */
932   public void revealHiddenColumns(int start, ColumnSelection sel)
933   {
934     try
935     {
936       LOCK.writeLock().lock();
937       Iterator<int[]> it = new RegionsIterator(start, start);
938       while (it.hasNext())
939       {
940         int[] region = it.next();
941         if (start == region[0])
942         {
943           for (int j = region[0]; j < region[1] + 1; j++)
944           {
945             sel.addElement(j);
946           }
947           it.remove();
948           break;
949         }
950         else if (start < region[0])
951         {
952           break; // passed all possible matching regions
953         }
954       }
955
956       if (hiddenColumns.size() == 0)
957       {
958         hiddenColumns = null;
959       }
960     } finally
961     {
962       LOCK.writeLock().unlock();
963     }
964   }
965
966   /**
967    * Add gaps into the sequences aligned to profileseq under the given
968    * AlignmentView
969    * 
970    * @param profileseq
971    * @param al
972    *          - alignment to have gaps inserted into it
973    * @param input
974    *          - alignment view where sequence corresponding to profileseq is
975    *          first entry
976    * @return new HiddenColumns for new alignment view, with insertions into
977    *         profileseq marked as hidden.
978    */
979   public static HiddenColumns propagateInsertions(SequenceI profileseq,
980           AlignmentI al, AlignmentView input)
981   {
982     int profsqpos = 0;
983
984     char gc = al.getGapCharacter();
985     Object[] alandhidden = input.getAlignmentAndHiddenColumns(gc);
986     HiddenColumns nview = (HiddenColumns) alandhidden[1];
987     SequenceI origseq = ((SequenceI[]) alandhidden[0])[profsqpos];
988     nview.propagateInsertions(profileseq, al, origseq);
989     return nview;
990   }
991
992   /**
993    * 
994    * @param profileseq
995    *          - sequence in al which corresponds to origseq
996    * @param al
997    *          - alignment which is to have gaps inserted into it
998    * @param origseq
999    *          - sequence corresponding to profileseq which defines gap map for
1000    *          modifying al
1001    */
1002   private void propagateInsertions(SequenceI profileseq, AlignmentI al,
1003           SequenceI origseq)
1004   {
1005     try
1006     {
1007       LOCK.writeLock().lock();
1008
1009       char gc = al.getGapCharacter();
1010
1011       // take the set of hidden columns, and the set of gaps in origseq,
1012       // and remove all the hidden gaps from hiddenColumns
1013
1014       // first get the gaps as a Bitset
1015       BitSet gaps = origseq.gapBitset();
1016
1017       // now calculate hidden ^ not(gap)
1018       BitSet hidden = new BitSet();
1019       markHiddenRegions(hidden);
1020       hidden.andNot(gaps);
1021       hiddenColumns = null;
1022       this.hideMarkedBits(hidden);
1023
1024       // for each sequence in the alignment, except the profile sequence,
1025       // insert gaps corresponding to each hidden region
1026       // but where each hidden column region is shifted backwards by the number
1027       // of
1028       // preceding visible gaps
1029       // update hidden columns at the same time
1030       Iterator<int[]> regions = hiddenColumns.iterator();
1031       ArrayList<int[]> newhidden = new ArrayList<>();
1032
1033       int numGapsBefore = 0;
1034       int gapPosition = 0;
1035       while (regions.hasNext())
1036       {
1037         // get region coordinates accounting for gaps
1038         // we can rely on gaps not being *in* hidden regions because we already
1039         // removed those
1040         int[] region = regions.next();
1041         while (gapPosition < region[0])
1042         {
1043           gapPosition++;
1044           if (gaps.get(gapPosition))
1045           {
1046             numGapsBefore++;
1047           }
1048         }
1049
1050         int left = region[0] - numGapsBefore;
1051         int right = region[1] - numGapsBefore;
1052         newhidden.add(new int[] { left, right });
1053
1054         // make a string with number of gaps = length of hidden region
1055         StringBuffer sb = new StringBuffer();
1056         for (int s = 0; s < right - left + 1; s++)
1057         {
1058           sb.append(gc);
1059         }
1060         padGaps(sb, left, profileseq, al);
1061
1062       }
1063       hiddenColumns = newhidden;
1064     } finally
1065     {
1066       LOCK.writeLock().unlock();
1067     }
1068   }
1069
1070   /**
1071    * Pad gaps in all sequences in alignment except profileseq
1072    * 
1073    * @param sb
1074    *          gap string to insert
1075    * @param left
1076    *          position to insert at
1077    * @param profileseq
1078    *          sequence not to pad
1079    * @param al
1080    *          alignment to pad sequences in
1081    */
1082   private void padGaps(StringBuffer sb, int pos, SequenceI profileseq,
1083           AlignmentI al)
1084   {
1085     // loop over the sequences and pad with gaps where required
1086     for (int s = 0, ns = al.getHeight(); s < ns; s++)
1087     {
1088       SequenceI sqobj = al.getSequenceAt(s);
1089       if (sqobj != profileseq)
1090       {
1091         String sq = al.getSequenceAt(s).getSequenceAsString();
1092         if (sq.length() <= pos)
1093         {
1094           // pad sequence
1095           int diff = pos - sq.length() - 1;
1096           if (diff > 0)
1097           {
1098             // pad gaps
1099             sq = sq + sb;
1100             while ((diff = pos - sq.length() - 1) > 0)
1101             {
1102               if (diff >= sb.length())
1103               {
1104                 sq += sb.toString();
1105               }
1106               else
1107               {
1108                 char[] buf = new char[diff];
1109                 sb.getChars(0, diff, buf, 0);
1110                 sq += buf.toString();
1111               }
1112             }
1113           }
1114           sq += sb.toString();
1115         }
1116         else
1117         {
1118           al.getSequenceAt(s).setSequence(
1119                   sq.substring(0, pos) + sb.toString() + sq.substring(pos));
1120         }
1121       }
1122     }
1123   }
1124
1125   /**
1126    * Returns a hashCode built from hidden column ranges
1127    */
1128   @Override
1129   public int hashCode()
1130   {
1131     try
1132     {
1133       LOCK.readLock().lock();
1134       int hashCode = 1;
1135       Iterator<int[]> it = hiddenColumns.iterator();
1136       while (it.hasNext())
1137       {
1138         int[] hidden = it.next();
1139         hashCode = HASH_MULTIPLIER * hashCode + hidden[0];
1140         hashCode = HASH_MULTIPLIER * hashCode + hidden[1];
1141       }
1142       return hashCode;
1143     } finally
1144     {
1145       LOCK.readLock().unlock();
1146     }
1147   }
1148
1149   /**
1150    * Hide columns corresponding to the marked bits
1151    * 
1152    * @param inserts
1153    *          - columns map to bits starting from zero
1154    */
1155   public void hideMarkedBits(BitSet inserts)
1156   {
1157     try
1158     {
1159       LOCK.writeLock().lock();
1160       for (int firstSet = inserts
1161               .nextSetBit(0), lastSet = 0; firstSet >= 0; firstSet = inserts
1162                       .nextSetBit(lastSet))
1163       {
1164         lastSet = inserts.nextClearBit(firstSet);
1165         hideColumns(firstSet, lastSet - 1);
1166       }
1167     } finally
1168     {
1169       LOCK.writeLock().unlock();
1170     }
1171   }
1172
1173   /**
1174    * 
1175    * @param inserts
1176    *          BitSet where hidden columns will be marked
1177    */
1178   public void markHiddenRegions(BitSet inserts)
1179   {
1180     try
1181     {
1182       LOCK.readLock().lock();
1183       if (hiddenColumns == null)
1184       {
1185         return;
1186       }
1187       Iterator<int[]> it = hiddenColumns.iterator();
1188       while (it.hasNext())
1189       {
1190         int[] range = it.next();
1191         inserts.set(range[0], range[1] + 1);
1192       }
1193     } finally
1194     {
1195       LOCK.readLock().unlock();
1196     }
1197   }
1198
1199   /**
1200    * Calculate the visible start and end index of an alignment.
1201    * 
1202    * @param width
1203    *          full alignment width
1204    * @return integer array where: int[0] = startIndex, and int[1] = endIndex
1205    */
1206   public int[] getVisibleStartAndEndIndex(int width)
1207   {
1208     try
1209     {
1210       LOCK.readLock().lock();
1211       int[] alignmentStartEnd = new int[] { 0, width - 1 };
1212       int startPos = alignmentStartEnd[0];
1213       int endPos = alignmentStartEnd[1];
1214
1215       int[] lowestRange = new int[] { -1, -1 };
1216       int[] higestRange = new int[] { -1, -1 };
1217
1218       if (hiddenColumns == null)
1219       {
1220         return new int[] { startPos, endPos };
1221       }
1222
1223       Iterator<int[]> it = hiddenColumns.iterator();
1224       while (it.hasNext())
1225       {
1226         int[] range = it.next();
1227         lowestRange = (range[0] <= startPos) ? range : lowestRange;
1228         higestRange = (range[1] >= endPos) ? range : higestRange;
1229       }
1230
1231       if (lowestRange[0] == -1 && lowestRange[1] == -1)
1232       {
1233         startPos = alignmentStartEnd[0];
1234       }
1235       else
1236       {
1237         startPos = lowestRange[1] + 1;
1238       }
1239
1240       if (higestRange[0] == -1 && higestRange[1] == -1)
1241       {
1242         endPos = alignmentStartEnd[1];
1243       }
1244       else
1245       {
1246         endPos = higestRange[0] - 1;
1247       }
1248       return new int[] { startPos, endPos };
1249     } finally
1250     {
1251       LOCK.readLock().unlock();
1252     }
1253
1254   }
1255
1256   /**
1257    * Finds the hidden region (if any) which starts or ends at res
1258    * 
1259    * @param res
1260    *          visible residue position, unadjusted for hidden columns
1261    * @return region as [start,end] or null if no matching region is found
1262    */
1263   public int[] getRegionWithEdgeAtRes(int res)
1264   {
1265     try
1266     {
1267       LOCK.readLock().lock();
1268       int adjres = adjustForHiddenColumns(res);
1269
1270       int[] reveal = null;
1271       Iterator<int[]> it = new RegionsIterator(adjres - 2,
1272               adjres + 2);
1273       while (it.hasNext())
1274       {
1275         int[] region = it.next();
1276         if (adjres + 1 == region[0] || adjres - 1 == region[1])
1277         {
1278           reveal = region;
1279           break;
1280         }
1281       }
1282       return reveal;
1283     } finally
1284     {
1285       LOCK.readLock().unlock();
1286     }
1287   }
1288
1289   /**
1290    * Return an iterator over the hidden regions
1291    */
1292   public Iterator<int[]> iterator()
1293   {
1294     return new BoundedHiddenColsIterator();
1295   }
1296
1297   /**
1298    * Return a bounded iterator over the hidden regions
1299    * 
1300    * @param start
1301    *          position to start from (inclusive, absolute column position)
1302    * @param end
1303    *          position to end at (inclusive, absolute column position)
1304    * @return
1305    */
1306   public Iterator<int[]> getBoundedIterator(int start, int end)
1307   {
1308     return new BoundedHiddenColsIterator(start, end);
1309   }
1310
1311   /**
1312    * Return a bounded iterator over the *visible* start positions of hidden
1313    * regions
1314    * 
1315    * @param start
1316    *          position to start from (inclusive, visible column position)
1317    * @param end
1318    *          position to end at (inclusive, visible column position)
1319    */
1320   public Iterator<Integer> getBoundedStartIterator(int start, int end)
1321   {
1322     return new BoundedStartRegionIterator(start, end, true);
1323   }
1324
1325   /**
1326    * Return an iterator over visible *columns* (not regions) between the given
1327    * start and end boundaries
1328    * 
1329    * @param start
1330    *          first column (inclusive)
1331    * @param end
1332    *          last column (inclusive)
1333    */
1334   public Iterator<Integer> getVisibleColsIterator(int start, int end)
1335   {
1336     return new VisibleColsIterator(start, end);
1337   }
1338
1339   /**
1340    * return an iterator over visible segments between the given start and end
1341    * boundaries
1342    * 
1343    * @param start
1344    *          (first column inclusive from 0)
1345    * @param end
1346    *          (last column - not inclusive)
1347    */
1348   public Iterator<int[]> getVisContigsIterator(int start, int end)
1349   {
1350     // return new VisibleBlocksIterator(start, end, true)
1351     return new VisibleContigsIterator(start, end, true);
1352   }
1353
1354   /**
1355    * return an iterator over visible segments between the given start and end
1356    * boundaries
1357    * 
1358    * @param start
1359    *          (first column - inclusive from 0)
1360    * @param end
1361    *          (last column - inclusive)
1362    * @param useVisibleCoords
1363    *          if true, start and end are visible column positions, not absolute
1364    *          positions
1365    */
1366   public Iterator<int[]> getVisibleBlocksIterator(int start, int end,
1367           boolean useVisibleCoords)
1368   {
1369     if (useVisibleCoords)
1370     {
1371       // TODO
1372       // we should really just convert start and end here with
1373       // adjustForHiddenColumns
1374       // and then create a VisibleContigsIterator
1375       // but without a cursor this will be horribly slow in some situations
1376       // ... so until then...
1377       return new VisibleBlocksVisBoundsIterator(start, end, true);
1378     }
1379     else
1380     {
1381       return new VisibleContigsIterator(start, end + 1, true);
1382     }
1383   }
1384
1385   /**
1386    * A local iterator which iterates over hidden column regions in a range.
1387    * Intended for use ONLY within the HiddenColumns class, because it works
1388    * directly with the hiddenColumns collection without locking (callers should
1389    * lock hiddenColumns).
1390    */
1391   private class RegionsIterator implements Iterator<int[]>
1392   {
1393     // start position to iterate from
1394     private int start;
1395
1396     // end position to iterate to
1397     private int end;
1398
1399     // current index in hiddenColumns
1400     private int currentPosition = 0;
1401
1402     // current column in hiddenColumns
1403     private int[] nextRegion = null;
1404
1405     private int[] currentRegion = null;
1406
1407     private int removedIndex = -1;
1408
1409     // Constructor with bounds
1410     RegionsIterator(int lowerBound, int upperBound)
1411     {
1412       start = lowerBound;
1413       end = upperBound;
1414
1415       if (hiddenColumns != null)
1416       {
1417         // iterate until a region overlaps with [start,end]
1418         currentPosition = 0;
1419         while ((currentPosition < hiddenColumns.size())
1420                 && (hiddenColumns.get(currentPosition)[1] < start))
1421         {
1422           currentPosition++;
1423         }
1424         if (currentPosition < hiddenColumns.size())
1425         {
1426           nextRegion = hiddenColumns.get(currentPosition);
1427         }
1428       }
1429     }
1430
1431     @Override
1432     public boolean hasNext()
1433     {
1434       return (hiddenColumns != null) && (nextRegion != null)
1435               && (nextRegion[0] <= end);
1436     }
1437
1438     @Override
1439     public int[] next()
1440     {
1441       currentRegion = nextRegion;
1442       currentPosition++;
1443       if (currentPosition < hiddenColumns.size())
1444       {
1445         nextRegion = hiddenColumns.get(currentPosition);
1446       }
1447       else
1448       {
1449         nextRegion = null;
1450       }
1451       return currentRegion;
1452     }
1453
1454     @Override
1455     public void remove()
1456     {
1457       if ((currentRegion != null) && (removedIndex != currentPosition))
1458       {
1459         currentPosition--;
1460         hiddenColumns.subList(currentPosition, currentPosition + 1).clear();
1461         removedIndex = currentPosition;
1462       }
1463       else
1464       {
1465         // already removed element last returned by next()
1466         // or next() has not yet been called
1467         throw new IllegalStateException();
1468       }
1469     }
1470
1471   }
1472
1473   /**
1474    * A local iterator which reverse iterates over hidden column regions in a
1475    * range. Intended for use ONLY within the HiddenColumns class, because it
1476    * works directly with the hiddenColumns collection without locking (callers
1477    * should lock hiddenColumns).
1478    */
1479   private class ReverseRegionsIterator implements Iterator<int[]>
1480   {
1481     // start position to iterate to
1482     private int start;
1483
1484     // end position to iterate from
1485     private int end;
1486
1487     // current index in hiddenColumns
1488     private int currentPosition = 0;
1489
1490     // current column in hiddenColumns
1491     private int[] nextRegion = null;
1492
1493     // Constructor with bounds
1494     ReverseRegionsIterator(int lowerBound, int upperBound)
1495     {
1496       init(lowerBound, upperBound);
1497     }
1498
1499     /**
1500      * Construct an iterator over hiddenColums bounded at
1501      * [lowerBound,upperBound]
1502      * 
1503      * @param lowerBound
1504      *          lower bound to iterate to
1505      * @param upperBound
1506      *          upper bound to iterate from
1507      */
1508     private void init(int lowerBound, int upperBound)
1509     {
1510       start = lowerBound;
1511       end = upperBound;
1512
1513       if (hiddenColumns != null)
1514       {
1515         // iterate until a region overlaps with [start,end]
1516         currentPosition = hiddenColumns.size() - 1;
1517         while (currentPosition >= 0
1518                 && hiddenColumns.get(currentPosition)[1] > end)
1519         {
1520           currentPosition--;
1521         }
1522         if (currentPosition >= 0)
1523         {
1524           nextRegion = hiddenColumns.get(currentPosition);
1525         }
1526       }
1527     }
1528
1529     @Override
1530     public boolean hasNext()
1531     {
1532       return (hiddenColumns != null) && (nextRegion != null)
1533               && (nextRegion[1] >= start);
1534     }
1535
1536     @Override
1537     public int[] next()
1538     {
1539       int[] region = nextRegion;
1540       currentPosition--;
1541       if (currentPosition >= 0)
1542       {
1543         nextRegion = hiddenColumns.get(currentPosition);
1544       }
1545       else
1546       {
1547         nextRegion = null;
1548       }
1549       return region;
1550     }
1551
1552   }
1553
1554   /**
1555    * An iterator which iterates over hidden column regions in a range. Works
1556    * with a copy of the hidden columns collection. Intended to be used by
1557    * callers OUTSIDE of HiddenColumns.
1558    */
1559   private class BoundedHiddenColsIterator implements Iterator<int[]>
1560   {
1561     // start position to iterate from
1562     private int start;
1563
1564     // end position to iterate to
1565     private int end;
1566
1567     // current index in hiddenColumns
1568     private int currentPosition = 0;
1569
1570     // current column in hiddenColumns
1571     private int[] currentRegion;
1572
1573     // local copy or reference to hiddenColumns
1574     private List<int[]> localHidden;
1575
1576     /**
1577      * Unbounded constructor
1578      */
1579     BoundedHiddenColsIterator()
1580     {
1581       if (hiddenColumns != null)
1582       {
1583         int last = hiddenColumns.get(hiddenColumns.size() - 1)[1];
1584         init(0, last);
1585       }
1586       else
1587       {
1588         init(0, 0);
1589       }
1590     }
1591
1592     /**
1593      * Construct an iterator over hiddenColums bounded at
1594      * [lowerBound,upperBound]
1595      * 
1596      * @param lowerBound
1597      *          lower bound to iterate from
1598      * @param upperBound
1599      *          upper bound to iterate to
1600      */
1601     BoundedHiddenColsIterator(int lowerBound, int upperBound)
1602     {
1603       init(lowerBound, upperBound);
1604     }
1605
1606     /**
1607      * Construct an iterator over hiddenColums bounded at
1608      * [lowerBound,upperBound]
1609      * 
1610      * @param lowerBound
1611      *          lower bound to iterate from
1612      * @param upperBound
1613      *          upper bound to iterate to
1614      */
1615     private void init(int lowerBound, int upperBound)
1616     {
1617       start = lowerBound;
1618       end = upperBound;
1619
1620       try
1621       {
1622         LOCK.readLock().lock();
1623         
1624         if (hiddenColumns != null)
1625         {
1626           localHidden = new ArrayList<>();
1627
1628           // iterate until a region overlaps with [start,end]
1629           int i = 0;
1630           while ((i < hiddenColumns.size())
1631                   && (hiddenColumns.get(i)[1] < start))
1632           {
1633             i++;
1634           }
1635
1636           // iterate from start to end, adding each hidden region. Positions are
1637           // absolute, and all regions which *overlap* [start,end] are added.
1638           while (i < hiddenColumns.size()
1639                   && (hiddenColumns.get(i)[0] <= end))
1640           {
1641             int[] rh = hiddenColumns.get(i);
1642             int[] cp = new int[2];
1643             System.arraycopy(rh, 0, cp, 0, rh.length);
1644             localHidden.add(cp);
1645             i++;
1646           }
1647         }
1648       }
1649       finally
1650       {
1651         LOCK.readLock().unlock();
1652       }
1653     }
1654
1655     @Override
1656     public boolean hasNext()
1657     {
1658       return (localHidden != null)
1659               && (currentPosition < localHidden.size());
1660     }
1661
1662     @Override
1663     public int[] next()
1664     {
1665       currentRegion = localHidden.get(currentPosition);
1666       currentPosition++;
1667       return currentRegion;
1668     }
1669   }
1670
1671   /**
1672    * An iterator which iterates over visible start positions of hidden column
1673    * regions in a range.
1674    */
1675   private class BoundedStartRegionIterator implements Iterator<Integer>
1676   {
1677     // start position to iterate from
1678     private int start;
1679
1680     // end position to iterate to
1681     private int end;
1682
1683     // current index in hiddenColumns
1684     private int currentPosition = 0;
1685
1686     // local copy or reference to hiddenColumns
1687     private List<Integer> positions = null;
1688
1689     /**
1690      * Construct an iterator over hiddenColums bounded at
1691      * [lowerBound,upperBound]
1692      * 
1693      * @param lowerBound
1694      *          lower bound to iterate from
1695      * @param upperBound
1696      *          upper bound to iterate to
1697      * @param useCopyCols
1698      *          whether to make a local copy of hiddenColumns for iteration (set
1699      *          to true if calling from outwith the HiddenColumns class)
1700      */
1701     BoundedStartRegionIterator(int lowerBound, int upperBound,
1702             boolean useCopy)
1703     {
1704       start = lowerBound;
1705       end = upperBound;
1706       
1707       try
1708       {
1709         if (useCopy)
1710         {
1711           // assume that if useCopy is false the calling code has locked
1712           // hiddenColumns
1713           LOCK.readLock().lock();
1714         }
1715
1716         if (hiddenColumns != null)
1717         {
1718           positions = new ArrayList<>(hiddenColumns.size());
1719
1720           // navigate to start, keeping count of hidden columns
1721           int i = 0;
1722           int hiddenSoFar = 0;
1723           while ((i < hiddenColumns.size())
1724                   && (hiddenColumns.get(i)[0] < start + hiddenSoFar))
1725           {
1726             int[] region = hiddenColumns.get(i);
1727             hiddenSoFar += region[1] - region[0] + 1;
1728             i++;
1729           }
1730
1731           // iterate from start to end, adding start positions of each
1732           // hidden region. Positions are visible columns count, not absolute
1733           while (i < hiddenColumns.size()
1734                   && (hiddenColumns.get(i)[0] <= end + hiddenSoFar))
1735           {
1736             int[] region = hiddenColumns.get(i);
1737             positions.add(region[0] - hiddenSoFar);
1738             hiddenSoFar += region[1] - region[0] + 1;
1739             i++;
1740           }
1741         }
1742         else
1743         {
1744           positions = new ArrayList<>();
1745         }
1746       } finally
1747       {
1748         if (useCopy)
1749         {
1750           LOCK.readLock().unlock();
1751         }
1752       }
1753     }
1754
1755     @Override
1756     public boolean hasNext()
1757     {
1758       return (currentPosition < positions.size());
1759     }
1760
1761     /**
1762      * Get next hidden region start position
1763      * 
1764      * @return the start position in *visible* coordinates
1765      */
1766     @Override
1767     public Integer next()
1768     {
1769       int result = positions.get(currentPosition);
1770       currentPosition++;
1771       return result;
1772     }
1773   }
1774
1775   /**
1776    * Iterator over the visible *columns* (not regions) as determined by the set
1777    * of hidden columns. Uses a local copy of hidden columns.
1778    * 
1779    * @author kmourao
1780    *
1781    */
1782   private class VisibleColsIterator implements Iterator<Integer>
1783   {
1784     private int last;
1785
1786     private int current;
1787
1788     private int next;
1789
1790     private List<int[]> localHidden = new ArrayList<>();
1791
1792     private int nexthiddenregion;
1793
1794     VisibleColsIterator(int firstcol, int lastcol)
1795     {
1796       last = lastcol;
1797       current = firstcol;
1798       next = firstcol;
1799       nexthiddenregion = 0;
1800
1801       LOCK.readLock().lock();
1802
1803       if (hiddenColumns != null)
1804       {
1805         int i = 0;
1806         for (i = 0; i < hiddenColumns.size()
1807                 && (current <= hiddenColumns.get(i)[0]); ++i)
1808         {
1809           if (current >= hiddenColumns.get(i)[0]
1810                   && current <= hiddenColumns.get(i)[1])
1811           {
1812             // current is hidden, move to right
1813             current = hiddenColumns.get(i)[1] + 1;
1814             next = current;
1815             nexthiddenregion = i + 1;
1816           }
1817         }
1818
1819         for (i = hiddenColumns.size() - 1; i >= 0
1820                 && (last >= hiddenColumns.get(i)[1]); --i)
1821         {
1822           if (last >= hiddenColumns.get(i)[0]
1823                   && last <= hiddenColumns.get(i)[1])
1824           {
1825             // last is hidden, move to left
1826             last = hiddenColumns.get(i)[0] - 1;
1827           }
1828         }
1829
1830         // make a local copy of the bit we need
1831         i = nexthiddenregion;
1832         while (i < hiddenColumns.size() && hiddenColumns.get(i)[0] <= last)
1833         {
1834           int[] region = new int[] { hiddenColumns.get(i)[0],
1835               hiddenColumns.get(i)[1] };
1836           localHidden.add(region);
1837           i++;
1838         }
1839       }
1840
1841       LOCK.readLock().unlock();
1842     }
1843
1844     @Override
1845     public boolean hasNext()
1846     {
1847       return next <= last;
1848     }
1849
1850     @Override
1851     public Integer next()
1852     {
1853       if (next > last)
1854       {
1855         throw new NoSuchElementException();
1856       }
1857       current = next;
1858       if ((localHidden != null)
1859               && (nexthiddenregion < localHidden.size()))
1860       {
1861         // still some more hidden regions
1862         if (next + 1 < localHidden.get(nexthiddenregion)[0])
1863         {
1864           // next+1 is still before the next hidden region
1865           next++;
1866         }
1867         else if ((next + 1 >= localHidden.get(nexthiddenregion)[0])
1868                 && (next + 1 <= localHidden.get(nexthiddenregion)[1]))
1869         {
1870           // next + 1 is in the next hidden region
1871           next = localHidden.get(nexthiddenregion)[1] + 1;
1872           nexthiddenregion++;
1873         }
1874       }
1875       else
1876       {
1877         // finished with hidden regions, just increment normally
1878         next++;
1879       }
1880       return current;
1881     }
1882
1883     @Override
1884     public void remove()
1885     {
1886       throw new UnsupportedOperationException();
1887     }
1888   }
1889
1890   /**
1891    * An iterator which iterates over visible regions in a range.
1892    */
1893   private class VisibleContigsIterator implements Iterator<int[]>
1894   {
1895     private List<int[]> vcontigs = new ArrayList<>();
1896
1897     private int currentPosition = 0;
1898
1899     VisibleContigsIterator(int start, int end, boolean usecopy)
1900     {
1901       try
1902       {
1903         if (usecopy)
1904         {
1905           LOCK.readLock().lock();
1906         }
1907
1908         if (hiddenColumns != null && hiddenColumns.size() > 0)
1909         {
1910           int vstart = start;
1911           int hideStart;
1912           int hideEnd;
1913
1914           for (int[] region : hiddenColumns)
1915           {
1916             hideStart = region[0];
1917             hideEnd = region[1];
1918
1919             // navigate to start
1920             if (hideEnd < vstart)
1921             {
1922               continue;
1923             }
1924             if (hideStart > vstart)
1925             {
1926               int[] contig = new int[] { vstart, hideStart - 1 };
1927               vcontigs.add(contig);
1928             }
1929             vstart = hideEnd + 1;
1930
1931             // exit if we're past the end
1932             if (vstart >= end)
1933             {
1934               break;
1935             }
1936           }
1937
1938           if (vstart < end)
1939           {
1940             int[] contig = new int[] { vstart, end - 1 };
1941             vcontigs.add(contig);
1942           }
1943         }
1944         else
1945         {
1946           int[] contig = new int[] { start, end - 1 };
1947           vcontigs.add(contig);
1948         }
1949       } finally
1950       {
1951         if (usecopy)
1952         {
1953           LOCK.readLock().unlock();
1954         }
1955       }
1956     }
1957
1958     @Override
1959     public boolean hasNext()
1960     {
1961       return (currentPosition < vcontigs.size());
1962     }
1963
1964     @Override
1965     public int[] next()
1966     {
1967       int[] result = vcontigs.get(currentPosition);
1968       currentPosition++;
1969       return result;
1970     }
1971   }
1972
1973   /**
1974    * An iterator which iterates over visible regions in a range. The range is
1975    * specified in terms of visible column positions. Provides a special
1976    * "endsAtHidden" indicator to allow callers to determine if the final visible
1977    * column is adjacent to a hidden region.
1978    */
1979   public class VisibleBlocksVisBoundsIterator implements Iterator<int[]>
1980   {
1981     private List<int[]> vcontigs = new ArrayList<>();
1982
1983     private int currentPosition = 0;
1984
1985     private boolean endsAtHidden = false;
1986
1987     /**
1988      * Constructor for iterator over visible regions in a range.
1989      * 
1990      * @param start
1991      *          start position in terms of visible column position
1992      * @param end
1993      *          end position in terms of visible column position
1994      * @param usecopy
1995      *          whether to use a local copy of hidden columns
1996      */
1997     VisibleBlocksVisBoundsIterator(int start, int end, boolean usecopy)
1998     {
1999       /* actually this implementation always uses a local copy but this may change in future */
2000       try
2001       {
2002         if (usecopy)
2003         {
2004           LOCK.readLock().lock();
2005         }
2006
2007         if (hiddenColumns != null && hiddenColumns.size() > 0)
2008         {
2009           int blockStart = start;
2010           int blockEnd = end;
2011           int hiddenSoFar = 0;
2012           int visSoFar = 0;
2013
2014           // iterate until a region begins within (start,end]
2015           int i = 0;
2016           while ((i < hiddenColumns.size())
2017                   && (hiddenColumns.get(i)[0] <= blockStart + hiddenSoFar))
2018           {
2019             hiddenSoFar += hiddenColumns.get(i)[1] - hiddenColumns.get(i)[0]
2020                     + 1;
2021             i++;
2022           }
2023
2024           blockStart += hiddenSoFar; // convert start to absolute position
2025           blockEnd += hiddenSoFar; // convert end to absolute position
2026
2027           // iterate from start to end, adding each visible region. Positions
2028           // are
2029           // absolute, and all hidden regions which overlap [start,end] are
2030           // used.
2031           while (i < hiddenColumns.size()
2032                   && (hiddenColumns.get(i)[0] <= blockEnd))
2033           {
2034             int[] region = hiddenColumns.get(i);
2035
2036             // end position of this visible region is either just before the
2037             // start of the next hidden region, or the absolute position of
2038             // 'end', whichever is lowest
2039             blockEnd = Math.min(blockEnd, region[0] - 1);
2040
2041             vcontigs.add(new int[] { blockStart, blockEnd });
2042
2043             visSoFar += blockEnd - blockStart + 1;
2044
2045             // next visible region starts after this hidden region
2046             blockStart = region[1] + 1;
2047
2048             hiddenSoFar += region[1] - region[0] + 1;
2049
2050             // reset blockEnd to absolute position of 'end', assuming we've now
2051             // passed all hidden regions before end
2052             blockEnd = end + hiddenSoFar;
2053
2054             i++;
2055           }
2056           if (visSoFar < end - start)
2057           {
2058             // the number of visible columns we've accounted for is less than
2059             // the number specified by end-start; work out the end position of
2060             // the last visible region
2061             blockEnd = blockStart + end - start - visSoFar;
2062             vcontigs.add(new int[] { blockStart, blockEnd });
2063
2064             // if the last visible region ends at the next hidden region, set
2065             // endsAtHidden=true
2066             if (i < hiddenColumns.size()
2067                     && hiddenColumns.get(i)[0] - 1 == blockEnd)
2068             {
2069               endsAtHidden = true;
2070             }
2071           }
2072         }
2073         else
2074         {
2075           // there are no hidden columns, return a single visible contig
2076           vcontigs.add(new int[] { start, end });
2077           endsAtHidden = false;
2078         }
2079       } finally
2080       {
2081         if (usecopy)
2082         {
2083           LOCK.readLock().unlock();
2084         }
2085       }
2086     }
2087
2088     @Override
2089     public boolean hasNext()
2090     {
2091       return (currentPosition < vcontigs.size());
2092     }
2093
2094     @Override
2095     public int[] next()
2096     {
2097       int[] result = vcontigs.get(currentPosition);
2098       currentPosition++;
2099       return result;
2100     }
2101
2102     public boolean endsAtHidden()
2103     {
2104       return endsAtHidden;
2105     }
2106   }
2107 }