public static int getIndexOfPrecedingMinimum(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 >= 0; --i) {
      maximum_value = Math.max(previous_value, maximum_value);

      if (contour.get(i) > previous_value) {

        if (!rising && maximum_value - previous_value > threshold) {
          // Just passed a local minima.
          // If the difference between the value of this minima is sufficiently lower that the maximum, return the index
          // of the local minima
          return i + 1;
        }
        rising = true;
      }

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

      previous_value = contour.get(i);
    }

    if (!rising && maximum_value - contour.get(0) > threshold) {
      // The previous minimum is the start of the contour
      return 0;
    } else {
      // The previous minimum is undefined, return the starting index.
      return idx;
    }
  }