def FindNotNaNBackwards(x, i):
    """Returns last position (starting at i backwards) which is not NaN, or -1."""
    while i >= 0:
        if not np.isnan(x[i]):
            return i
        i -= 1
    return -1