pro IRIS_PREP_CCDSTAT_LOGGER, index, data, $
	logdir = logdir, datarr = datarr

;+
;
; Writes some information about dark current in various CCD regions
; to a log file. See ITN 1 Figure 8 for description of regions
;
;
;-

date_obs = STRMID(TIME2FILE(index[0].t_obs), 0, 8)
if not KEYWORD_SET(logdir) then logdir = ''
txtpath = CONCAT_DIR(logdir, 'ccdstat')
if not FILE_EXIST(txtpath) then begin
	BOX_MESSAGE, ['IRIS_PREP_CCDSTAT_LOGGER: Output path does not exist!', txtpath]
	RETURN
endif
filename = CONCAT_DIR(txtpath, date_obs + '_ccdstat.txt')

nimgs = N_ELEMENTS(index)
sumspat = index[0].sumspat
sumsptrl = index[0].sumsptrl

columns = ['T_OBS', 'FSN', 'IMG_PATH', 'EXPTIME', 'INT_TIME', $
	'BLS1_MEAN', 'BLS1_STDEV', $	;	Port E; LL
	'BLS2_MEAN', 'BLS2_STDEV', $	;	Port F; UL
	'BLS3_MEAN', 'BLS3_STDEV', $	;	Port H; LR
	'BLS4_MEAN', 'BLS4_STDEV', $	;	Port G; UR
	'OSCAN1_MEAN', 'OSCAN1_STDEV', $	; Left Side
	'OSCAN2_MEAN', 'OSCAN2_STDEV']		; Right side
datarr = FLTARR(12,nimgs) + !values.f_nan

if not FILE_EXIST(filename) then begin
	OPENW, lun, /get, filename
	PRINTF, lun, columns, 'WRITTEN', form = '(A25,16A14,A25)'
endif else begin
	OPENW, lun, /get, filename, /append
endelse

dx = [0,2071,2072, 4143]
dy = [0, 19, 1076, 1095]

for i = 0, nimgs - 1 do begin
	; Rotate the image to lev0 orientation
	flip_rotate_dir = [0, 7, 5, 2]	;	map win_flip keyword to IDL's ROTATE function
	flipper = flip_rotate_dir[index[i].win_flip]
	thisdat = ROTATE(data[*,*,i], flipper)
	; Decide if it is a full frame or only a half frame
	if index[i].naxis1 * index[i].sumsptrl gt 2072 then jmax = 3 else jmax = 1
	; NUV images are the right half; SJI are the left half
	if index[i].img_path eq 'NUV' then begin
		oo = 2			;	Shift to the second set of regions
		ddx = [0, 19]	;	Oscans are on the left, not the right
	endif else begin
		oo = 0
		ddx = [2062, 2071, 2072, 2081]
	endelse
	; Read the BLS columns
	for j = 0, jmax do begin
		subarr = thisdat[(dx[(j/2)*2])/sumsptrl:(dx[(j/2)*2+1])/sumsptrl,dy[(j mod 2)*2]/sumspat:dy[(j mod 2)*2 + 1]/sumspat]
		gooddat = WHERE(subarr eq subarr, numgood)
		if numgood gt 1 then begin
			datarr[j*2+oo*2,i] = MEAN(subarr[gooddat])
			datarr[j*2+oo*2+1,i] = STDDEV(subarr[gooddat])
		endif	
	endfor
	; Read the overscan rows
	for j = 0, jmax gt 2 do begin
		subarr = thisdat[ddx[j*2]/sumsptrl:ddx[j*2+1]/sumsptrl,20/sumspat:1075/sumspat]
		gooddat = WHERE(subarr eq subarr, numgood)
		if numgood gt 1 then begin
			datarr[8+oo+j*2,i] = MEAN(subarr[gooddat])
			datarr[9+oo+j*2,i] = STDDEV(subarr[gooddat])
		endif
	endfor
	; Write the results to a text file
	PRINTF, lun, index[i].t_obs, index[i].fsn, index[i].img_path, index[i].exptime, $
		index[i].int_time, datarr[*,i], RELTIME(/now, out='CCSDS'), $
		format = '(a25,i14,a14,14f14.3,a25)'
endfor


FREE_LUN, lun

end
