public static int getIndexOfFollowingMinimum(Contour contour, int idx, Double threshold) {
    double previous_value = contour.get(idx);
    double maximum_value = contour.get(idx);
    boolean rising = false;
    for (int i = idx + 1; i < contour.size(); ++i) {
      maximum_value = Math.max(previous_value, maximum_value);
      if (contour.get(i) > previous_value) {

        // In a valley.  If the valley was sufficiently deep from previous peak, store the value.
        if (!rising && maximum_value - previous_value > threshold) {
          return i - 1;
        }
        rising = true;
      }

      if (contour.get(i) < previous_value) {
        rising = false;
      }

      previous_value = contour.get(i);
    }

    if (!rising && maximum_value - contour.get(contour.size() - 1) > threshold) {
      // The following minimum is the end of the contour
      return contour.size() - 1;
    } else {
      // The following local mimina is undefined, return the ending point.
      return idx;
    }
  }