
function rd_flat_headers, wave, bfi=bfi, side=side, bin=bin, $
  flat_files=flat_files, help=help

waves_bfi = [ '6684', '4305', '3968', '3883', '4504', '5550' ]
waves_nfi = [ '6302', '5576', '5896', '5250', '5172', '6563' ]

if keyword_set(bfi) then print, waves_bfi else print, waves_nfi

if not exist(dir_top) then $
  dir_top = '/sanhome/slater/public_html/missions/hinode/sot/' + $
            (['nfi', 'bfi'])[keyword_set(bfi)] + '/flats'

pw_dir = curdir()
cd, dir_top
flat_dirs = $
  file_search('sot_' + (['nfi', 'bfi'])[keyword_set(bfi)] + '_flat_????A_?_?x?_????????_????')

if exist(wave) then begin
  ss_match_wave = where(strpos(flat_dirs, strtrim(wave,2) + 'A_') ne -1, n_match_wave)
  if n_match_wave gt 0 then begin
    flat_dirs = flat_dirs[ss_match_wave]
  endif else begin
    print, 'No flats matching requested wave found. Returning.'
    return, ''
  endelse
endif

if exist(side) then begin
  ss_match_side = where(strpos(flat_dirs, 'A_' + side + '_') ne -1, n_match_side)
  if n_match_side gt 0 then begin
    flat_dirs = flat_dirs[ss_match_side]
  endif else begin
    print, 'No flats matching requested ccd side found. Returning.'
    return, ''
  endelse
endif

if exist(bin) then begin
  pattern = '_' + strtrim(bin,2) + 'x' + strtrim(bin,2) + '_'
  ss_match_bin = where(strpos(flat_dirs, pattern) ne -1, n_match_bin)
  if n_match_bin gt 0 then begin
    flat_dirs = flat_dirs[ss_match_bin]
  endif else begin
    print, 'No flats matching requested binning found. Returning.'
    return, ''
  endelse
endif

;flat_files = file_search(flat_dirs, 'flat_????????_??????.gif')
 flat_files = flat_dirs + '/' + flat_dirs + '.fits'
ss_exist_arr = file_exist(flat_files)
ss_exist = where(ss_exist_arr ne -1, n_exist)
ss_not_exist = where(ss_exist_arr eq -1, n_not_exist)

if n_not_exist gt 0 then begin
  print, ' The following flat dirs do not contain a flat file with correct naming convention:
  prstr, flat_dirs[ss_not_exist]
endif

if n_exist gt 0 then begin
  flat_files = flat_files[ss_exist]
  mreadfits_header, flat_files, index_flat
endif else begin
  print, 'No flats matching request found. Returning.'
  return, ''
endelse

;if not keyword_set(no_display) then xstepper, flat_cube

cd, pw_dir
return, index_flat

end
