FUNCTION DIcal_flatField, in, fitsHdr, FN=fn

;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Used in the DI Calibration Pipeline.
;;	Performs a flat field correction to account for the fact that 
;;	individual pixels react slightly differently to the same amount of
;;	light. 
;;
;; CALLING SEQUENCE:
;;	out = DIcal_flatField(in, fitsHdr, imgCols, imgRows, FN=fn)
;;
;; REQUIRED INPUTS:
;;	in - The image to which this pipeline element is going to be applied. 
;;		This should only be the pixels that are actually a part of the
;;		image (ie. no POC rows or BIAS columns)
;;	fitsHdr - The FITS header for the image
;;
;; OUTPUTS:
;;	RETURN - the image after going through this calibration step
;;
;; OPTIONAL INPUT KEYWORDS:
;;	FN - filename of flat field to use. If this is not set, the flat 
;;		field is retrieved from the database
;;
;; EXAMPLE:
;;      IDL> imgOut = DIcal_flatField(imgIn, fitsHdr, imgCols, imgRows)
;;
;; PROCEDURES USED (i.e. called directly!):
;;	READFITS - read a fits file
;;
;; MODIFICATION HISTORY:
;;   2004-05-24  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------

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

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

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

;; Get the filter
filter = SXPAR(fitsHdr, 'IMGH036', COUNT=c2)

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

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

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

out = double(in)

;; Get the file name
IF NOT keyword_set(FN) THEN BEGIN
	;; Get the real filter number
	filter = imgh036ToFilter(filter,inst,date)

	serv = getSQLserver()
	db = 'di_calib'
	tbl = 'FLAT'
	sel = ['Filepath']
	cond = 'Instrument = "'+inst+'" AND Date <= "'+date+$
		'" AND Mode = '+strtrim(mode, 2)+' AND Filter = '+$
		strtrim(filter, 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 flat field'

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

;; Open the flat field
flat = readFITS(fn1[0], calHdr, /SILENT)
IF size(flat, /N_DIMENSIONS) EQ 0 THEN $
	message, 'Invalid flat-field image.', /NONAME

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

;; Replace all zeros in the flat with ones so that the image data isn't corrupted
w = where(flat EQ 0, cnt)
IF cnt GT 0 THEN flat[w] = 1

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

;; Perform flat field normalization
RETURN, out / flat

END