pro IRIS_CHECK_BADPIX, result, $
	silent = silent, pstop = pstop, save = save

;+
;
; Perform consistency checks on bad pixel maps
; 2022-08-10 RPT changing calibration files location
;-

cluster_dist_cutoff = 10

sswdata = CONCAT_DIR('$SSWDB','iris/data')

; Load flat index and badpix list
IRIS_FLAT_CATALOG, flat_index
badinds = FILE_SEARCH(CONCAT_DIR(sswdata, '*badpix.genx'))
badind_tai = ANYTIM2TAI(FILE2TIME(STRMID(FILE_BASENAME(badinds), 0, 15)))
latest = WHERE(badind_tai eq MAX(badind_tai))
RESTGEN, file = badinds[latest], str = badpix_str

; Loop through img_path and check for bad pixels
img_paths = ['SJI_1330', 'SJI_1400', 'SJI_2796', 'SJI_2832', 'SJI_1600W', 'SJI_5000W']
npath = N_ELEMENTS(img_paths)
for i = 0, npath - 1 do begin
	newbads = 0ll
	index = WHERE(flat_index.img_path eq img_paths[i], nn)
	flatframe = BYTARR(2072,1096,nn)
	for j = 0, nn-1 do begin
		recnum = flat_index[index[j]].recnum
		bplist = badpix_str.(recnum - 100)
		blankframe = BYTARR(2072,1096)
		blankframe[bplist] = 1
		flatframe[*,*,j] = blankframe
	endfor
	firstflat = flatframe[*,*,0]
	bpdiff = flatframe[*,*,1:*] - CONGRID(REFORM(FIX(firstflat), 2072,1096,1), 2072,1096,nn-1)
	totalflat = TOTAL(flatframe, 3)
	totalflat_bads = WHERE(totalflat ne 0, numtbad)
	smoothflat = SMOOTH(totalflat, 4) gt 3.5
	smoothflat_bads = WHERE(smoothflat ne 0, numsbad)
	for j = 0, numtbad - 1 do begin
		dists = SQRT( ( (totalflat_bads[j] / 2072) - (smoothflat_bads / 2072) )^2. + $
			( (totalflat_bads[j] mod 2072) - (smoothflat_bads mod 2072) )^2. )
		if MIN(dists) le cluster_dist_cutoff then newbads = [newbads, totalflat_bads[j]]
	endfor
	newbad_frame = BYTARR(2072,1096)
	newbad_frame[newbads] = 1
	if not KEYWORD_SET(silent) then $
		PLOOP, [ [[newbad_frame]], [[firstflat]], [[flatframe[*,*,nn-1]]] ], $
		title = ['New', 'Orig', 'Last']
	if KEYWORD_SET(pstop) then STOP
	if i eq 0 then result = CREATE_STRUCT(img_paths[i], newbads[1:*]) else $
		result = CREATE_STRUCT(result, img_paths[i], newbads[1:*])
endfor

if KEYWORD_SET(save) then begin
	ofile = CONCAT_DIR('~/data/iris/calibration/201506', TIME2FILE(/sec, RELTIME(/now)) + '_badpix.genx')
	for i = 0, N_ELEMENTS(flat_index) - 1 do begin
		tagname = 'F' + STRING(i+100,form = '(i03)')
		thispath = flat_index[i].img_path
		if STRMID(thispath, 0, 3) eq 'SJI' then begin
			thisarray = result.(WHERE(thispath eq img_paths))
		endif else begin
			thisarray = badpix_str.(i)
		endelse
		if i eq 0 then newbadpix_str = CREATE_STRUCT(tagname, thisarray) else $
			newbadpix_str = CREATE_STRUCT(newbadpix_str, tagname, thisarray)
		PRINT, thispath, N_ELEMENTS(thisarray), form = '(a20,i20)'
	endfor
	SAVEGEN, file = ofile, str = newbadpix_str
	
endif

end
