FUNCTION DIcal_smooTemp, fitsHdr

;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Used in the DI Calibration Pipeline.
;;	Updates the header with a smoothed version of the IR temperatures if
;;	they have been calculated. This was done to help remove some of the
;;	noise in the temperature sensors
;;
;; CALLING SEQUENCE:
;;	out = DIcal_smooTemp(fitsHdr)
;;
;; REQUIRED INPUTS:
;;	fitsHdr - The FITS header for the image
;;
;; OUTPUTS:
;;	RETURN -  the updated FITS header
;;
;; OPTIONAL INPUT KEYWORDS:
;;
;; EXAMPLE:
;;      IDL> out = DIcal_smooTemp(fitsHdr)
;;
;; PROCEDURES USED (i.e. called directly!):
;;	SXPAR - Read FITS header
;;	FXADDPAR - Modifies the FITS header
;;	di_sqlquery
;;	getsqlserver
;;
;; MODIFICATION HISTORY:
;;   2005-11-04  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------

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

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

;; Get the expid
expid = SXPAR(fitsHdr, 'EXPID', COUNT=c1)

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

;; Get the image number in the sequence
imgNum = sxpar(fitsHdr, 'FNIMGNMB', count=c3)

;; Make sure we got everything from the header
IF c1 EQ 0 OR c2 EQ 0 OR c3 EQ 0 THEN message, 'Invalid FITS header', /noname

out = fitsHdr

;; Query the database for the updated temperatures
serv = getSQLserver()
db = 'di_calib'
tbl = 'SIMTEMPS_SMOOTH'
sel = ['NewTemp']
cond = 'DOY = '+strtrim(doy,2)+' AND ExpID = '+strtrim(expid, 2)+$
	' AND ImageNumber = '+strtrim(imgNum,2)+$
	' AND NewTemp>0 order by Date desc, Version desc limit 1'

catch, err
IF err NE 0 THEN return, out	;; There was an error getting the results. Oh well. Just finish cleanly

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

IF min(dim) EQ 0 THEN return, out

;; Make the changes to the FITS header
fxaddpar, out, 'SMOBENT', float(temp[0])

RETURN, out

END