;+
; NAME:
;     DLAFIT
; PURPOSE:
;     Fits a gaussian to the central part of the delay pattern for a
;     single baseline, to represent the delay center offset in nsec.
; CATEGORY:
;     OVRO APC CALIBRATION
; CALLING SEQUENCE:
;     dlafit,x,y,x0,chisq,xfit,yfit
; INPUTS:
;     input description
; OPTIONAL (KEYWORD) INPUT PARAMETERS:
;     flag  description
; ROUTINES CALLED:
;     curvefit
; OUTPUTS:
;
; COMMENTS:
; SIDE EFFECTS:
; RESTRICTIONS:
; MODIFICATION HISTORY:
;     Written 21-May-2000 by Dale E. Gary
;-
pro gfunct,x,a,f,pder
   awid=6.0   ; Hardwires the full-width-half-max to 10 nsec, which is the nominal
   ; Function to fit
   f = abs(a(0))*exp(-((x-a(1))/awid)^2)

   ; These are the partial derivatives of the fit function
   if n_params() ge 4 then begin
      pder = fltarr(n_elements(x),2)
      if (a(0) lt 0) then pder(*,0) = -exp(-((x-a(1))/awid)^2) $
                     else pder(*,0) =  exp(-((x-a(1))/awid)^2)
      pder(*,1) = 2*abs(a(0))*((x-a(1))/(awid^2))*exp(-((x-a(1))/awid)^2)
   endif
end

pro dlafit,x,y,x0,sigma,xfit,yfit

   ; Search for peak within 10 nsec of the center (delays must be adjusted by hand to get
   ; close).
   ymid = n_elements(y)/2
   ymax = max(y[ymid-20:ymid+20],imax)
   ; Found peak, so now do fit centered around the peak
   xpk = imax-20         ; X value of peak location
   jmax = imax+ymid-20   ; Index of peak location, in Y array
   a = [ymax,xpk]
   w = y[jmax-7:jmax+7]*0 + 1.0   ; Just use unit weights
   out = curvefit(x[jmax-7:jmax+7],y[jmax-7:jmax+7],w,a,siga,func='gfunct',chisq=chisq)
   x0 = a[1]
   xfit = congrid(x[jmax-7:jmax+7],90,/interp)
   yfit = abs(a[0])*exp(-((xfit-a[1])/6.0)^2)
   sigma = siga[1]

return
end