import numpy as np


def peakfind(x, search_thresh, i=0, max_depth=None, direction="right",
             fail_flag=False):
    """Find first local maximum of x that is larger than search_tresh.

    Arguments:
        x (array): input signal
        search_thresh (scalar): minimum amplitude of local maximum
        i (int): start index (default=0)
        max_depth (int): maximum search iterations (default=None)
        direction (string): search direction - accepts string "right"
                            or "left" (default="right")
        fail_flag (int): determines behavior if no local maximum above
                         threshold is found (accepted values: True, or
                         False); if False: global maximum is returned on
                         failure, else -1 is returned

    Returns:
        peak_i (int): index of first occurrence local maximum above
                      threshold
    """

    peak_i = -1
    step = 1 if direction == "right" else -1
    if max_depth:
        end = min(len(x)-1, i + max_depth*np.sign(step))
    else:
        end = len(x)-1 if step > 0 else 1

    for j in range(i+step, end, step):
        if x[j-1] < x[j] > x[j+1] and x[j] > search_thresh:
            peak_i = j
            break

    if peak_i == -1 and not fail_flag:
        peak_i = x.argmax()
    return peak_i
