function iris_fid_fitter, gx, gy, py1l, xval=xval, yval=yval, nterms = nterms

; NAME:   fid_fitter.pro
;       
; PURPOSE:  Works with fid_finder to fit the slices made
;
; CATEGORY: Image Calibration
;
; CALLING SEQUENCE: values = fid_fitter(gx, gy, py1l, /yval)
;
; INPUT ARGUMENTS:  
;       gx = The pixel positions of the slice
;		gy = The values to fit
;		py = An offset value for the centroid position based on where the slice starts
;
; INPUT KEYWORD PARAMETER:
;		xval = Set if fitting a dip.
;		yval = Set if fitting a peak.
;		
;
; OUTPUTS: An array containing:
;			yfit = The fit values.
;			coeff = The determined centroid position.
;			chisq_y1 = The goodness of fit.
;
; PROGRAM NOTES: 
;			When measured values are considered bad (the goodness of fit values are large)
;			the value is thrown out by setting it to 0. Keep this in mind when using the 
;			output data.
;
; OTHER PROGRAMS NEEDED:
; 			fid_fitter - Used to fit slices taken to get sub-pixel values for locations
;
;
; MODIFICATION HISTORY:
;	2013/08/26 Written by Sean McKillop (smckillop@cfa.harvard.edu)
; Generate the slice fits. 


tot_size = size(gy, /n_elements)
err = SQRT(ABS(gy)>1)
err = err[0:tot_size-1]
if not KEYWORD_SET(nterms) then nterms = 5

; Find the various fitting parameters to feed into gaussfit

; Trending Slope
left_ave = average(gy(0:1))
right_ave = average(gy(tot_size-2:tot_size-1))
rise = right_ave - left_ave
t_slope = rise/tot_size

; Baseline Value
a = abs((right_ave - left_ave)/2)
if left_ave lt right_ave then b = left_ave + a
if right_ave lt left_ave then b = right_ave + a
if right_ave eq left_ave then b = left_ave     
 
; Gauss Height
if keyword_set(xval) then g_max = float(min(gy))
if keyword_set(yval) then g_max = float(max(gy))
g_h = abs(g_max - b)
         
; Centroid position
g_h_w = where(gy eq g_max)
g_h_w = g_h_w + py1l(0)
if size(g_h_w, /n_elements) ge 2 then begin
    cent = g_h_w(0) + 0.5
    endif else begin
        lv = gy(g_h_w - 1)
        if abs(g_max - lv) lt 2.0 then cent = g_h_w - .5
        rv = gy(g_h_w + 1)
        if abs(g_max - rv) lt 2.0 then cent = g_h_w + .5
        if abs(g_max - lv) ge 2.0 and abs(g_max - rv) ge 2.0 then cent = g_h_w
	endelse

; Do the fitting
estimates = [g_h, cent, 2, b, t_slope] ; G-height, centroid, width, baseline value, slope
yfit = mpfitpeak(gx, gy, coeff, estimates=estimates, chisq=chisq_y1, nterms=nterms, measure_errors=err)

; Vary the parameters to get the best fit possible
arr = [0.2, 0.3, 0.1, 0.5, 0.3]
for ii=1,20 do begin
    estimates2 = estimates + arr*randomn(seed,5)
    yfit2 = mpfitpeak(gx, gy, coeff2, estimates=estimates2, chisq=chisq_new, nterms=nterms, measure_errors=err)
    if chisq_new lt chisq_y1 then begin
            yfit = yfit2
            coeff = coeff2
            chisq_y1 = chisq_new
    endif
endfor

; Collect the values together
values = {yfit : yfit, coeff : coeff, chisq : chisq_y1}

return, values
end

