FUNCTION DIcal_compress, in, fitsHdr

;;------------------------------------------------------------------------------
;; PURPOSE:
;;	Used in the DI Calibration Pipeline.
;;	Compresses an image using the lookup table appropriate for the DI FITS 
;;	header given.
;;
;; CALLING SEQUENCE:
;;	out = DIcal_compress(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:
;;
;; EXAMPLE:
;;      IDL> imgOut = DIcal_compress(imgIn, fitsHdr)
;;
;; PROCEDURES USED (i.e. called directly!):
;;	getSQLServer - Info on how to get to the database
;;	DI_sqlQuery - Sends queries to the SQL server
;;	getLocFn - Gets a file and stores it locally
;;	SXPAR - Read the FITS header
;;
;; MODIFICATION HISTORY:
;;   2005-07-19  M. Desnoyer    Created
;;
;;------------------------------------------------------------------------------

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

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

;; Get the date stamp on the image
date = SXPAR(fitsHdr,'OBSDATE', COUNT=c1)

;; Get the LUT used
lutNum = SXPAR(fitsHdr,'IMGH001', COUNT=c2)

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

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

;; Get the filename of where the LUT is stored

;; The LUT filenames will be stored in the SQL database so they can be 
;; searched easily by time
serv = getSQLServer()
db = 'di_calib' 

;; Generate the SQL query to get the filename containing the LUT
tblNm = 'CMPLUT' 
sel = ['Filepath'] 
cond = "(DATE <= '"+date+"') and (INSTRUMENT='"+strtrim(inst,2) $
	+"') and (Idx="+strtrim(lutNum,2)+ $
	") order by DATE DESC, Version desc limit 1"

;; Query the database and make sure it returns useful data
webfn = DI_sqlQuery(serv, db, tblNm, sel, cond, DIM=dim)
IF min(dim) EQ 0 THEN $;; The database didn't have anything
	message, 'Could not find valid compression LUT', /NONAME

;; Get the local filename of the LUT to use
fn1 = getLocFn(webfn, subdir='CMPLUT')

;; Get the LUT. 
lut = readFITS(fn1[0])

out = in

;; If it's IR, also have to invert the signal
IF strtrim(inst,2) EQ 'HRIIR' THEN BEGIN
	out = 16383-out
	w_wrap = where(out GT 16383,wrapCnt)
	IF wrapCnt GT 0 THEN out[w_wrap] = out[w_wrap]-16384
ENDIF

;; Perform the compression
out = lut[out]

RETURN, out

END