Merge commit 'alpha/update_2_12_for_2_11_2_series_merge^2' into HEAD
[jalview.git] / src / jalview / util / MappingUtils.java
index 915293e..fe95f4b 100644 (file)
@@ -1020,22 +1020,78 @@ public final class MappingUtils
       }
     }
   }
+  /**
+   * Adds the given range to a list of ranges. If the new range just extends
+   * existing ranges, the current endpoint is updated instead.
+   * 
+   * @param range
+   * @param addTo
+   */
+  public static void addRange(int[] range, List<int[]> addTo)
+  {
+    /*
+     * list is empty - add to it!
+     */
+    if (addTo.size() == 0)
+    {
+      addTo.add(range);
+      return;
+    }
+  
+    int[] last = addTo.get(addTo.size() - 1);
+    boolean lastForward = last[1] >= last[0];
+    boolean newForward = range[1] >= range[0];
+  
+    /*
+     * contiguous range in the same direction - just update endpoint
+     */
+    if (lastForward == newForward && last[1] == range[0])
+    {
+      last[1] = range[1];
+      return;
+    }
+  
+    /*
+     * next range starts at +1 in forward sense - update endpoint
+     */
+    if (lastForward && newForward && range[0] == last[1] + 1)
+    {
+      last[1] = range[1];
+      return;
+    }
+  
+    /*
+     * next range starts at -1 in reverse sense - update endpoint
+     */
+    if (!lastForward && !newForward && range[0] == last[1] - 1)
+    {
+      last[1] = range[1];
+      return;
+    }
+  
+    /*
+     * just add the new range
+     */
+    addTo.add(range);
+  }
 
   /**
-   * Converts a list of [start, end] ranges to a single array of [start, end,
-   * start, end ...]
+   * Converts a list of {@code start-end} ranges to a single array of
+   * {@code start1, end1, start2, ... } ranges
    * 
    * @param ranges
    * @return
    */
-  public static int[] listToArray(List<int[]> ranges)
+  public static int[] rangeListToArray(List<int[]> ranges)
   {
-    int[] result = new int[ranges.size() * 2];
-    int i = 0;
-    for (int[] range : ranges)
+    int rangeCount = ranges.size();
+    int[] result = new int[rangeCount * 2];
+    int j = 0;
+    for (int i = 0; i < rangeCount; i++)
     {
-      result[i++] = range[0];
-      result[i++] = range[1];
+      int[] range = ranges.get(i);
+      result[j++] = range[0];
+      result[j++] = range[1];
     }
     return result;
   }