pro IRIS_PREP_DOSE_LOGGER, index, data, $
	logdir = logdir

;+
;
; Writes a text file and two FITS files showing how many DN were read out by
; each image, how many seconds worth of exposure were read out, and how long
; each CCD sector was exposed for.
;
;
; JPW 2017-05-19 fixed bug that neglected to divide rebinned image by sumspat*sumsptrl
;-

if not KEYWORD_SET(logdir) then logdir = ''
nimgs = N_ELEMENTS(index)
; If there are multiple images, check to make sure that they all have the same
; date and img_path
if nimgs gt 1 then begin
	imgpath = index[0].img_path
	sumspat = index[0].sumspat
	sumsptrl = index[0].sumsptrl
	diffpath = WHERE(index.img_path ne imgpath or index.sumspat ne sumspat or $
		index.sumsptrl ne sumsptrl, numdiff)
	if numdiff ne 0 then begin
		BOX_MESSAGE, ['IRIS_PREP_DOSE_LOGGER: Mixed img_paths or summing', $
			'Exiting without logging...']
		RETURN
	endif
	date_obs = STRMID(TIME2FILE(index.t_obs), 0, 8)
	dsort = SORT(date_obs)
	udate = UNIQ(date_obs, dsort)
	numdate = N_ELEMENTS(udate)
	if numdate gt 1 then begin
		for i = 0, numdate - 1 do begin
			thisdate = date_obs[dsort[udate[i]]]
			thisind = WHERE(date_obs eq thisdate)
			IRIS_PREP_DOSE_LOGGER, index[thisind], data[*,*,thisind], logdir = logdir
		endfor
		RETURN
	endif
endif

common IRIS_PREP_DOSE_CB, cb_date_obs, fd_fits, nd_fits, fr_fits, nr_fits

nimgs = N_ELEMENTS(index)
fsnmask = BYTARR(nimgs)
date_obs = STRMID(TIME2FILE(index[0].t_obs), 0, 8)
if N_ELEMENTS(cb_date_obs) eq 0 then cb_date_obs = ''
txtpath = CONCAT_DIR(logdir, 'dose')
if not FILE_EXIST(txtpath) then begin
	BOX_MESSAGE, ['IRIS_PREP_DOSE_LOGGER: Output path does not exist!', txtpath]
	RETURN
endif

filename = CONCAT_DIR(txtpath, date_obs + '_dose.txt')
fd_fitsname = CONCAT_DIR(txtpath, date_obs + '_fdose.fits')	;	DN/pixel in all images
nd_fitsname = CONCAT_DIR(txtpath, date_obs + '_ndose.fits')
fr_fitsname = CONCAT_DIR(txtpath, date_obs + '_fread.fits')	;	seconds/pixel of exposure read out
nr_fitsname = CONCAT_DIR(txtpath, date_obs + '_nread.fits')

sumspat = index[0].sumspat
sumsptrl = index[0].sumsptrl

columns = ['T_OBS', 'FSN', 'IMG_PATH', 'EXPTIME']

count = nimgs
todo = LINDGEN(nimgs)						;	List of which files need to be logged
if not FILE_EXIST(filename) then begin		;	Nothing for today; define the log and FITS files
	OPENW, lun, /get, filename
;	PRINTF, lun, columns, 'WRITTEN', form = '(A25,3A11,A25)'
	PRINTF, lun, columns, 'WRITTEN V2', form = '(A25,3A11,A25)' ; inconspicuously mark fixed version without
	                                                            ; affecting output from iris_prep_txt2str
	fd_fits = FLTARR(4144,1096)
	nd_fits = FLTARR(4144,1096)
	fr_fits = FLTARR(4144,1096)
	nr_fits = FLTARR(4144,1096)
	WRITEFITS, fd_fitsname, fd_fits
	WRITEFITS, nd_fitsname, nd_fits
	WRITEFITS, fr_fitsname, fr_fits
	WRITEFITS, nr_fitsname, nr_fits
endif else begin							; 	Some dose images have already been written for today
	logdat = RD_TFILE(filename, 4)			;	Check and see if this image has been logged
	numlines = N_ELEMENTS(logdat) / 4
	if numlines gt 0 then begin
		logfsns = LONG(REFORM(logdat[1,1:*]))
		newfsns = SETDIFFERENCE(index.fsn, logfsns, count=count, positions=todo)
	endif
	if count eq 0 then begin
		PRINT, 'IRIS_PREP_DOSE_LOGGER: All FSNs already logged...'
		RETURN
	endif
	OPENW, lun, /get, filename, /append		;	open log file for appending
	;	If common block not loaded; read today's FITS files	
	if cb_date_obs ne date_obs then begin
		MREADFITS, fd_fitsname, fd_head, fd_fits
		MREADFITS, nd_fitsname, nd_head, nd_fits
		MREADFITS, fr_fitsname, fr_head, fr_fits
		MREADFITS, nr_fitsname, nr_head, nr_fits
		cb_date_obs = date_obs
	endif
endelse

; Stack the dose and readout time for all the images passed in
dsize = SIZE(data)
isint = dsize[-2] lt 4
fulldoseimg = FLTARR(dsize[1] * index[0].sumsptrl, dsize[2] * index[0].sumspat)
fullreadimg = FLTARR(dsize[1] * index[0].sumsptrl, dsize[2] * index[0].sumspat)
for i = 0, count - 1 do begin
	thisdoseimg = REBIN(FLOAT(data[*,*,todo[i]]), $
		index[todo[i]].naxis1 * index[todo[i]].sumsptrl, $
		index[todo[i]].naxis2 * index[todo[i]].sumspat)<1.6e4
	thisreadimg = thisdoseimg
	thisreadimg[*] = 0. + index[todo[i]].exptime
	if isint then thisbadpoints = WHERE(thisdoseimg eq -32768., numbad) $
		else thisbadpoints = WHERE(thisdoseimg ne thisdoseimg, numbad)
	if numbad gt 0 then begin
		thisreadimg[thisbadpoints] = 0.
		thisdoseimg[thisbadpoints] = 0.
	endif
        sumscalfac = float(index[todo[i]].sumsptrl*index[todo[i]].sumspat)
;	fulldoseimg = fulldoseimg + thisdoseimg
	fulldoseimg = fulldoseimg + thisdoseimg / sumscalfac  ; fix JPW 2017-05-19
	fullreadimg = fullreadimg + thisreadimg
	PRINTF, lun, index[todo[i]].t_obs, index[todo[i]].fsn, $
		index[todo[i]].img_path, index[todo[i]].exptime, RELTIME(/now, out='CCSDS'), $
		form = '(A25,I11,A11,F11.3,A25)'
endfor

FREE_LUN, lun

; Add the results to what's saved and write it back into the FITS file
case index[0].img_path of
	'FUV'	:	begin
		fd_fits = fd_fits + fulldoseimg
		fr_fits = fr_fits + fullreadimg
		WRITEFITS, fd_fitsname, fd_fits
		WRITEFITS, fr_fitsname, fr_fits	
	end
	'NUV-SJI'	:	begin		;	Hmm...who is really exposed in an NUV-SJI image?
		nd_fits = nd_fits + fulldoseimg
		nr_fits = nr_fits + fullreadimg
		WRITEFITS, nd_fitsname, nd_fits
		WRITEFITS, nr_fitsname, nr_fits	
	end
	'NUV'	:	begin
		nd_fits[2072:*,*] = nd_fits[2072:*,*] + fulldoseimg
		nr_fits[2072:*,*] = nr_fits[2072:*,*] + fullreadimg
		WRITEFITS, nd_fitsname, nd_fits
		WRITEFITS, nr_fitsname, nr_fits	
	end
	else	:	begin
		fulldoseimg[1036:*,*] = 0.			;	Other SJI channel is not exposed
		fullreadimg[1036:*,*] = 0.		
		isfuv = FIX(STRMID(index[0].img_path, 4, 1)) eq 1	;	FUV slit jaw will be flipped
		if isfuv then begin
			fulldoseimg = ROTATE(fulldoseimg, 5)	;	Flip X to -X 
			fullreadimg = ROTATE(fullreadimg, 5)
		endif
		nd_fits[0:2071,*] = nd_fits[0:2071,*] + fulldoseimg
		nr_fits[0:2071,*] = nr_fits[0:2071,*] + fullreadimg
		WRITEFITS, nd_fitsname, nd_fits
		WRITEFITS, nr_fitsname, nr_fits	
	end
	else	:	PRINT, 'IRIS_PREP_DOSE_LOGGER: wtf?'
endcase

end
