FUNCTION DIcal_fixBadPixs, in, fitsHdr,FN=fn, FLAGS=flags

;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Used in the DI Calibration Pipeline.
;;	Identifies bad pixels. Bad pixels are defined by a bad
;;	pixel map, which is a binary image where 1 signifies a bad pixel
;;
;; CALLING SEQUENCE:
;;	RETURN = DIcal_fixBadPixs(in, fitsHdr,imgCols, imgRows, 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 - contains the image after going through the calibration step
;;
;; OPTIONAL INPUT KEYWORDS:
;;	FN - Filename of the bad pixel map to use. If not specified, this is
;;		found using a database.
;;	FLAGS - Array of flags for each pixel. If this is not specified,
;;		a new array is created with just the bad pixel flags
;;
;; EXAMPLE:
;;      IDL> imgOut = DIcal_fixBadPixs(imgIn, fitsHdr)
;;
;; PROCEDURES USED (i.e. called directly!):
;;	SXPAR - Reads a FITS header item
;;
;; MODIFICATION HISTORY:
;;   2004-05-24  M. Desnoyer    Created
;;
;;----------------------------------------------------------------------------- 

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

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

;; Check the inputs
imgDim = size(in, /DIMENSIONS)
IF (N_ELEMENTS(imgDim) NE 2) THEN $
	message, 'Invalid image', /NONAME

;; Default
dim = size(in, /dimensions)
IF n_elements(flags) EQ 0 THEN flags = intarr(dim[0],dim[1])

;; Get the instrument
inst = sxpar(fitsHdr, 'INSTRUME', COUNT=c1)

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

;; Get the detector
det = sxpar(fitsHdr, 'IMGH021', COUNT=c3)

;; Get the temperature
IF det EQ 0 THEN temp = sxpar(fitsHdr, 'CCDT', COUNT=c4) $
ELSE IF det EQ 1 THEN temp = sxpar(fitsHdr, 'IRFPAT', COUNT=c4) $
ELSE c4 = 0

;; Get the date the image was taken
date = sxpar(fitsHdr, 'OBSDATE', COUNT=c5)

;; Make sure all the data was in the header
IF (c1 EQ 0) OR (c2 EQ 0) OR (c3 EQ 0) OR (c4 EQ 0) OR (c5 EQ 0) THEN $
	message, 'Invalid DI FITS header', /NONAME

out = double(in)

;; Get filename of the bad pixel map
IF not keyword_set(fn) THEN BEGIN
	serv = getSQLserver()
	db = 'di_calib'
	tbl = 'BAD_PIXS'
	sel = ['Filepath']
	cond = 'Instrument = "'+inst+'" AND Date <= "'+date+$
		'" AND Mode = '+strtrim(mode,2)+' AND Temperature >= '+$
		strtrim(temp,2)+' order by Date desc, Version desc, Temperature limit 1'

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

	IF min(dim) EQ 0 THEN message, 'No valid bad pixel map found'

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

badPixs = readFITS(fn1[0], calHdr, /SILENT)

;; Check the bad pixel map
mapDim = size(badPixs, /DIMENSIONS)
IF (N_ELEMENTS(mapDim) NE 2) THEN $
	message, 'Invalid bad pixel map', /NONAME
w = where(badPixs EQ 0, c1)
w = where(badPixs EQ 1, c2)
IF (c1+c2 NE N_ELEMENTS(badPixs)) THEN $
	message, 'Invalid bad pixel map', /NONAME

;; Rotate the bad pixel map
badPixs = DICal_RotCalImg(badPixs,inst,calHdr)

;; Add all the flags
@dical_flags
w = where(badPixs NE 0,c1)
IF (c1 GT 0) THEN flags[w] = flags[w] OR FLAG_BAD

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

RETURN, out
END