function IRIS_PREP_MAKE_FLAT_INDEX, $
	path = path, save = save, badpix = badpix

;+
;
; Expects flatfield fits files written in the format
;	flat_SJI_1330_20140101_120000.fits
;	flat_NUV_DETECTOR_20150101_180000.fits
;	etc. 
; with a 2-D array in each file.
;
; Makes an output called YYYYMMDD_HHMMSS_flat.genx
; 2022-08-10 RPT changing calibration files location
;-

; Set up necessary constants
ttag = TIME2FILE(/sec, RELTIME(/now))
flat_index_template = {img_path : 'SJI_1330', filetime : '20130101_000000', $
	filetai : 1735689635d, filename : 'flat_SJI_1330_20130101_000000.fits', $
	posttime : ttag, recnum : 0l}
imgpaths = ['SJI_5000W', 'SJI_2832', 'SJI_2796', 'SJI_1600W', 'SJI_1400', 'SJI_1330', $
	'FUV_DETECTOR', 'FUV_SPATIAL', 'NUV_DETECTOR', 'NUV_SPATIAL', 'SJI_NUV']
if N_ELEMENTS(path) eq 0 then path = CONCAT_DIR('$SSWDB','iris/data')

; Check to see how many FITS files are available
flatfiles = FILE_SEARCH(CONCAT_DIR(path, 'flat_*.fits'))
numfiles = N_ELEMENTS(flatfiles)
flat_index = REPLICATE(flat_index_template, numfiles)
numused = 0

; Load the current flat index to append to
indexfiles = FILE_SEARCH(CONCAT_DIR(path, '*flat.genx'))
if indexfiles[0] ne '' then begin
	filetime = STRMID(FILE_BASENAME(indexfiles), 0, 15)
	filetai = ANYTIM2TAI(FILE2TIME(filetime))
	latest_ind = WHERE(filetai eq MAX(filetai))
	RESTGEN, file = indexfiles[latest_ind], old_index
	numused = N_ELEMENTS(old_index)
	for i = 0, numused-1 do flat_index[i] = old_index[i]
endif

; Go through all the FITS files and write them in if they aren't already in use
for i = 0, numfiles - 1 do begin
	thisfile = FILE_BASENAME(flatfiles[i])
	splitfile = STRSPLIT(/extract, thisfile, '_')
	thispath = STRJOIN(splitfile[1:2], '_')
	thispathind = WHERE(thispath eq imgpaths, ispath)
	if ispath lt 1 then begin
		PRINT, 'IRIS_PREP_READ_FLATS: Hmm, weird img_path'
	endif else begin
		thisfiletime = STRJOIN(splitfile[3:4], '_')
		thisfileutc = FILE2TIME(/ccsds, thisfiletime)
		thisfiletai = ANYTIM2TAI(thisfileutc)
		thismatch = WHERE(flat_index.img_path eq thispath and $
			flat_index.filetai eq thisfiletai, ismatch)
		if ismatch eq 0 then begin
			flat_index[numused].img_path = thispath
			flat_index[numused].filetime = thisfiletime
			flat_index[numused].filetai = thisfiletai
			flat_index[numused].filename = thisfile
			flat_index[numused].recnum = (MAX(flat_index.recnum) + 1) > 100
			numused = numused + 1
		endif
	endelse
endfor

; Clean up the filetime
flat_index.filetime = FILE_BASENAME(flat_index.filetime, '.fits')

; Check and make sure everything worked out ok
if MIN(flat_index.recnum) lt 1 then STOP

if KEYWORD_SET(save) then begin
	ofile = CONCAT_DIR(path, ttag + '_flat.genx')
	SAVEGEN, flat_index, file = ofile
endif

if KEYWORD_SET(badpix) then begin
	bpstr = IRIS_PREP_MAKE_BADPIX(flat_index, ttag, /write, path = path, /static)
endif

RETURN, flat_index

end
