
pro nn_test_movie, files_genx=files_genx, case_nums=case_nums, $
  mapr_sot=mapr_sot, max_frames=max_frames, add_map_waves=add_map_waves, $
  no_derot=no_derot, $
  do_sot_map_movie=do_sot_map_movie, do_sdo_map_movie=do_sdo_map_movie, $
  do_interleave_movie=do_interleave_movie, do_corr_plots=do_corr_plots, $
  verbose=verbose, debug=debug, do_debug=do_debug, _extra=_extra

if not exist(drotate) then drotate = 1
;if not keyword_set(debug) then debug = 1
if not keyword_set(verbose) then verbose = 1
if not exist(dt_max) then dt_max = 12 ; 60 ; seconds
if not exist(wait_read_sdo_fail) then wait_read_sdo_fail = 0.4

;if not exist(dir_top) then $
;  dir_top = '/sanhome/slater/public_html/outgoing/slater/sot_corr_testing'
if not exist(dir_top) then begin
  if get_logenv('SOT_CORR_DB') eq '' then $
    set_logenv, 'SOT_CORR_DB', concat_dir(concat_dir(get_logenv('SSWDB'), 'hinode/gen'), 'hinode_sdo_alignment')
;   set_logenv, 'SOT_CORR_DB', concat_dir(get_logenv('HOME'), 'sot_corr_db')
; mk_dir, get_logenv('SOT_CORR_DB')
  mk_dir, concat_dir(get_logenv('SOT_CORR_DB'), 'database')
  dir_top = get_logenv('SOT_CORR_DB')
endif
  
if not exist(dir_genx) then dir_genx = dir_top
if not exist(files_genx) then files_genx = file_list(dir_genx, 'case_num*.genx')

file_log_exec_times = concat_dir(dir_top, 'sot_l1_mapgen_exec_times.log')
n_files_genx = n_elements(files_genx)

if exist(case_nums) then begin
  n_case = n_elements(case_nums)
  st_case = case_nums[0]
  en_case = case_nums[n_case-1]
endif else begin
  n_case = n_files_genx
  st_case = 0
  en_case = n_files_genx-1
endelse

for j=st_case, en_case do begin
  delvarx, ref_wcs, mapr_sot, mapr_sdo_arr

  rd_genx, files_genx[j], buff
  index_sot_corr = buff.savegen0
if exist(max_frames) then index_sot_corr = index_sot_corr[0:(max_frames-1)]
  n_img = n_elements(index_sot_corr)

  files_sot = reform(index_sot_corr.file_sot)

  read_sot, files_sot, index_sot_uncorr, data_sot

; Convert index, data arrays to maps:
  if keyword_set(verbose) then print, ' Begin conversion of sot index, data arrays to map array.'
  if keyword_set(debug) then STOP, ' Stopping before index2map call for sot.'
  index2map, index_sot_corr, data_sot, map_sot
  if keyword_set(verbose) then print, ' Completed conversion of sot index, data arrays to map array.'

; Create self-registered SOT map:
  if keyword_set(verbose) then print, ' Begin creation of registered map.'
  if keyword_set(debug) then STOP, ' Stopping before coreg_map call for sot.'
  mapr_sot = coreg_map(map_sot, map_sot[0], drotate=drotate)
  if keyword_set(verbose) then print, ' Completed creation of registered map.'

; Optionally save the SOT registered map:
  if keyword_set(do_write) then begin
    file_sot_map_sav = concat_dir(dir_genx, filnams_genx[j] + '.sav')
    save, files_sot, index_sot_uncorr, index_sot_corr, mapr_sot, file=file_sot_map_sav
  endif

  if keyword_set(do_sot_map_movie) then begin
    movie_map, mapr_sot
;   movie_map, mapr_sot, center=[index_sot_corr[0].xcen, index_sot_corr[0].ycen], fov=[4,4]  
STOP
    print, "type '.con' and return to continue."
;   print, 'Type any key to continue.'
;   dum = get_kbrd(1)
  endif

  if exist(add_map_waves) then begin
    n_add_map_waves = n_elements(add_map_waves)
    n_frames = n_elements(index_sot_corr)

    for kkk = 0, n_add_map_waves-1 do begin

      for kk = 0, n_frames-1 do begin
delvarx, index_add_wave0, file_add_wave0, data_sdo
        ssw_jsoc_time2data, anytim(anytim(index_sot_corr[kk].date_obs)-50., /ccsds), $
                            anytim(anytim(index_sot_corr[kk].date_obs)+50., /ccsds), $
          wave=add_map_waves[kkk], index_add_wave0, file_add_wave0, /files_only ;, xquery=xquery
        if ( (exist(file_add_wave0)) and (size(index_add_wave0, /type) eq 8) ) then begin
          min_t_off_sec_sdo = min(abs(anytim(index_sot_corr[kk].date_obs) - $
                                      anytim(index_add_wave0.date_obs)), ss_min_t_off)
          file_add_wave0 = file_add_wave0[ss_min_t_off]
          index_add_wave0 = index_add_wave0[ss_min_t_off]
        endif else begin
          stop, 'No close enough in time files found for this sot image and add wave.  Stopping.'
        endelse

; Calculate cutout coordinates for read_sdo:
x_pix_sot_llur_fov = [0, index_sot_corr[kk].naxis1-1]
y_pix_sot_llur_fov = [0, index_sot_corr[kk].naxis2-1]
pix_sot_llur_fov = transpose([[x_pix_sot_llur_fov], [y_pix_sot_llur_fov]])

pix_sdo_llur_fov = wcs_pix2pix_2(pix_sot_llur_fov, index_sot_corr[kk], index_add_wave0)

;xllp_sdo = min([pix_sdo_llur_fov[0,0], pix_sdo_llur_fov[0,1]])
;yllp_sdo = min([pix_sdo_llur_fov[1,0], pix_sdo_llur_fov[1,1]])
xllp_sdo = round(min([pix_sdo_llur_fov[0,0], pix_sdo_llur_fov[0,1]]))
yllp_sdo = round(min([pix_sdo_llur_fov[1,0], pix_sdo_llur_fov[1,1]]))
xurp_sdo = max([pix_sdo_llur_fov[0,0], pix_sdo_llur_fov[0,1]])
yurp_sdo = max([pix_sdo_llur_fov[1,0], pix_sdo_llur_fov[1,1]])

nxp_sdo0  = ceil(xurp_sdo) - floor(xllp_sdo) + 1
nyp_sdo0  = ceil(yurp_sdo) - floor(yllp_sdo) + 1
nxp_sdo = ceil(index_sot_corr[kk].naxis1*(index_sot_corr[kk].cdelt1 / index_add_wave0.cdelt1) ) + 1
nyp_sdo = ceil(index_sot_corr[kk].naxis2*(index_sot_corr[kk].cdelt2 / index_add_wave0.cdelt2) ) + 1
if not exist(nxp_sdo_arr) then begin
  nxp_sdo0_arr  = nxp_sdo0
  nyp_sdo0_arr  = nyp_sdo0
  nxp_sdo_arr = nxp_sdo
  nyp_sdo_arr = nyp_sdo
endif else begin
  nxp_sdo0_arr  = [nxp_sdo0_arr, nxp_sdo0]
  nyp_sdo0_arr  = [nyp_sdo0_arr, nyp_sdo0]
  nxp_sdo_arr = [nxp_sdo_arr, nxp_sdo]
  nyp_sdo_arr = [nyp_sdo_arr, nyp_sdo]
endelse
print, nxp_sdo_arr
print, nxp_sdo0_arr
print, nyp_sdo_arr
print, nyp_sdo0_arr

t0_exec_read_sdo_sec = anytim(!stime)

if ( (add_map_waves[kkk] eq 'blos') or (add_map_waves[kkk] eq 'cont') ) then begin
  uncomp_delete = 1
  use_index = 1
  use_shared = 0 ; NOTA BENA - 'use_shared' flag apparently incompatible with 'use_index' flag.
  noshell = 1
endif else begin
  uncomp_delete = 1
  use_index = 0 ;1
  use_shared = 0
  noshell = 1
endelse

read_sdo, file_add_wave0, index_add_wave0, data_sdo, $
          xllp_sdo, yllp_sdo, nxp_sdo, nyp_sdo, $
          uncomp_delete=uncomp_delete, use_index=use_index, use_shared=use_shared, noshell=noshell
;read_sdo, file_add_wave0, index_add_wave0, data_sdo, $
;          xllp_sdo, yllp_sdo, nxp_sdo, nyp_sdo, $
;          /uncomp_delete, /noshell

; If read_sdo failed, try once more:
if not exist(data_sdo) then begin
  print, 'READ_SDO failed.  Re-reading after wait.'
  wait, wait_read_sdo_fail
  read_sdo, file_add_wave0, index_add_wave0, data_sdo, $
            xllp_sdo, yllp_sdo, nxp_sdo, nyp_sdo, $
            uncomp_delete=uncomp_delete, use_index=use_index, use_shared=use_shared, noshell=noshell
;  read_sdo, file_add_wave0, index_add_wave0, data_sdo, $
;            xllp_sdo, yllp_sdo, nxp_sdo, nyp_sdo, $
;            /uncomp_delete, /noshell
endif

t1_exec_read_sdo_sec = anytim(!stime)

if ( (not exist(index_add_wave0)) or (not exist(data_sdo)) ) then begin
  stop, 'Either INDEX_SDO or DATA_SDO does not exist. Stopping.' 
  return
endif

if not tag_exist(index_add_wave0, 'crota2') then begin
  stop, " SDO image header has no 'CROTA2' tag. Stopping."
  return
endif

file_sdo  = file_add_wave0
index_sdo = index_add_wave0

; Optionally prep SDO image:
;do_prep_sdo=1
if keyword_set(do_prep_sdo) then begin
  aia_prep, index_sdo, data_sdo, indexp_sdo, datap_sdo
endif else begin
  indexp_sdo = index_sdo
  datap_sdo = data_sdo
endelse

print, 'De-rotate add wave image to SOT reference map.'
index2map, indexp_sdo, datap_sdo, mapp_sdo

; KLUGE - Attempt to correct for apparent indexing error in READ_SDO coordinate reference:
mapp_sdo.xc = mapp_sdo.xc - indexp_sdo.cdelt1
mapp_sdo.yc = mapp_sdo.yc - indexp_sdo.cdelt2

dt_sdo = anytim(indexp_sdo.date_obs) - anytim(index_sot_corr[0].date_obs)
if abs(dt_sdo) le dt_max then no_drotate = 1 else no_drotate = 0


rmapp_sdo = drot_map(mapp_sdo, ref_map=mapr_sot[0], no_drotate=no_drotate, $
                     rigid=rigid, no_project=no_project, _extra=_extra)

      if not exist(mapr_add_wave_arr) then begin
;        sdo_data_arr = congrid(mapp_sdo.data, index_sot_corr[kk].naxis1, index_sot_corr[kk].naxis2)
;        mapp_sdo_arr = mapp_sdo
        mapr_add_wave_arr = rmapp_sdo
      endif else begin
;        sdo_data_arr = [[[sdo_data_arr]], $
;                        [[congrid(mapp_sdo.data, index_sot_corr[kk].naxis1, index_sot_corr[kk].naxis2)]]]
;        mapp_sdo_arr = concat_struct(mapp_sdo_arr, mapp_sdo)
        mapr_add_wave_arr = concat_struct(mapr_add_wave_arr, rmapp_sdo)
      endelse


      endfor


; Optionally save the SDO registered map
  if keyword_set(do_write) then begin
    file_sdo_map_sav = concat_dir(dir_genx, filnams_genx[j] + '_' + add_map_waves[kkk-1] + '.sav')
;   save, files_add_wave, index_add_wave_arr, mapr_add_wave_arr, file=file_sdo_map_sav
;   save, index_add_wave_arr, mapr_add_wave_arr, file=file_sdo_map_sav
    save, mapr_add_wave_arr, file=file_sdo_map_sav
  endif

  if keyword_set(do_sdo_map_movie) then begin
    movie_map, mapr_add_wave_arr, center=[index_sot_corr[0].xcen, index_sot_corr[0].ycen], fov=[4,4]  
    print, "type '.con' and return to continue."
STOP
;   print, 'Type any key to continue.'
;   dum = get_kbrd(1)
  endif

if keyword_set(do_corr_plots) then begin
  wdef,0,1280,1024
  !p.multi = [0,1,3]
  !p.charsize = 3
  !p.psym = -2
  !p.symsize = 2
  !p.linestyle = 4
  utplot, index_sot_corr.t_sot, index_sot_corr.xdisp_rot, /ynoz, title='X Corr Offset (arcsec)'
  utplot, index_sot_corr.t_sot, index_sot_corr.ydisp_rot, /ynoz, title='Y Corr Offset (arcsec)'
  utplot, index_sot_corr.t_sot, index_sot_corr.peak_str,  /ynoz, title='peak_str = (mx-mean(cc)) / stddev(cc)'
endif
  
; Optionally display interleaved movie:
if keyword_set(do_interleave_movie) then begin
  data_interleave = intarr(index_sot_corr[0].naxis1, index_sot_corr[0].naxis2, n_frames*2)
  for k=0,n_frames-1 do data_interleave[0,0,k*2]   = mapr_sot[k].data
  for k=0,n_frames-1 do data_interleave[0,0,k*2+1] = mapr_add_wave_arr[k].data
  xstepper, data_interleave
endif

if keyword_set(do_debug) then STOP, 'Stopping on request after xstepper of interleaved movie.'

    endfor

  endif ; End 'add_map_waves' optional loop

endfor

end
