FUNCTION di_dn2TempVolt, date, inst, keyName, dnVal, VALDATE=valdate

;;------------------------------------------------------------------------------
;; PURPOSE:
;;    	This function converts the raw DN value for temperature and voltage
;;	readings into physical values. This is done by looking up scaling
;;	coefficients in an sql database and applying the following polynomial:
;;
;;	Result = c0 + c1*dnVl + c2*dnVal^2
;;
;; CALLING SEQUENCE:
;;    	siVal = di_dn2TempVolt(date, inst, keyName, dnVal)
;;
;; REQUIRED INPUTS:
;;    	date - Date the image was taken.
;;	inst - String specifying the instrument (eg. 'HRIVIS')
;;	keyName - The keyword name for the value beign converted (eg. IMGH0004)
;;	dnVal - The DN value corresponding to keyName
;;
;; OUTPUTS:
;;    	The value in SI units
;;
;; OPTIONAL INPUT KEYWORDS:
;;	VALDATE - returns the date the used data was valid
;;
;; EXAMPLE:
;;      IDL> siVal = di_dn2TempVolt(date, 'HRIIR', 'IMGH031', 1253)
;;
;; PROCEDURES USED (i.e. called directly!):
;;    Functions: 
;;    Procedures:
;;
;; MODIFICATION HISTORY:
;;   2004-06-21  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------

;; The keyword name comming in might have a imghdr. tacked onto the front so 
;; remove it
IF strcmp(keyName, 'imghdr.',7) THEN $
	keyName = (strsplit(keyName,'.',/EXTRACT))[1]

;; Figure out how to get acess the database
serv = getSQLServer()
tbl = 'TEMPVOLT'
db = 'di_calib'
sel = ['c0', 'c1', 'c2', 'Date']
cond = 'Date <= "'+strtrim(date,2)+'" AND Instrument="'+strtrim(inst,2)+$
	'" AND FITSKey="'+keyName+'" order by Date desc, Version desc limit 1'

;; Query the database
c = di_sqlquery(serv, db, tbl, sel, cond, dim=dim)

IF max(dim) EQ 0 THEN $
	message, 'Could not find valid entry in conversion table to convert DN to temperature/voltage'

valdate = c[3]
c = double(c[0:2])

RETURN, c[0]+DNVal*(c[1]+c[2]*DNVal)

END