;;-----------------------------------------------------------------------------
;; PURPOSE:
;;	Calculates the noise for each pixel in an image by root sum squaring
;;	the shot noise, read noise and quantization noise
;;
;; CALLING SEQUENCE:
;;	RESULT = dical_calcNoise(hdr, rawImg, flags, QUANT=quant)
;;
;; REQUIRED INPUTS:
;;	hdr - the fits header of the image
;;	rawImg - the raw image in DNs
;;	flags - the flags for the image
;;
;; OUTPUTS:
;;	RETURN - a frame specifying the noise in each pixel
;;
;; OPTIONAL INPUT KEYWORDS:
;;	quant - map of the quantization noise squared. This should be passed in
;;		if the image has been compressed as that value is calculated in 
;;		the decompression stage when the lookup table is available.
;;
;; EXAMPLE:
;;      IDL> noise=dical_calcNoise(hdr, rawImg, flags, QUANT=quant)
;;
;; PROCEDURES USED (i.e. called directly!):
;;	DI_sqlQuery - Query the SQL server
;;	getSQLServer - Retrives info on how to acess the SQL server
;;
;; MODIFICATION HISTORY:
;;   2005-09-20  M. Desnoyer    Created
;;
;;-----------------------------------------------------------------------------
FUNCTION dical_calcNoise, hdr, rawImg, flags, QUANT=quant

;; Parse the header
inst = sxpar(hdr,'INSTRUME', count=c1)
mode = sxpar(hdr, 'IMGMODE', count=c2)
date = sxpar(hdr, 'OBSDATE', count=c3)

IF c1 EQ 0 OR c2 EQ 0 OR c3 EQ 0 THEN message, 'Invalid FITS Header'

;; Check the parameters
IF size(rawImg, /n_dimensions) NE 2 THEN message, 'Invalid Image'
IF size(flags, /n_dimensions) NE 2 THEN message, 'Invalid Flag Map'

;; Figure out if the image is binned
isBinned = (mode EQ 1) OR (mode EQ 2) OR (mode EQ 3) OR (mode EQ 5)
 
;; Get the noise parameters from the database server
;; Parameters to access SQL database
serv = getSQLServer()
db = 'di_calib'
tblNm = 'NOISE_PARAMS'

sel = ['Quant',isBinned?'ReadBin':'ReadUnbin']
cond = "(Instrument='" + inst + "') AND (Date<='" + date + $
	"') order by Date DESC, Version desc limit 1"

data = DI_sqlQuery(serv, db, tblNm, sel, cond, DIM=dim)
IF max(dim) EQ 0 THEN $
	message, 'Database contained no noise parameters',/NONAME 

;; Start by calculating the quantization noise. This is the maximum of the 
;; noise specified in the database and the quantization noise passed in 
;; as a parameter.
noise = (data[0,0]^2/12)
IF n_elements(quant) GT 0 THEN noise = quant > noise

;; Now, add the read noise
noise = noise + data[1,0]^2

;; Now add on the shot noise
;; Figure out the gain
inst = strtrim(inst,2)
IF inst EQ 'HRIIR' THEN $
	gain = isBinned?60:15 $
ELSE $
	gain = 30

tmpHdr = hdr
noise = noise + abs((rawImg - getBias(tmpHdr,inst, date, mode, flags, OCLOCK=((inst NE 'HRIIR') AND (mode NE 8) AND (mode NE 7)), img=rawImg)))/gain

;; Finally take the square root of the squared sums
return, sqrt(noise)

END