;
;+
;
;  Averages a cube of images, accounting for saturated and missing
;  data.

PRO sxt_average1, data, texp, average, satpix=satpix, unc=unc, error=error, sum=sum, expose=expose, missing=missing

;
; Inputs:
;	data =  data cube, calibrated, to be averaged. 
;	texp = vector of exposure times for the images in data, milliseconds
;
; Outputs:
;	average = average image, DN/millisec
;
; Optional Keywords:
;   Input:
;	satpix = cube of saturated pixels
;	unc = cube of decompression uncertainty. Used to compute error image.
;	missing = lowest valid data value.  Default = 0.  To preserve
;		accuracy, set this to a large negative number, < -4096.
;   Output:
;	sum = sum image, DN
;	expose = exposure time image, milliseconds
;	error = uncertainty image, DN. Derived from unc cube.
;
;
; History:
;	Written June 3, 1993 Barry LaBonte
;	Add uncertainty, sum, time images   February 2, 1994   BJL
;	Add /MISSING keyword	March 4, 1994   BJL
;
;-
;



asize = SIZE(data)
; Set valid threshold
IF( KEYWORD_SET(missing) EQ 0 ) THEN missing = 0

valid = REPLICATE(1., asize(1), asize(2), asize(3))
miss = WHERE(data LE missing, count) 
IF(count  GT 0) THEN valid(miss) = 0.
IF(KEYWORD_SET(satpix) GT 0) THEN valid = valid < (1 - satpix)

; Sum only valid data
time = FLTARR(asize(1), asize(2))
tot = time
error = time
average = time
IF(KEYWORD_SET(unc) GT 0) THEN error=time
FOR k=0,asize(3)-1 DO BEGIN
	time = time + texp(k) *  valid(*,*,k)
	tot = tot + data(*,*,k) * valid(*,*,k)
	IF(KEYWORD_SET(unc) GT 0) THEN error = error + unc(*,*,k)^2 * valid(*,*,k)
ENDFOR

good = WHERE(time GT 0)
average(good) = tot(good)/time(good)
IF(KEYWORD_SET(unc) GT 0) THEN error = SQRT(error)
sum = tot
expose = time

RETURN
END
