// image:    image to analize
// poslo:    lower range for edge
// poshi:    upper range for edge
// edgepars: [1]:  number of pixels to omit at left end
//           [2]:  number of pixels to omit at right end
//           [3]:  size of moving window to median
//           [4]:  order of polynomial to fit locally to the edge (in the moving window)
//           [5]:  order of the polynomial to fit to the whole edge
//           [6]:  sigma-factor for rejection
function luciedgedetect, image, poslo, poshi, edgepars {
    omitborderleft = int(edgepars[1])
    omitborderright = int(edgepars[2])
    boxm = int(edgepars[3])
    order = int(edgepars[4])
    edgeorder = int(edgepars[5])
    sigma = edgepars[6]

    imagewidth = naxis1(image)
    result = fits(imagewidth)
    result[*] = 1/0
    xline = fits(imagewidth)
    xline[*] = 1/0
    warray = doublearray(imagewidth, order-1)

    for (x=boxm+1; x<=imagewidth-boxm-1; x += boxm) {
        sub = image[x-boxm:x+boxm,poslo:poshi]
        line = sub[1,*]
        for y = 1, naxis2(sub) {
            line[y] = median(sub[*,y])
        }
        
        // fit polynomial of high order
        p = polyfit(line, order)[*,1]

        // calculate turning points
        w = polyroots(p, 2)
        w = real(w[where(imag(w) == 0)])
        nlow = nelements(where(w < 1))
        nhigh = nelements(where(w > poshi-poslo))
        w = w[sort(w)]
        w = w[nlow+1:nelements(w)-nhigh]

        warray[x,1:nelements(w)] = w

        // evaluate polynomials at turning points (Wendepunkt)
        v = poly(w, p)
        
        // subtract values left and right from turning point
        v2 = abs(v[3:nelements(v)] - v[1:nelements(v)-2])

        result[x] = w[xmax(v2)+1]
    }

    // fit polynomial to the turning points (edge) using outlier rejection
    p = polyfit(result, edgeorder)[*,1]
    v = poly([1:imagewidth],p)

    // apply outlier rejection
    r2 = abs(result - v)
    r2 -= median(r2)
    r2 = abs(r2)
    thresh = meddev(r2) * sigma
    result[where(r2 > thresh)] = 1/0

    if (omitborderleft > 0) {
        result[1:omitborderleft] = 1/0
    }
    if (omitborderright > 0) {
        result[nelements(result)-omitborderright:nelements(result)] = 1/0
    }

    // fit again
    p = polyfit(result, edgeorder)[*,1]
    v = poly([1:imagewidth],p)

    // find out position of nearest turning point to our polynomial
    for (x=boxm+1; x<=imagewidth-boxm-1; x += boxm) {
        w = warray[x,*]
        w -= v[x]
        result[x] = warray[x, xmin(abs(w))] + poslo - 1
    }

    // fit polynomial to the turning points (edge) using outlier rejection
    p = polyfit(result, edgeorder)[*,1]
    r2 = abs(result - poly([1:imagewidth],p))
    r2 -= median(r2)
    r2 = abs(r2)
    thresh = meddev(r2) * sigma
    result[where(r2 > thresh)] = 1/0

    luciedgedetect = polyfit(result, edgeorder)[*,1]

    print "FINISHED DETECTING EDGE"
}
