def scanedges(d, minthresh):
    tofs = []
    sz = d.shape[0]
    order = 3
    i = 1
    while i < sz - 10:
        while d[i] > minthresh:
            i += 1
            if i == sz - 10: return tofs
        while i < sz - 10 and d[i] < d[i - 1]:
            i += 1
        start = i
        i += 1
        while i < sz - 10 and d[i] > d[i - 1]:
            i += 1
        stop = i
        if stop - start < 4:
            continue
        x = np.arange(stop - start, dtype=float)
        y = d[start:stop]
        x0 = float(stop) / 2.
        y -= (y[0] + y[-1]) / 2.
        theta = np.linalg.pinv(mypoly(np.array(x).astype(float),
                                      order=order)).dot(
                                          np.array(y).astype(float))
        for j in range(3):  # 3 rounds of Newton-Raphson
            X0 = np.array([np.power(x0, int(i)) for i in range(order + 1)])
            x0 -= theta.dot(X0) / theta.dot([
                i * X0[(i + 1) % (order + 1)] for i in range(order + 1)
            ])  # this seems like maybe it should be wrong
        tofs += [start + x0]
    return tofs
def zeroFitRoot(lt, d, thresh=1.):
    tofs = []
    sz = d.shape[0]
    x = []
    y = []
    order = 3
    i = 0
    while i < sz - 10:
        while d[i] < thresh:
            i += 1
            if i == sz - 10: return tofs
        while d[i + 1] > d[i] and i < sz - 10:
            i += 1
        while d[i + 1] < d[i] and i < sz - 10:
            x += [lt[i]]
            y += [d[i]]
            i += 1

        x0 = np.mean(x)
        theta = np.linalg.pinv(mypoly(np.array(x).astype(float),
                                      order=order)).dot(
                                          np.array(y).astype(float))
        for j in range(2):
            X0 = np.array([np.power(x0, int(i)) for i in range(order + 1)])
            x0 -= theta.dot(X0) / theta.dot(
                [i * X0[(i + 1) % (order + 1)] for i in range(order + 1)])
        tofs += [x0]
        x = []
        y = []
    return tofs
def zeroFit(lt, d, thresh=1.):
    tofs = []
    sz = d.shape[0]
    i = int(2)
    while i < sz - 10:
        while d[i] < thresh:
            i += 1
            if i == sz - 10: return tofs
        while d[i] > 0:
            i += 1
            if i == sz - 10: return tofs
        y = lt[i - 2:i + 2]
        x = d[i - 2:i + 2]
        tofs += [
            np.linalg.pinv(mypoly(np.array(x).copy().astype(float),
                                  order=1)).dot(np.array(y).astype(float))[0]
        ]
        i += 2
    return tofs