pro iris_pipeline_makecal, obs_str, l1files, drms, testing=testing, _extra=_extra
;
;   Name: iris_pipeline_makecal
;
;   Purpose: generate iris_prep calibration files - pre-pass prior to calling L12L2,/pipeline (which uses these)
;
;   Input Parameters:
;      obs_str - structure for selected OBS, generally from iris_time2timeline output
;      l1files - list of Level1 files associated with this OBS
;      drms - metadata, generally from jsoc/ssw_jsoc_time2data - at least .IMG_PATH
;
;   Keyword Parameters:
;      testing - if set, just show what this would do, but don't do anything...
;      _extra - keywords -> read_iris, iris_prep
;
;   History:
;      9-jun-2015 - S.L.Freeland per Paul Boerner 29-May email
;     10-jun-2015 - add _extra -> iris_prep,read_iris
;     12-jun-2015 - remove the /prep/.../<obs>/ logdir prior to mk_dir
;     15-oct-2015 - replace /NRT_PIPELINE in iris_prep call with explicit keyword settings
;                   remove _extra from iris_prep call since explicit settings desired
;-

testing=keyword_set(testing)

if n_params() lt 3 or (1-required_tags(obs_str,'date_obs,obsid')) then begin
   box_message,['IDL> iris_pipeline_makecal,obs_str,l1files,drms','returning with no action']
   return ; EARLY EXIT on bad input
endif

; Set up output paths
obsid = obs_str.obsid
tstart = TIME2FILE(/sec, obs_str.date_obs)
parent=concat_dir('$IRIS_DATA','prep')
logdir=concat_dir(ssw_time2paths(parent=parent,times=obs_str.date_obs),arr2str([tstart, STRTRIM(obsid, 2)],'_'))
subpaths = ['fid', 'wavecorr', 'dose', 'ccdstat', 'aiacorr']
alldirs=[logdir,concat_dir(logdir,subpaths)]
if testing then box_message,['mk_dir',alldirs] else begin
   spawn,['rm','-rf',logdir],/noshell
   if get_logenv('check_rm') ne '' then stop,'rm logdir?'
   mk_dir,alldirs ; make all implied directories
endelse

; Prep the images and measure the fiducial/wavelength shift in the results
img_paths = ['NUV', 'SJI_1330', 'SJI_1400', 'SJI_2796', 'SJI_2832', 'SJI_1600W', 'SJI_5000W', 'FUV']
npaths = N_ELEMENTS(img_paths)
for i = 0, npaths - 1 do begin
   thispath = img_paths[i]
   index = WHERE(drms.img_path eq thispath, numind)
   if testing then print,'# ' + img_paths[i] + ' = ' + strtrim(numind,2) else begin 
      if numind gt 0 then begin
         READ_IRIS, l1files[index], hdr, dat, _extra=_extra
         if get_logenv('l1_list') ne '' then file_append,concat_dir(logdir,'l1_list'),l1files[index]
         IRIS_PREP, hdr, dat, ohdr_dummy, odat_dummy, $
            poly2d = 1,update_roll = 1,measure_aia = 1,post_warp = 1,verbose = 1, $
            run_time = 1, shift_wave = 1, shift_fid = 1, write = 1, pipeline = 0, $
            logdir = logdir
       endif else box_message,'No images for 
   endelse
endfor

; 
; Now make the obsfits.genx file
if testing then print,'would now do:  IRIS_PREP_PIPELINE_PATCH_OBS, obs_str, logdir' else $
   IRIS_PREP_PIPELINE_PATCH_OBS, obs_str, logdir


return
end
