
function xrt_index2planinfo, index, hcr_window=hcr_window, cache_window=cache_window, $
   hcr_select=hcr_select, quiet=quiet, refresh=refresh, debug=debug, verbose=verbose, $
   _extra=_extra

;+
;   Input Parameters:
;      index - vector of one or more indices
;
;   Output:
;      function returns index w/added HCR/Planning tags 
;         Any or all of the following tags may be updated if values were sumbitted by
;         planner to metadata for the observation(s) corresponding to the input index: 
;            obstitle
;            target
;            sci_obj
;            sci_obs
;            obs_dec
;            join_sb
;            obs_num
;            jop_id
;            noaa_num
;            observer
;            planner
;            tohbans
;  
;   27-Oct-2010 - S.L.Freeland - ssw_hcr_query + ssw_time2epoch 
;   17-apr-2014 - GLS - Fixed possible time format problem in hcr data
;                       (epoch_starts, epoch_stops)
;   18-jun-2014 - GLS - Removed 'anytim' wrapper from epoch_starts, epoch_stops defs.
;   18-jun-2014 - GLS - Changed call from ssw_time2epoch to hinode_time2epoch.
;   04-dec-2014 - GLS - Trapped error when no plan files found.
;   29-Jul-2015 - Zarro - added more stringent test for missing plans
;-

common xrt_index2planinfo_blk, hcrcache

debug = keyword_set(debug)
refresh = keyword_set(refresh) or n_elements(hcrcache) eq 0 
loud = 1-keyword_set(quiet)

; Check wheather All input indices are within current cache
if not refresh then begin
   epoch_start = anytim(strtrim(str_replace(hcrcache[0].date_obs,         'Z',' '),2))
   epoch_stop  = anytim(strtrim(str_replace(last_nelem(hcrcache.date_end),'Z',' '),2))
   epoch = ssw_time2epoch(struct2ssw([index(0), last_nelem(index)], /nopoint), $
                          epoch_start, epoch_stop)
   ssnoepoch = where(epoch eq -1,necnt)
   refresh = necnt gt 0
endif
if n_elements(cache_window) eq 0 then cache_window=[-14,7] ; day window for HCR search->cache

fkeys_full = str2arr('obstitle, target, sci_obj,       sci_obs, obs_dec,      join_sb, ' + $
                     'obs_num, jop_id, noaa_num, observer,      planner,      tohbans')
hcrps_full = str2arr('obsTitle, target, sciObjectives, purpose, descriptions, joinSb,  ' + $
                     'obsNum,  jop_id, noaaNum,  observers,     planners,     tohbans')
voeps_full = str2arr('obstitle, target, sci_obj,       sci_obs, goal,         join_sb, ' + $
                     'obs_num, jop_id, noaa_num, chiefobserver, chiefplanner, tohbans')

num_fkeys_full = n_elements(fkeys_full)

retval = index ; initialize

if refresh then begin
   case 1 of 
      required_tags(retval,'date_obs'): times=index.date_obs
      data_chk(index,/string): times=index
      else: begin 
         box_message,'Unexpected input structure/times'
         return,-1
      endcase
   endcase
   if loud then box_message,'Updating HCR cache'
   time_window,times,ct0,ct1,days=cache_window ; define time window +/- INDEX
   ;hcr=ssw_hcr_query(ssw_hcr_make_query(ct0,ct1,instrument='XRT', $
   ;          select=hcrps),/remove_dummy, count=count)
   plans=sot_time2planfiles(ct0,ct1,/xml,/xrt)
   if keyword_set(debug) then STOP
   
   if ~is_blank(plans[0])then begin
      hcr=hinode_planvoe2struct(plans)
      ss_valid_date_obs = valid_time(hcr.date_obs)
      ss_valid_date_end = valid_time(hcr.date_end)
      ss_valid_times = where( ss_valid_date_obs and ss_valid_date_end, n_valid_times)
      if n_valid_times gt 0 then begin
        hcr = hcr[ss_valid_times]
        count=n_elements(hcr)
      endif else begin
        count = 0
      endelse
   endif else count=0

   if count gt 0 then begin
      hcrcache=temporary(hcr)
   endif else begin
      box_message,'No HCR records for INDEX'
      return, index
   endelse
endif 

hcr_window=hcrcache

find=tag_index(index,strtrim(fkeys_full,2))
hind=tag_index(hcrcache,strtrim(voeps_full,2))

both=hind ne -1 and find ne -1
bss=where(both,bothcnt)
nss=where(find eq -1 or hind eq -1,ncnt)
if ncnt gt 0 then begin 
   box_message,['No tags for ','FITS: ' + string(fkeys_full(nss)) + $
                 'PLAN: ' + string(voeps_full(nss))]
endif

fkeys_full_status = intarr(num_fkeys_full) -1

fkeys=strtrim(fkeys_full(bss),2)
voeps=strtrim(voeps_full(bss),2)
find=find(bss)
hind=hind(bss)
epoch_starts = strtrim(str_replace(hcrcache.date_obs,'Z',' '),2)
epoch_stops  = strtrim(str_replace(hcrcache.date_end,'Z',' '),2)
epoch=hinode_time2epoch(retval.date_obs, epoch_starts, epoch_stops)
debug=keyword_set(debug)
eok=where(epoch ne -1, ecnt)

if ecnt gt 0 then begin 
   ae=all_vals(epoch(eok))

   for e=0,n_elements(ae)-1 do begin 
      ss=where(epoch eq ae(e))

      for p=0,bothcnt-1 do begin 
         if ae[e] gt n_elements(hcrcache) then begin
            print, 'Non-existent index of hcrcache referenced in xrt_index2planinfo.pro.'
            print, 'Returning original index un-modified.'
            return, index
         endif else begin
            retval(ss).(find(p))=hcrcache(ae(e)).(hind(p))

;if keyword_set(track_updates) then begin
;   if retval(ss).(find(p)) ne index.(find(p)) then begin
;      fkeys_full_status[bss[p]] = 1
;      fkeys_full_vals[bss[p]] = strtrim(retval(ss).(find(p)),2)
;   endif else begin
;      fkeys_full_status[bss[p]] = 0
      
         endelse
      endfor

      if debug then stop,'index(ss)'

   endfor

endif

return,retval
end
