FUNCTION DIcal_gain, in, fitsHdr, FN=fn
;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Used in the DI Calibration Pipeline.
;;	Normalizes the gains of the different quadrants.
;;
;; CALLING SEQUENCE:
;;	x = DIcal_gain(in, fitsHdr, FN=fn)
;;
;; REQUIRED INPUTS:
;;	in - The image to which this pipeline element is going to be applied
;;	fitsHdr - The FITS header for the image
;;
;; OUTPUTS:
;;	RETURN - the image after going through this calibration step
;;
;; OPTIONAL INPUT KEYWORDS:
;;	FN - Filename of the file containing a map of all the gains
;;
;; EXAMPLE:
;;      IDL> imgOut = DIcal_gain(imgIn, fitsHdr)
;;
;; PROCEDURES USED (i.e. called directly!):
;;
;; MODIFICATION HISTORY:
;;   2004-08-22  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------

;; Do error handling 
;CATCH, error
error=0

IF error NE 0 THEN BEGIN
	CATCH, /CANCEL
	message, 'Gain Normalization - ' + !ERROR_STATE.MSG, /NONAME
ENDIF

;; Get the instrument
inst = STRTRIM(SXPAR(fitsHdr, 'INSTRUME', COUNT=c1),2)

;; Get the operating mode
mode = SXPAR(fitsHdr, 'IMGH030', COUNT=c2)

;; Get the date
date = SXPAR(fitsHdr, 'OBSDATE', COUNT=c3)

;; Make sure the FITS header is good
IF (c1 EQ 0) OR (c2 EQ 0) OR (c3 EQ 0) THEN $
	message, 'Invalid FITS header', /NONAME

out = double(in)

;; Get the file name of the gain file
IF NOT keyword_set(FN) THEN BEGIN
	serv = getSQLserver()
	db = 'di_calib'
	tbl = 'GAIN'
	sel = ['Filepath']
	cond = 'Instrument = "'+inst+'" AND Date <= "'+date+$
		'" AND Mode = '+strtrim(mode, 2)+' order by Date desc, Version desc limit 1'

	webfn = di_sqlquery(serv, db, tbl, sel, cond, dim=dim)

	IF min(dim) EQ 0 THEN message, 'Could not find valid gain map'

	fn1 = getLocFn(webFn, subdir='GAIN')
ENDIF ELSE fn1=fn

;; Open the gain map
gain = readFITS(fn1[0], calHdr, /SILENT)
IF size(gain, /N_DIMENSIONS) EQ 0 THEN $
	message, 'Invalid gain map', /NONAME

;; Rotate the gain
gain = DICal_RotCalImg(gain,inst, calHdr)

;; Update the fits header
fxaddpar, fitsHdr, 'GAINCORR', 'T'
fxaddpar, fitsHdr, 'GAINFN', $
	strupcase(strmid(fn1[0], strpos(fn1[0], path_sep(), /reverse_search)+1))

RETURN, out/gain

END