function IRIS_PREP_GET_BADPIX, iindex, $
	badpix_recnum = badpix_recnum

;+
;
; Load a previously-generated bad pixel map corresponding to a FITS header
;
; INPUTS:
;	iindex	-	FITS header for which you want the bad pixel map. Looks at the
;				img_path and t_obs
;
; RETURNS:
;	badpix_list -	A vector of LONG64 pixel addresses specifying the location
;					of badpixels in the input image
;
;  2022-08-10 RPT changing calibration files location
;-

; Load the flatfield common block, and the bad pixel common block
common IRIS_PREP_BADPIX_CB, badpix_str
common IRIS_PREP_FLAT_CB, flat_index, flat_loaded, flat_sji_2832, flat_sji_2796, $
	flat_sji_5000w, flat_sji_1330, flat_sji_1400, flat_sji_1600w, $
	flat_fuv_detector, flat_fuv_spatial, flat_nuv_detector, flat_nuv_spatial, $
	flat_sji_nuv
sswdata = CONCAT_DIR('$SSWDB','iris/data')

; Read in the index of all available flats if necessary
; There should be only one index, but in case there are multiples it uses the
; one with the most recent date in its filename
if N_TAGS(flat_index) eq 0 then begin
	flatinds = FILE_SEARCH(CONCAT_DIR(sswdata, '*flat.genx'))
	flatind_tai = ANYTIM2TAI(FILE2TIME(STRMID(FILE_BASENAME(flatinds), 0, 15)))
	latest = WHERE(flatind_tai eq MAX(flatind_tai))
	RESTGEN, file = flatinds[latest], flat_index
endif

; Read in the list of all available bad pixel maps if necessary
; There should be only one index, but in case there are multiples it uses the
; one with the most recent date in its filename
;RPT for 'program code full' 9/14/16
if N_TAGS(badpix_str) eq 0 then begin
	badinds = FILE_SEARCH(CONCAT_DIR(sswdata, '*badpix.geny'))
	badind_tai = ANYTIM2TAI(FILE2TIME(STRMID(FILE_BASENAME(badinds), 0, 15)))
	latest = WHERE(badind_tai eq MAX(badind_tai))
;	RESTGENX, file = badinds[latest], str = badpix_str
; RPT I don't understand why 1-element STR array vs str but oh well...
        filenamearr = badinds[latest]
        filename = filenamearr(0)
        RESTGENX, result, file=filename
        badpix_str = result
endif

; Determine the flatfield recnum needed
taiobs = MIN(ANYTIM2TAI(iindex.t_obs))
imgpath = iindex[0].img_path
if STRMID(imgpath, 0, 3) ne 'SJI' then imgpath = imgpath + '_DETECTOR'
indexind = WHERE(imgpath eq flat_index.img_path)
thispath_index = flat_index[indexind]
taidiff = ABS(taiobs - thispath_index.filetai)
index_addr = WHERE(taidiff eq MIN(taidiff))
badpix_recnum = thispath_index[index_addr[0]].recnum

; Use that flatfield recnum to look up the badpixel list
tagind = WHERE(TAG_NAMES(badpix_str) eq 'F' + STRTRIM(badpix_recnum, 2))
badpix_list = badpix_str.(tagind[0])

RETURN, badpix_list

end
