// midline:          data vector (white)
// linelist:         line list (wavelengths) (red)
// midgausspos:      pixel positions of extracted lines (blue)
// identifylongslit: pixel positions of identified lines (green)
// plot:             the plot device, OS-specific
procedure luciplotlines, midline, linelist, midgausspos, identifylongslit, plot {
    imagewidth = nelements(midline)

    nrfound = naxis1(midgausspos)
    nridentified = naxis1(identifylongslit[1,*])
        
    maxl = max(midline)
    minl = min(midline)
    deltal = maxl - minl
    
    // setup plot environment
    pgbeg 0, plot, 1, 1
    pgenv 1, imagewidth, minl, maxl + deltal*0.1, 0, 0
    pglab "x-axis", "intensity", "[Boxcar] Extr: " + nrfound + ", Ident: " +nridentified+" ("+identifylongslit[1,1]+","+identifylongslit[1,nridentified]+")"

    // plot data, white
    pgline imagewidth, [1:imagewidth], midline

    // plot extracted lines (edgedetect), blue
    pgsci 4

    i = 1
    pos = 1
    while (pos <= imagewidth && i <= naxis1(midgausspos)) {
        if (pos >= midgausspos[i]) {
            mypos = pos
            
            if (mypos > 1 && midline[mypos] < midline[mypos-1]) {
                mypos -= 1
                if (mypos > 1 && midline[mypos] < midline[mypos-1]) {
                    mypos -= 1
                }
            }
            if (mypos < imagewidth && midline[mypos+1] > midline[mypos]) {
                mypos += 1
                if (mypos < imagewidth && midline[mypos+1] > midline[mypos]) {
                    mypos += 1
                }
            }

            pgline 2, [mypos,mypos], [midline[mypos]+deltal*.08,midline[mypos]+deltal*.12]
            i++
        }
        pos++
    }

    // plot candidate lines (linelist), red
    pgsci 2
    tmp = polyfitxy(identifylongslit[1,*], identifylongslit[2,*], 2)
    cal = poly([1:imagewidth], tmp[*,1])

    i = 1
    pos = 1
    while (pos <= imagewidth && i <= naxis1(linelist)) {
        if (cal[pos] >= linelist[i]) {
            mypos = pos
            
            if (mypos > 1 && midline[mypos] < midline[mypos-1]) {
                mypos -= 1
                if (mypos > 1 && midline[mypos] < midline[mypos-1]) {
                    mypos -= 1
                }
            }
            if (mypos < imagewidth && midline[mypos+1] > midline[mypos]) {
                mypos += 1
                if (mypos < imagewidth && midline[mypos+1] > midline[mypos]) {
                    mypos += 1
                }
            }

            pgline 2, [mypos,mypos], [midline[mypos]+deltal*.02,midline[mypos]+deltal*.08]
            i++
        }
        pos++
    }

    // plot identified lines, green
    pgsci 3
    for i=1, nridentified {
        pos = identifylongslit[1,i]
        pgline 2, [pos,pos], [midline[pos]+deltal*.02,midline[pos]+deltal*.08]
    }

    pgend
}
