JAL-2674 Rewrote propagateInsertions
[jalview.git] / src / jalview / datamodel / HiddenColumns.java
index be10721..fe2907d 100644 (file)
@@ -21,7 +21,6 @@
 package jalview.datamodel;
 
 import jalview.util.Comparison;
-import jalview.util.ShiftList;
 
 import java.util.ArrayList;
 import java.util.BitSet;
@@ -33,19 +32,51 @@ import java.util.concurrent.locks.ReentrantReadWriteLock;
 public class HiddenColumns
 {
   private static final ReentrantReadWriteLock LOCK = new ReentrantReadWriteLock();
-  
+
   /*
    * list of hidden column [start, end] ranges; the list is maintained in
    * ascending start column order
    */
-  private Vector<int[]> hiddenColumns;
+  private ArrayList<int[]> hiddenColumns;
 
   /**
-   * This Method is used to return all the HiddenColumn regions
+   * Constructor
+   */
+  public HiddenColumns()
+  {
+  }
+
+  /**
+   * Copy constructor
+   * 
+   * @param copy
+   */
+  public HiddenColumns(HiddenColumns copy)
+  {
+    try
+    {
+      LOCK.writeLock().lock();
+      if (copy != null)
+      {
+        if (copy.hiddenColumns != null)
+        {
+          hiddenColumns = copy.copyHiddenRegionsToArrayList();
+        }
+      }
+    } finally
+    {
+      LOCK.writeLock().unlock();
+    }
+  }
+
+  /**
+   * This method is used to return all the HiddenColumn regions and is intended
+   * to remain private. External callers which need a copy of the regions can
+   * call getHiddenColumnsCopyAsList.
    * 
    * @return empty list or List of hidden column intervals
    */
-  public List<int[]> getHiddenRegions()
+  private List<int[]> getHiddenRegions()
   {
     return hiddenColumns == null ? Collections.<int[]> emptyList()
             : hiddenColumns;
@@ -67,13 +98,16 @@ public class HiddenColumns
     {
       LOCK.readLock().lock();
       StringBuilder regionBuilder = new StringBuilder();
-      for (int[] range : hiddenColumns)
+      if (hiddenColumns != null)
       {
-        regionBuilder.append(delimiter).append(range[0]).append(between)
-                .append(range[1]);
-      }
+        for (int[] range : hiddenColumns)
+        {
+          regionBuilder.append(delimiter).append(range[0]).append(between)
+                  .append(range[1]);
+        }
 
-      regionBuilder.deleteCharAt(0);
+        regionBuilder.deleteCharAt(0);
+      }
       return regionBuilder.toString();
     } finally
     {
@@ -92,7 +126,7 @@ public class HiddenColumns
     {
       LOCK.readLock().lock();
       int size = 0;
-      if (hasHidden())
+      if (hasHiddenColumns())
       {
         for (int[] range : hiddenColumns)
         {
@@ -100,29 +134,10 @@ public class HiddenColumns
         }
       }
       return size;
-    }
-    finally
-    {
-      LOCK.readLock().unlock();
-    }
-  }
-
-  /**
-   * Answers if there are any hidden columns
-   * 
-   * @return true if there are hidden columns
-   */
-  public boolean hasHidden()
-  {
-    try
-    {
-      LOCK.readLock().lock();
-      return (hiddenColumns != null) && (!hiddenColumns.isEmpty());
     } finally
     {
       LOCK.readLock().unlock();
     }
-
   }
 
   @Override
@@ -183,7 +198,7 @@ public class HiddenColumns
       {
         for (int i = 0; i < hiddenColumns.size(); i++)
         {
-          int[] region = hiddenColumns.elementAt(i);
+          int[] region = hiddenColumns.get(i);
           if (result >= region[0])
           {
             result += region[1] - region[0] + 1;
@@ -218,7 +233,7 @@ public class HiddenColumns
         int[] region;
         do
         {
-          region = hiddenColumns.elementAt(index++);
+          region = hiddenColumns.get(index++);
           if (hiddenColumn > region[1])
           {
             result -= region[1] + 1 - region[0];
@@ -273,47 +288,47 @@ public class HiddenColumns
     {
 
       LOCK.readLock().lock();
-    int distance = visibleDistance;
+      int distance = visibleDistance;
 
-    // in case startColumn is in a hidden region, move it to the left
-    int start = adjustForHiddenColumns(findColumnPosition(startColumn));
+      // in case startColumn is in a hidden region, move it to the left
+      int start = adjustForHiddenColumns(findColumnPosition(startColumn));
 
-    // get index of hidden region to left of start
-    int index = getHiddenIndexLeft(start);
-    if (index == -1)
-    {
-      // no hidden regions to left of startColumn
-      return start - distance;
-    }
+      // get index of hidden region to left of start
+      int index = getHiddenIndexLeft(start);
+      if (index == -1)
+      {
+        // no hidden regions to left of startColumn
+        return start - distance;
+      }
 
-    // walk backwards through the alignment subtracting the counts of visible
-    // columns from distance
-    int[] region;
-    int gap = 0;
-    int nextstart = start;
+      // walk backwards through the alignment subtracting the counts of visible
+      // columns from distance
+      int[] region;
+      int gap = 0;
+      int nextstart = start;
 
-    while ((index > -1) && (distance - gap > 0))
-    {
-      // subtract the gap to right of region from distance
-      distance -= gap;
-      start = nextstart;
+      while ((index > -1) && (distance - gap > 0))
+      {
+        // subtract the gap to right of region from distance
+        distance -= gap;
+        start = nextstart;
 
-      // calculate the next gap
-      region = hiddenColumns.get(index);
-      gap = start - region[1];
+        // calculate the next gap
+        region = hiddenColumns.get(index);
+        gap = start - region[1];
 
-      // set start to just to left of current region
-      nextstart = region[0] - 1;
-      index--;
-    }
+        // set start to just to left of current region
+        nextstart = region[0] - 1;
+        index--;
+      }
 
-    if (distance - gap > 0)
-    {
-      // fell out of loop because there are no more hidden regions
-      distance -= gap;
-      return nextstart - distance;
-    }
-    return start - distance;
+      if (distance - gap > 0)
+      {
+        // fell out of loop because there are no more hidden regions
+        distance -= gap;
+        return nextstart - distance;
+      }
+      return start - distance;
     } finally
     {
       LOCK.readLock().unlock();
@@ -331,34 +346,41 @@ public class HiddenColumns
     try
     {
       LOCK.readLock().lock();
-      List<Integer> positions = new ArrayList<>(
-              hiddenColumns.size());
+      List<Integer> positions = null;
 
-      positions.add(hiddenColumns.elementAt(0)[0]);
-      for (int i = 1; i < hiddenColumns.size(); ++i)
+      if (hiddenColumns != null)
       {
+        positions = new ArrayList<>(hiddenColumns.size());
 
-        int result = 0;
-        if (hiddenColumns != null)
+        positions.add(hiddenColumns.get(0)[0]);
+        for (int i = 1; i < hiddenColumns.size(); ++i)
         {
-          int index = 0;
-          int gaps = 0;
-          do
+
+          int result = 0;
+          if (hiddenColumns != null)
           {
-            int[] region = hiddenColumns.elementAt(index);
-            gaps += region[1] + 1 - region[0];
-            result = region[1] + 1;
-            index++;
-          } while (index <= i);
+            int index = 0;
+            int gaps = 0;
+            do
+            {
+              int[] region = hiddenColumns.get(index);
+              gaps += region[1] + 1 - region[0];
+              result = region[1] + 1;
+              index++;
+            } while (index <= i);
 
-          result -= gaps;
+            result -= gaps;
+          }
+          positions.add(result);
         }
-        positions.add(result);
+      }
+      else
+      {
+        positions = new ArrayList<>();
       }
 
       return positions;
-    }
-    finally
+    } finally
     {
       LOCK.readLock().unlock();
     }
@@ -381,7 +403,7 @@ public class HiddenColumns
         int index = 0;
         do
         {
-          int[] region = hiddenColumns.elementAt(index);
+          int[] region = hiddenColumns.get(index);
           if (alPos < region[0])
           {
             return region[0];
@@ -412,22 +434,22 @@ public class HiddenColumns
     {
       LOCK.readLock().lock();
 
-    if (hiddenColumns != null)
-    {
-      int index = hiddenColumns.size() - 1;
-      do
+      if (hiddenColumns != null)
       {
-        int[] region = hiddenColumns.elementAt(index);
-        if (alPos > region[1])
+        int index = hiddenColumns.size() - 1;
+        do
         {
-          return region[1];
-        }
+          int[] region = hiddenColumns.get(index);
+          if (alPos > region[1])
+          {
+            return region[1];
+          }
 
-        index--;
-      } while (index > -1);
-    }
+          index--;
+        } while (index > -1);
+      }
 
-    return alPos;
+      return alPos;
     } finally
     {
       LOCK.readLock().unlock();
@@ -448,22 +470,22 @@ public class HiddenColumns
     {
 
       LOCK.readLock().lock();
-    if (hiddenColumns != null)
-    {
-      int index = hiddenColumns.size() - 1;
-      do
+      if (hiddenColumns != null)
       {
-        int[] region = hiddenColumns.elementAt(index);
-        if (pos > region[1])
+        int index = hiddenColumns.size() - 1;
+        do
         {
-          return index;
-        }
+          int[] region = hiddenColumns.get(index);
+          if (pos > region[1])
+          {
+            return index;
+          }
 
-        index--;
-      } while (index > -1);
-    }
+          index--;
+        } while (index > -1);
+      }
 
-    return -1;
+      return -1;
     } finally
     {
       LOCK.readLock().unlock();
@@ -479,28 +501,23 @@ public class HiddenColumns
    */
   public void hideColumns(int start, int end)
   {
-    hideColumns(start, end, false);
-  }
-
-  /**
-   * Adds the specified column range to the hidden columns
-   * 
-   * @param start
-   * @param end
-   */
-  private void hideColumns(int start, int end, boolean alreadyLocked)
-  {
+    boolean wasAlreadyLocked = false;
     try
     {
-
-      if (!alreadyLocked)
+      // check if the write lock was already locked by this thread,
+      // as this method can be called internally in loops within HiddenColumns
+      if (!LOCK.isWriteLockedByCurrentThread())
       {
         LOCK.writeLock().lock();
       }
+      else
+      {
+        wasAlreadyLocked = true;
+      }
 
       if (hiddenColumns == null)
       {
-        hiddenColumns = new Vector<>();
+        hiddenColumns = new ArrayList<>();
       }
 
       /*
@@ -509,14 +526,14 @@ public class HiddenColumns
        */
       for (int i = 0; i < hiddenColumns.size(); i++)
       {
-        int[] region = hiddenColumns.elementAt(i);
+        int[] region = hiddenColumns.get(i);
 
         if (end < region[0] - 1)
         {
           /*
            * insert discontiguous preceding range
            */
-          hiddenColumns.insertElementAt(new int[] { start, end }, i);
+          hiddenColumns.add(i, new int[] { start, end });
           return;
         }
 
@@ -558,15 +575,15 @@ public class HiddenColumns
           }
           return;
         }
-    }
+      }
 
-    /*
-     * remaining case is that the new range follows everything else
-     */
-    hiddenColumns.addElement(new int[] { start, end });
+      /*
+       * remaining case is that the new range follows everything else
+       */
+      hiddenColumns.add(new int[] { start, end });
     } finally
     {
-      if (!alreadyLocked)
+      if (!wasAlreadyLocked)
       {
         LOCK.writeLock().unlock();
       }
@@ -579,82 +596,38 @@ public class HiddenColumns
     {
       LOCK.readLock().lock();
 
-    if (hiddenColumns != null)
-    {
-      for (int[] region : hiddenColumns)
+      if (hiddenColumns != null)
       {
-        if (column >= region[0] && column <= region[1])
+        for (int[] region : hiddenColumns)
         {
-          return false;
+          if (column >= region[0] && column <= region[1])
+          {
+            return false;
+          }
         }
       }
-    }
 
-    return true;
+      return true;
     } finally
     {
       LOCK.readLock().unlock();
     }
   }
 
-  /**
-   * ColumnSelection
-   */
-  public HiddenColumns()
-  {
-  }
-
-  /**
-   * Copy constructor
-   * 
-   * @param copy
-   */
-  public HiddenColumns(HiddenColumns copy)
-  {
-    try
-    {
-
-      LOCK.readLock().lock();
-      if (copy != null)
-      {
-        if (copy.hiddenColumns != null)
-        {
-          hiddenColumns = copy.copyHiddenRegions();
-        }
-      }
-    }
-    finally
-    {
-      LOCK.readLock().unlock();
-    }
-  }
-
-  private Vector<int[]> copyHiddenRegions()
+  private ArrayList<int[]> copyHiddenRegionsToArrayList()
   {
-    Vector<int[]> copy = new Vector<>(hiddenColumns.size());
-    for (int i = 0, j = hiddenColumns.size(); i < j; i++)
+    int size = 0;
+    if (hiddenColumns != null)
     {
-      int[] rh;
-      int[] cp;
-      rh = hiddenColumns.elementAt(i);
-      if (rh != null)
-      {
-        cp = new int[rh.length];
-        System.arraycopy(rh, 0, cp, 0, rh.length);
-        copy.addElement(cp);
-      }
+      size = hiddenColumns.size();
     }
-    return copy;
-  }
+    ArrayList<int[]> copy = new ArrayList<>(size);
 
-  private ArrayList<int[]> copyHiddenRegionsToArrayList()
-  {
-    ArrayList<int[]> copy = new ArrayList<>(hiddenColumns.size());
-    for (int i = 0, j = hiddenColumns.size(); i < j; i++)
+    for (int i = 0, j = size; i < j; i++)
     {
       int[] rh;
       int[] cp;
-      rh = hiddenColumns.elementAt(i);
+      rh = hiddenColumns.get(i);
       if (rh != null)
       {
         cp = new int[rh.length];
@@ -662,22 +635,19 @@ public class HiddenColumns
         copy.add(cp);
       }
     }
-    return copy;
-  }
 
-  public Vector<int[]> getHiddenColumnsCopy()
-  {
-    try
-    {
-      LOCK.readLock().lock();
-      return copyHiddenRegions();
-    } finally
-    {
-      LOCK.readLock().unlock();
-    }
+    return copy;
   }
 
-  public ArrayList<int[]> getHiddenColumnsCopyAsList()
+  /**
+   * Returns a copy of the vector of hidden regions, as an ArrayList. Before
+   * using this method please consider if you really need access to the hidden
+   * regions - a new (or existing!) method on HiddenColumns might be more
+   * appropriate.
+   * 
+   * @return hidden regions as an ArrayList of [start,end] pairs
+   */
+  public ArrayList<int[]> getHiddenColumnsCopy()
   {
     try
     {
@@ -711,12 +681,12 @@ public class HiddenColumns
         int hSize = hiddenColumns.size();
         for (int i = 0; i < hSize; i++)
         {
-          int[] region = hiddenColumns.elementAt(i);
+          int[] region = hiddenColumns.get(i);
           if (region[0] > start && start + change > region[1])
           {
             deletedHiddenColumns.add(region);
 
-            hiddenColumns.removeElementAt(i);
+            hiddenColumns.remove(i);
             i--;
             hSize--;
             continue;
@@ -763,7 +733,7 @@ public class HiddenColumns
       {
         for (int i = 0; i < hiddenColumns.size(); i++)
         {
-          int[] region = hiddenColumns.elementAt(i);
+          int[] region = hiddenColumns.get(i);
           if (region[0] >= start)
           {
             region[0] -= change;
@@ -774,7 +744,7 @@ public class HiddenColumns
           }
           if (region[1] < region[0])
           {
-            hiddenColumns.removeElementAt(i--);
+            hiddenColumns.remove(i--);
           }
 
           if (region[0] < 0)
@@ -787,8 +757,7 @@ public class HiddenColumns
           }
         }
       }
-    }
-    finally
+    } finally
     {
       LOCK.writeLock().unlock();
     }
@@ -855,8 +824,7 @@ public class HiddenColumns
       {
         return new int[] { start, end - 1 };
       }
-    }
-    finally
+    } finally
     {
       LOCK.readLock().unlock();
     }
@@ -869,7 +837,7 @@ public class HiddenColumns
     {
       LOCK.readLock().lock();
       int iSize = seqs.length;
-      String selections[] = new String[iSize];
+      String[] selections = new String[iSize];
       if (hiddenColumns != null && hiddenColumns.size() > 0)
       {
         for (int i = 0; i < iSize; i++)
@@ -925,8 +893,7 @@ public class HiddenColumns
       }
 
       return selections;
-    }
-    finally
+    } finally
     {
       LOCK.readLock().unlock();
     }
@@ -955,7 +922,7 @@ public class HiddenColumns
       {
         int ifpos = seq.findIndex(fpos) - 1;
         int ilpos = seq.findIndex(lpos) - 1;
-        return new int[] { ifpos, ilpos, fpos, lpos, ifpos, ilpos };
+        return new int[] { ifpos, ifpos, ilpos };
       }
 
       // Simply walk along the sequence whilst watching for hidden column
@@ -1014,13 +981,11 @@ public class HiddenColumns
       }
       if (foundStart)
       {
-        return new int[] { findColumnPosition(start),
-            findColumnPosition(lastvispos), fpos, lpos, firstP, lastP };
+        return new int[] { findColumnPosition(start), firstP, lastP };
       }
       // otherwise, sequence was completely hidden
-      return new int[] { visPrev, visNext, 0, 0, firstP, lastP };
-    }
-    finally
+      return new int[] { visPrev, firstP, lastP };
+    } finally
     {
       LOCK.readLock().unlock();
     }
@@ -1141,8 +1106,7 @@ public class HiddenColumns
       {
         alignmentAnnotation.restrict(start, end);
       }
-    }
-    finally
+    } finally
     {
       LOCK.readLock().unlock();
     }
@@ -1194,7 +1158,7 @@ public class HiddenColumns
       List<int[]> inserts = sr.getInsertions();
       for (int[] r : inserts)
       {
-        hideColumns(r[0], r[1], true);
+        hideColumns(r[0], r[1]);
       }
     } finally
     {
@@ -1214,7 +1178,7 @@ public class HiddenColumns
       {
         for (int i = 0; i < hiddenColumns.size(); i++)
         {
-          int[] region = hiddenColumns.elementAt(i);
+          int[] region = hiddenColumns.get(i);
           for (int j = region[0]; j < region[1] + 1; j++)
           {
             sel.addElement(j);
@@ -1223,8 +1187,7 @@ public class HiddenColumns
       }
 
       hiddenColumns = null;
-    }
-    finally
+    } finally
     {
       LOCK.writeLock().unlock();
     }
@@ -1243,7 +1206,7 @@ public class HiddenColumns
       LOCK.writeLock().lock();
       for (int i = 0; i < hiddenColumns.size(); i++)
       {
-        int[] region = hiddenColumns.elementAt(i);
+        int[] region = hiddenColumns.get(i);
         if (start == region[0])
         {
           for (int j = region[0]; j < region[1] + 1; j++)
@@ -1251,7 +1214,7 @@ public class HiddenColumns
             sel.addElement(j);
           }
 
-          hiddenColumns.removeElement(region);
+          hiddenColumns.remove(region);
           break;
         }
       }
@@ -1259,133 +1222,7 @@ public class HiddenColumns
       {
         hiddenColumns = null;
       }
-    }
-    finally
-    {
-      LOCK.writeLock().unlock();
-    }
-  }
-
-  /**
-   * removes intersection of position,length ranges in deletions from the
-   * start,end regions marked in intervals.
-   * 
-   * @param shifts
-   * @param intervals
-   * @return
-   */
-  private boolean pruneIntervalVector(final List<int[]> shifts,
-          Vector<int[]> intervals)
-  {
-    boolean pruned = false;
-    int i = 0;
-    int j = intervals.size() - 1;
-    int s = 0;
-    int t = shifts.size() - 1;
-    int hr[] = intervals.elementAt(i);
-    int sr[] = shifts.get(s);
-    while (i <= j && s <= t)
-    {
-      boolean trailinghn = hr[1] >= sr[0];
-      if (!trailinghn)
-      {
-        if (i < j)
-        {
-          hr = intervals.elementAt(++i);
-        }
-        else
-        {
-          i++;
-        }
-        continue;
-      }
-      int endshift = sr[0] + sr[1]; // deletion ranges - -ve means an insert
-      if (endshift < hr[0] || endshift < sr[0])
-      { // leadinghc disjoint or not a deletion
-        if (s < t)
-        {
-          sr = shifts.get(++s);
-        }
-        else
-        {
-          s++;
-        }
-        continue;
-      }
-      boolean leadinghn = hr[0] >= sr[0];
-      boolean leadinghc = hr[0] < endshift;
-      boolean trailinghc = hr[1] < endshift;
-      if (leadinghn)
-      {
-        if (trailinghc)
-        { // deleted hidden region.
-          intervals.removeElementAt(i);
-          pruned = true;
-          j--;
-          if (i <= j)
-          {
-            hr = intervals.elementAt(i);
-          }
-          continue;
-        }
-        if (leadinghc)
-        {
-          hr[0] = endshift; // clip c terminal region
-          leadinghn = !leadinghn;
-          pruned = true;
-        }
-      }
-      if (!leadinghn)
-      {
-        if (trailinghc)
-        {
-          if (trailinghn)
-          {
-            hr[1] = sr[0] - 1;
-            pruned = true;
-          }
-        }
-        else
-        {
-          // sr contained in hr
-          if (s < t)
-          {
-            sr = shifts.get(++s);
-          }
-          else
-          {
-            s++;
-          }
-          continue;
-        }
-      }
-    }
-    return pruned; // true if any interval was removed or modified by
-    // operations.
-  }
-
-  /**
-   * remove any hiddenColumns or selected columns and shift remaining based on a
-   * series of position, range deletions.
-   * 
-   * @param deletions
-   */
-  public void pruneDeletions(List<int[]> shifts)
-  {
-    try
-    {
-      LOCK.writeLock().lock();
-      // delete any intervals intersecting.
-      if (hiddenColumns != null)
-      {
-        pruneIntervalVector(shifts, hiddenColumns);
-        if (hiddenColumns != null && hiddenColumns.size() == 0)
-        {
-          hiddenColumns = null;
-        }
-      }
-    }
-    finally
+    } finally
     {
       LOCK.writeLock().unlock();
     }
@@ -1431,154 +1268,113 @@ public class HiddenColumns
           SequenceI origseq)
   {
     char gc = al.getGapCharacter();
-    // recover mapping between sequence's non-gap positions and positions
-    // mapping to view.
-    pruneDeletions(ShiftList.parseMap(origseq.gapMap()));
-    int[] viscontigs = al.getHiddenColumns().getVisibleContigs(0,
-            profileseq.getLength());
-    int spos = 0;
-    int offset = 0;
-
-    // add profile to visible contigs
-    for (int v = 0; v < viscontigs.length; v += 2)
-    {
-      if (viscontigs[v] > spos)
+
+    // take the set of hidden columns, and the set of gaps in origseq,
+    // and remove all the hidden gaps from hiddenColumns
+
+    // first get the gaps as a Bitset
+    BitSet gaps = origseq.gapBitset();
+
+    // now calculate hidden ^ not(gap)
+    BitSet hidden = new BitSet();
+    markHiddenRegions(hidden);
+    hidden.andNot(gaps);
+    hiddenColumns = null;
+    this.hideMarkedBits(hidden);
+
+    // for each sequence in the alignment, except the profile sequence,
+    // insert gaps corresponding to each hidden region
+    // but where each hidden column region is shifted backwards by the number of
+    // preceding visible gaps
+    // update hidden columns at the same time
+    ArrayList<int[]> regions = getHiddenColumnsCopy();
+    ArrayList<int[]> newhidden = new ArrayList<>();
+
+    int numGapsBefore = 0;
+    int gapPosition = 0;
+    for (int[] region : regions)
+    {
+      // get region coordinates accounting for gaps
+      // we can rely on gaps not being *in* hidden regions because we already
+      // removed those
+      while (gapPosition < region[0])
       {
-        StringBuffer sb = new StringBuffer();
-        for (int s = 0, ns = viscontigs[v] - spos; s < ns; s++)
+        gapPosition++;
+        if (gaps.get(gapPosition))
         {
-          sb.append(gc);
+          numGapsBefore++;
         }
-        for (int s = 0, ns = al.getHeight(); s < ns; s++)
-        {
-          SequenceI sqobj = al.getSequenceAt(s);
-          if (sqobj != profileseq)
-          {
-            String sq = al.getSequenceAt(s).getSequenceAsString();
-            if (sq.length() <= spos + offset)
-            {
-              // pad sequence
-              int diff = spos + offset - sq.length() - 1;
-              if (diff > 0)
-              {
-                // pad gaps
-                sq = sq + sb;
-                while ((diff = spos + offset - sq.length() - 1) > 0)
-                {
-                  // sq = sq
-                  // + ((diff >= sb.length()) ? sb.toString() : sb
-                  // .substring(0, diff));
-                  if (diff >= sb.length())
-                  {
-                    sq += sb.toString();
-                  }
-                  else
-                  {
-                    char[] buf = new char[diff];
-                    sb.getChars(0, diff, buf, 0);
-                    sq += buf.toString();
-                  }
-                }
-              }
-              sq += sb.toString();
-            }
-            else
-            {
-              al.getSequenceAt(s).setSequence(
-                      sq.substring(0, spos + offset) + sb.toString()
-                              + sq.substring(spos + offset));
-            }
-          }
-        }
-        // offset+=sb.length();
       }
-      spos = viscontigs[v + 1] + 1;
-    }
-    if ((offset + spos) < profileseq.getLength())
-    {
-      // pad the final region with gaps.
+
+      int left = region[0] - numGapsBefore;
+      int right = region[1] - numGapsBefore;
+      newhidden.add(new int[] { left, right });
+
+      // make a string with number of gaps = length of hidden region
       StringBuffer sb = new StringBuffer();
-      for (int s = 0, ns = profileseq.getLength() - spos - offset; s < ns; s++)
+      for (int s = 0; s < right - left + 1; s++)
       {
         sb.append(gc);
       }
-      for (int s = 0, ns = al.getHeight(); s < ns; s++)
-      {
-        SequenceI sqobj = al.getSequenceAt(s);
-        if (sqobj == profileseq)
-        {
-          continue;
-        }
-        String sq = sqobj.getSequenceAsString();
-        // pad sequence
-        int diff = origseq.getLength() - sq.length();
-        while (diff > 0)
-        {
-          // sq = sq
-          // + ((diff >= sb.length()) ? sb.toString() : sb
-          // .substring(0, diff));
-          if (diff >= sb.length())
-          {
-            sq += sb.toString();
-          }
-          else
-          {
-            char[] buf = new char[diff];
-            sb.getChars(0, diff, buf, 0);
-            sq += buf.toString();
-          }
-          diff = origseq.getLength() - sq.length();
-        }
-      }
-    }
-  }
-
-  /**
-   * remove any hiddenColumns or selected columns and shift remaining based on a
-   * series of position, range deletions.
-   * 
-   * @param deletions
-   */
-  private void pruneDeletions(ShiftList deletions)
-  {
-    if (deletions != null)
-    {
-      final List<int[]> shifts = deletions.getShifts();
-      if (shifts != null && shifts.size() > 0)
-      {
-        pruneDeletions(shifts);
+      padGaps(sb, left, profileseq, al);
 
-        // and shift the rest.
-        this.compensateForEdits(deletions);
-      }
     }
+    hiddenColumns = newhidden;
   }
 
   /**
-   * Adjust hidden column boundaries based on a series of column additions or
-   * deletions in visible regions.
+   * Pad gaps in all sequences in alignment except profileseq
    * 
-   * @param shiftrecord
-   * @return
+   * @param sb
+   *          gap string to insert
+   * @param left
+   *          position to insert at
+   * @param profileseq
+   *          sequence not to pad
+   * @param al
+   *          alignment to pad sequences in
    */
-  private ShiftList compensateForEdits(ShiftList shiftrecord)
+  private void padGaps(StringBuffer sb, int pos, SequenceI profileseq,
+          AlignmentI al)
   {
-    if (shiftrecord != null)
+    // loop over the sequences and pad with gaps where required
+    for (int s = 0, ns = al.getHeight(); s < ns; s++)
     {
-      final List<int[]> shifts = shiftrecord.getShifts();
-      if (shifts != null && shifts.size() > 0)
+      SequenceI sqobj = al.getSequenceAt(s);
+      if (sqobj != profileseq)
       {
-        int shifted = 0;
-        for (int i = 0, j = shifts.size(); i < j; i++)
+        String sq = al.getSequenceAt(s).getSequenceAsString();
+        if (sq.length() <= pos)
+        {
+          // pad sequence
+          int diff = pos - sq.length() - 1;
+          if (diff > 0)
+          {
+            // pad gaps
+            sq = sq + sb;
+            while ((diff = pos - sq.length() - 1) > 0)
+            {
+              if (diff >= sb.length())
+              {
+                sq += sb.toString();
+              }
+              else
+              {
+                char[] buf = new char[diff];
+                sb.getChars(0, diff, buf, 0);
+                sq += buf.toString();
+              }
+            }
+          }
+          sq += sb.toString();
+        }
+        else
         {
-          int[] sh = shifts.get(i);
-          compensateForDelEdits(shifted + sh[0], sh[1]);
-          shifted -= sh[1];
+          al.getSequenceAt(s).setSequence(
+                  sq.substring(0, pos) + sb.toString() + sq.substring(pos));
         }
       }
-      return shiftrecord.getInverse();
     }
-    return null;
   }
 
   /**
@@ -1600,8 +1396,7 @@ public class HiddenColumns
         }
       }
       return hashCode;
-    }
-    finally
+    } finally
     {
       LOCK.readLock().unlock();
     }
@@ -1623,7 +1418,7 @@ public class HiddenColumns
                       .nextSetBit(lastSet))
       {
         lastSet = inserts.nextClearBit(firstSet);
-        hideColumns(firstSet, lastSet - 1, true);
+        hideColumns(firstSet, lastSet - 1);
       }
     } finally
     {
@@ -1649,8 +1444,7 @@ public class HiddenColumns
       {
         inserts.set(range[0], range[1] + 1);
       }
-    }
-    finally
+    } finally
     {
       LOCK.readLock().unlock();
     }
@@ -1711,4 +1505,37 @@ public class HiddenColumns
 
   }
 
+  /**
+   * Finds the hidden region (if any) which starts or ends at res
+   * 
+   * @param res
+   *          visible residue position, unadjusted for hidden columns
+   * @return region as [start,end] or null if no matching region is found
+   */
+  public int[] getRegionWithEdgeAtRes(int res)
+  {
+    try
+    {
+      LOCK.readLock().lock();
+      int adjres = adjustForHiddenColumns(res);
+
+      int[] reveal = null;
+      if (hiddenColumns != null)
+      {
+        for (int[] region : hiddenColumns)
+        {
+          if (adjres + 1 == region[0] || adjres - 1 == region[1])
+          {
+            reveal = region;
+            break;
+          }
+        }
+      }
+      return reveal;
+    } finally
+    {
+      LOCK.readLock().unlock();
+    }
+  }
+
 }