;+
;  Name:
;       GAIN_COR
;c ****************************************************************************
;c       pro gain_cor,ndet,nlines,chan,en,a,b,c,x0
;
;c      Subroutine to calculate gain corrected coefficients for the calibration
;c     equation. The fiducial  coefficients are read from the  file FCOEFF.DAT.
;;c     Inputs:
;c        ndet--detector number
;c        nlines--number of lines used to calibrate
;c        chan--vector of locations of lines in uncompressed channels
;c        en--vector of locations of lines in energy
;
;c     Outputs:
;c        a,b,c,x0--coefficients used in calibration equation:
;c
;c           E*g_c = a + b*x + c*(x-x0)**2*H(x0-x)
;c
;c        where H(x0_x) is the Heaviside function and x is channel number.
;c
;c     written 11/8/91              last modified 12/6/91       LAF
;c	ras, 28-mar-95
;c*****************************************************************************
;c
;      
;     
;-
pro gain_cor,ndet,nlines,chan,en,a,b,c,x0, error = error

common fiducial_com, af,bf,cf,xf
error = 1

gain_offset = spex_current('gain_offset', error=spex_error)
gain_mult = spex_current('gain_mult', error=spex_error)
if spex_error then gain_mult = 1.0  ;gain_offset

;modify the fiducials temporarily
af(ndet) = af(ndet) + gain_offset
bf(ndet) = bf(ndet) * gain_mult
;c
;c     Calculate the scaling factor
;c
      sum=0.
      xi = en * 0.0
      for i=0,nlines-1 do begin
         denom=af(ndet) + bf(ndet)*chan(i)
         if (chan(i) lt xf(ndet)) then $
            denom=denom+cf(ndet)*(chan(i)-xf(ndet))^2
	 g_c, en(i), fun, dfun 
         xi(i)=en(i)*(fun)(0)/denom
         sum=sum+xi(i)
      endfor
;c
;c     Scale the coefficients
;c
      average=sum/float(nlines)
      a=af(ndet)*average
      b=bf(ndet)*average
      c=cf(ndet)*average
      x0=xf(ndet)
;c
;restore the fiducials 
af(ndet) = af(ndet) - gain_offset
bf(ndet) = bf(ndet) / gain_mult
;c
error = 0

return
end
