FUNCTION DIcal_bitWeight, in, fitsHdr, FN=fn

;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Used in the DI Calibration Pipeline.
;;	Corrects for uneven ADC bit weighting. This is
;;	done using a lookup table saved as FITS file. 
;;	The variable should be an array with 2^14 elements
;;
;;      NOTE: The analysis for this step was never completed so it doesn't
;;            do anything valid
;;
;; CALLING SEQUENCE:
;;	out = DIcal_bitWeight, in, fitsHdr
;;
;; 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 lookup table to use. If this keyword is not set,
;;		the database is queried.
;;
;; EXAMPLE:
;;      IDL> imgOut = DIcal_bitWeight(imgIn, fitsHdr)
;;
;; PROCEDURES USED (i.e. called directly!):
;;	SXPAR - Read FITS header
;;	FXADDPAR - Modifies the FITS header
;;
;; MODIFICATION HISTORY:
;;   2004-05-24  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------

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

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

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

;; Get the date the image was taken
date = SXPAR(fitsHdr, 'OBSDATE', COUNT=c2)

;; Make sure the FITS header contained everything
IF (c1 EQ 0) OR (c2 EQ 0) THEN $
	message, 'Invalid FITS Header', /NONAME

;; Get the filename
IF not keyword_set(fn) THEN BEGIN
	serv = getSQLserver()
	db = 'di_calib'
	tbl = 'ADC_LUT'
	sel = ['Filepath']
	cond = 'Instrument = "'+inst+'" AND Date <= "'+date+$
		'" 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 calibration file'

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

;; Restore the LUT
LUT = readfits(fn1[0])

IF n_elements(LUT) NE 2ll^14 THEN message, 'Invalid bit weighting LUT'

;; Find the finite parts of the image
out = double(in)
w = where(finite(out) EQ 1)

;; Perform the conversion
out[w] = LUT[out[w]] 

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

RETURN,  out
END