
pro xrt_fix_head, files=files, iindex=iindex, oindex=oindex, pnt_str=pnt_str, refresh=refresh, $
  hcrcache_refresh=hcrcache_refresh, x_fudge=x_fudge, y_fudge=y_fudge, $
  do_pnt=do_pnt, do_kathy=do_kathy, kat_refresh=kat_refresh, filnam_log=filnam_log, $
  do_planning=do_planning, $
  do_compare=do_compare, do_write=do_write, dir_orig=dir_orig, dir_mod=dir_mod, do_delete=do_delete, $
  verbose=verbose

;+
;   Name: XRT_FIX_HEAD
;   Purpose: Update various XRT header tags
;   Input Parameters:
;     FILES - String array of files to update
;     IINDEX - Array of FITS header structures to be updated.  If FILES exists, then this parameter
;              will be populated by reading the headers from the files.
;   Output Paramters:
;     OINDEX
;   Keyword Parameters:
;
;     files
;     iindex
;     oindex
;     pnt_str
;     refresh
;     hcrcache_refresh
;     x_fudge
;     y_fudge
;     do_pnt
;     do_kathy
;     kat_refresh
;     filnam_log
;     do_planning
;     do_compare
;     do_write
;     dir_orig
;     dir_mod
;     do_delete
;     verbose
;
;   Calling Sequence:
;     IDL> oindex = xrt_fix_head(iindex)
;   History:
;     18-oct-2010 - G.L.Slater
;     24-oct-2013 - GLS - Various bugs fixed
;-

  common kat_common, n_rec, t_kat, t_kat_sec, t_st, t_en, ec_fw12_cor, ec__fw12_cor

; Define prognam, progver variables:
  prognam = 'XRT_FIX_HEAD.PRO'
  progver = 'V1.0' ; 2011-07-27 (GLS)

;  pscale_arr = [1.03206, 1.02860]
  pscale_arr = [1.02860, 1.03206]

  if not exist(do_compare) then do_compare = 0
  
  if exist(files) then begin
    if not exist(iindex) then mreadfits_header, files, iindex

; help, iindex.mdp_clk, iindex.e_sclock, iindex.obt_time, iindex.obt_end, iindex.exptime

    if keyword_set(do_write) then begin
      if exist(dir_orig) then begin
        break_file, files, disk_logs, dirs_in, filnams, extens
        files_orig = concat_dir(dir_orig, filnams + '_orig' + extens)
        if keyword_set(do_delete) then $
          spawn, 'rm -f ' + strtrim(dir_orig,2) + '/XRT*.fits*'
      endif
      if exist(dir_mod) then begin
        break_file, files, disk_logs, dirs_in, filnams, extens
        files_out = concat_dir(dir_mod, filnams + '_mod' + extens)
        if keyword_set(do_delete) then $
          spawn, 'rm -f ' + strtrim(dir_mod,2) + '/XRT*.fits*'
      endif else begin
        files_out = files
      endelse
    endif

  endif

  n_head = n_elements(iindex)

; Create temporary tag value arrays:
  date_obs = iindex.date_obs
  naxis1   = iindex.naxis1
  naxis2   = iindex.naxis2
  platescl = iindex.platescl
  chip_sum = iindex.chip_sum
  ec_fw2_  = iindex.ec_fw2_
  ec_fw2   = iindex.ec_fw2
  ec_vl    = iindex.ec_vl
  p1row    = iindex.p1row
  p1col    = iindex.p1col
  rpos_row = iindex.rpos_row
  rpos_col = iindex.rpos_col
  rsiz_row = iindex.rsiz_row
  rsiz_col = iindex.rsiz_col

  xcen     = iindex.xcen
  ycen     = iindex.ycen
  crval1   = iindex.crval1
  crval2   = iindex.crval2
  crpix1   = iindex.crpix1
  crpix2   = iindex.crpix2

  flflg    = iindex.flflg

;  platescl_fix = (1.02860 + (1.03206-1.02860)*((ec_fw2-3) eq 0))*chip_sum
  platescl_fix = pscale_arr[ (ec_fw2 eq 3) and (ec_vl eq 1) ]*chip_sum
  cdelt1_fix   = platescl_fix
  cdelt2_fix   = platescl_fix
  xscale_fix   = platescl_fix
  yscale_fix   = platescl_fix
  fovx_fix     = naxis1*cdelt1_fix
  fovy_fix     = naxis2*cdelt1_fix

  p1row_fix    = rpos_row
  p1col_fix    = rpos_col
  p2row_fix    = rpos_row + rsiz_row - 1
  p2col_fix    = rpos_col + rsiz_col - 1

  crpix1_fix   = (float(iindex.naxis1)+1.)/2.
  crpix2_fix   = (float(iindex.naxis2)+1.)/2.
  crval1_fix   = xcen
  crval2_fix   = ycen

  buff = xrt_tim2prg(iindex, use_ssw_dist=use_ssw_dist, refresh=refresh, $
    flflg_fix=flflg_fix, obs_mode_fix=obs_mode_fix, flr_trig_cfa=flr_trig_cfa, $
    flr_trig_resp_cfa=flr_trig_resp_cfa, flr_prog_enabled=flr_prog_enabled, $
    prog_no_orl=prog_no_orl, do_index_fix=do_index_fix, oindex=oindex, debug=debug)

; Fix tags in output index structure array:
  oindex = iindex

  oindex.platescl = platescl_fix
  oindex.cdelt1   = cdelt1_fix
  oindex.cdelt2   = cdelt2_fix
  oindex.xscale   = xscale_fix
  oindex.yscale   = yscale_fix
  oindex.fovx     = fovx_fix
  oindex.fovy     = fovy_fix

  oindex.p1row    = p1row_fix
  oindex.p1col    = p1col_fix
  oindex.p2row    = p2row_fix
  oindex.p2col    = p2col_fix

  oindex.crpix1   = crpix1_fix
  oindex.crpix2   = crpix2_fix
  oindex.crval1   = crval1_fix
  oindex.crval2   = crval2_fix

; Update FLFLG tag:
  oindex.flflg    = flflg_fix

; Update or add OBS_MODE tag:
  if tag_exist(oindex,'obs_mode') then oindex.obs_mode = obs_mode_fix else $
    oindex = add_tag(oindex, obs_mode_fix, 'OBS_MODE')

; If requested, update pointing tags (XCEN, YCEN, CRVAL1, CRVAL2):
  if keyword_set(do_pnt) then begin
    oindex = xrt_align(oindex, x_fudge=x_fudge, y_fudge=y_fudge, x_off=x_off, y_off=y_off, $
                       refresh=refresh)

    x_offset_fix = oindex.x_offset
    y_offset_fix = oindex.y_offset
    xcen_fix     = oindex.xcen
    ycen_fix     = oindex.ycen
    crval1_fix   = oindex.crval1
    crval2_fix   = oindex.crval2
  endif

; Special update of December, 2006 keywods for Kathy:
  if keyword_set(do_kathy) then begin

    if not exist(t_kat) or keyword_set(kat_refresh) then begin
      restore, 'kat_str.sav'
      t_kat = kat_str.t_arr
      n_rec = n_elements(t_kat)
      t_kat_sec = anytim(t_kat)
      ss_sort = sort(t_kat_sec)
      t_kat  = t_kat[ss_sort]
      t_kat_sec = t_kat_sec[ss_sort]
      t_st_sec = t_kat_sec[0]
      t_en_sec = t_kat_sec[n_rec-1]

ec_fw12_cur = kat_str.ec_fw12__cur[ss_sort]
ec_fw12_cor = kat_str.ec_fw12__cor[ss_sort]
ec_fw12__cur = kat_str.ec_fw12_cur[ss_sort]
ec_fw12__cor = kat_str.ec_fw12_cor[ss_sort]

ec_fw1_cur = lonarr(n_rec)
ec_fw2_cur = lonarr(n_rec)
ec_fw1__cur = strarr(n_rec)
ec_fw2__cur = strarr(n_rec)

ec_fw1_cor = lonarr(n_rec)
ec_fw2_cor = lonarr(n_rec)
ec_fw1__cor = strarr(n_rec)
ec_fw2__cor = strarr(n_rec)

pos_slash = strpos(ec_fw12__cor, '/')
ss_slash = where(pos_slash ne -1, n_slash)
ec_fw1__cor[ss_slash] = strmids(ec_fw12__cor[ss_slash],0,pos_slash[ss_slash])
ec_fw2__cor[ss_slash] = strmids(ec_fw12__cor[ss_slash],pos_slash[ss_slash]+1)

ss_single_val = where( ((ec_fw12_cor ne '') and (pos_slash eq -1)), n_single_val)
ec_fw1__cor[ss_single_val] = ec_fw12__cor[ss_single_val]
ec_fw2__cor[ss_single_val] = ec_fw12__cor[ss_single_val]

ss_blank = where(ec_fw12__cor eq '', n_blank)
pos_slash = strpos(ec_fw12__cur[ss_blank], '/')
ss_slash = where(pos_slash ne -1, n_slash)
if n_slash ne n_blank then stop,' N_SLASH NE N_BLANK. STOPPING.'
ec_fw1__cur[ss_blank] = strmids(ec_fw12__cur[ss_blank],0,pos_slash)
ec_fw2__cur[ss_blank] = strmids(ec_fw12__cur[ss_blank],pos_slash+1)
ec_fw1__cor[ss_blank] = ec_fw1__cur[ss_blank]
ec_fw2__cor[ss_blank] = ec_fw2__cur[ss_blank]

pos_slash = strpos(ec_fw12_cor, '/')
ss_slash = where(pos_slash ne -1, n_slash)
ec_fw1_cor[ss_slash] = long(strmids(ec_fw12_cor[ss_slash],0,pos_slash[ss_slash]))
ec_fw2_cor[ss_slash] = long(strmids(ec_fw12_cor[ss_slash],pos_slash[ss_slash]+1))

    endif

update_ec_fw_arr = strarr(n_head)

    t_iindex = anytim(iindex.date_obs, /ccsds)
    t_st_iindex = anytim(t_iindex[0])
    t_en_iindex = anytim(t_iindex[n_head-1])
    if ( ((t_st_iindex ge t_st_sec) and (t_st_iindex le t_en_sec)) or $
         ((t_en_iindex ge t_st_sec) and (t_en_iindex le t_en_sec)) ) then begin

      ss_match_kat = where_arr(t_kat, t_iindex, n_match_kat)
      if n_match_kat gt 0 then begin
        ss_match_arr = where_arr(t_kat, t_iindex, /map_ss)
        ss_match_iindex = where(ss_match_arr ne -1, n_match_iindex)
        ss_match_arr = ss_match_arr[ss_match_iindex]

        oindex[ss_match_arr].ec_fw1 = ec_fw1_cor[ss_match_kat]
        oindex[ss_match_arr].ec_fw1_ = ec_fw1__cor[ss_match_kat]
        oindex[ss_match_arr].ec_fw2 = ec_fw2_cor[ss_match_kat]
        oindex[ss_match_arr].ec_fw2_ = ec_fw2__cor[ss_match_kat]

        if keyword_set(kat_verbose) then begin
          prstr, string(kat_str.T_ARR[0:(n_rec-1)<9], format='$(a25)') + $
                 string(kat_str.EC_FW12_CUR[0:(n_rec-1)<9], format='$(a25)') + $
                 string(kat_str.EC_FW12_COR[0:(n_rec-1)<9], format='$(a25)') + $
                 string(kat_str.EC_FW12__CUR[0:(n_rec-1)<9], format='$(a8)') + $
                 string(kat_str.EC_FW12__COR[0:(n_rec-1)<9], format='$(a8)')
          print, ''
          prstr, string(T_kat[0:(n_rec-1)<9], format='$(a25)') + $
                 string(EC_FW12__CUR[0:(n_rec-1)<9], format='$(a25)') + $
                 string(EC_FW12__COR[0:(n_rec-1)<9], format='$(a25)') + $
                 string(EC_FW12_CUR[0:(n_rec-1)<9], format='$(a8)') + $
                 string(EC_FW12_COR[0:(n_rec-1)<9], format='$(a8)')
          print,''

          prstr, string(t_kat[ss_match_kat[0:(n_match_kat-1)<4]], format='$(a25)') + $
                 string(ec_fw1__cor[ss_match_kat[0:(n_match_kat-1)<4]], format='$(a25)') + $
                 string(ec_fw2__cor[ss_match_kat[0:(n_match_kat-1)<4]], format='$(a25)') + $
                 string(fix(ec_fw1_cor[ss_match_kat[0:(n_match_kat-1)<4]]), format='$(a8)') + $
                 string(fix(ec_fw2_cor[ss_match_kat[0:(n_match_kat-1)<4]]), format='$(a8)') + $
                 string(t_iindex[ss_match_arr[0:(n_match_kat-1)<4]], format='$(a25)') + $
                 string(oindex[ss_match_arr[0:(n_match_kat-1)<4]].ec_fw1_, format='$(a25)') + $
                 string(oindex[ss_match_arr[0:(n_match_kat-1)<4]].ec_fw2_, format='$(a25)') + $
                 string(fix(oindex[ss_match_arr[0:(n_match_kat-1)<4]].ec_fw1), format='$(a8)') + $
                 string(fix(oindex[ss_match_arr[0:(n_match_kat-1)<4]].ec_fw2), format='$(a8)')
        endif

        buff = string(t_kat[ss_match_kat], format='$(a25)') + $
               string(ec_fw1__cor[ss_match_kat], format='$(a25)') + $
               string(ec_fw2__cor[ss_match_kat], format='$(a25)') + $
               string(fix(ec_fw1_cor[ss_match_kat]), format='$(a8)') + $
               string(fix(ec_fw2_cor[ss_match_kat]), format='$(a8)') + $
               string(t_iindex[ss_match_arr], format='$(a25)') + $
               string(oindex[ss_match_arr].ec_fw1_, format='$(a25)') + $
               string(oindex[ss_match_arr].ec_fw2_, format='$(a25)') + $
               string(fix(oindex[ss_match_arr].ec_fw1), format='$(a8)') + $
               string(fix(oindex[ss_match_arr].ec_fw2), format='$(a8)')

        file_append, filnam_log, buff, uniq=uniq, nlines=nlines, loud=loud, error=error 

        update_ec_fw_arr[ss_match_arr] = 'ec_fw1_, ec_fw2_, ec_fw1, ec_fw2'

      endif
    endif
  endif

; If requested, update or add planning tags:
  if keyword_set(do_planning) then begin
    oindex = xrt_index2planinfo(oindex)
;    for i=0,n_head-1 do oindex[i] = xrt_index2planinfo(oindex[i], refresh=hcrcache_refresh)

    obstitle_fix = oindex.obstitle
    target_fix   = oindex.target
    sci_obj_fix  = oindex.sci_obj
    sci_obs_fix  = oindex.sci_obs
    obs_dec_fix  = oindex.obs_dec
    join_sb_fix  = oindex.join_sb
    obs_num_fix  = oindex.obs_num
    jop_id_fix   = oindex.jop_id
    noaa_num_fix = oindex.noaa_num
    observer_fix = oindex.observer
    planner_fix  = oindex.planner
    tohbans_fix  = oindex.tohbans
  endif

; Remove blank or duplicate history records:
  history_new = oindex.history
  history_new0 = history_new[*,0]
  ss_non_blank_rec = where(history_new0 ne '', n_non_blank_rec)
  if n_non_blank_rec gt 0 then history_new = history_new[ss_non_blank_rec,*]
  history_new0 = history_new[*,0]
  ss_uniq = uniq(history_new0)
  history_new = history_new[ss_uniq,*]

  history_new0 = history_new[*,0]
  n_rec = n_elements(history_new0)
  ss_fitshead2struct = where(strpos(strlowcase(history_new0),'fitshead2struct') ne -1, n_fitshead2struct)
  if n_fitshead2struct gt 1 then begin
    ss_keep = bytarr(n_rec) + 1b
    ss_keep[ss_fitshead2struct[1:*]] = 0b
    history_new = history_new[where(ss_keep ne 0),*]
  endif

; Now add history records giving list of updated keywords:
  history_update_arr = replicate('XRT_FIX_HEAD ver ' + progver + ' run on ' + $ 
		       anytim(!stime, /ccsds, /date) + '. Keywords updated: ', n_head)
  history_update_arr = [[history_update_arr], [replicate('platescl, cdelt1, cdelt2, xscale, yscale, fovx, fovy', n_head)]]
  history_update_arr = [[history_update_arr], [replicate('p1row, p1col, p2row, p2col, crpix1, crpix2, flflg, obs_mode', n_head)]]
  history_update_arr = [[history_update_arr], [update_ec_fw_arr]]
;  history_update_arr = [[history_update_arr], [replicate('ec_fw1_, ec_fw2_, ec_fw1, ec_fw2', n_head)]]

  history_new = transpose([[transpose(history_new)], [history_update_arr]])
  n_rec_history_new = n_elements(history_new[*,0])

;  update_history, oindex, history_update_rec_1, caller=prognam, version=progver, mode=1
;  update_history, oindex, history_update_rec_2, caller=prognam, mode=1
;  update_history, oindex, history_update_rec_3, caller=prognam, mode=1

  n_hist_new = n_elements(history_new[*,0])

;  history_fix = oindex.history
  history_fix = history_new

;  iindex = rem_tag(iindex, 'history')
;  iindex = add_tag(iindex, history_fix, 'history')
  oindex = rem_tag(oindex, 'history')
  oindex = add_tag(oindex, history_fix, 'history')
;STOP
; Optionally print out old and new keyword values for comparison:
  if keyword_set(do_compare) then begin

    t_names_fixed = ['platescl','cdelt1','cdelt2','xscale','yscale','fovx','fovy', $
                     'p1row','p1col','p2row','p2col','flflg',           'xcen','ycen', $
                     'crpix1','crpix2','crval1','crval2','obstitle','target','sci_obj','sci_obs','obs_dec', $
                     'join_sb','obs_num','jop_id','noaa_num','observer','planner','tohbans'  $
                              ]
    n_tags_fixed = n_elements(t_names_fixed)

    for i=0, n_head-1 do begin
      print, ''
      for j=0, n_tags_fixed-1 do begin
        cmd = "print, '" + t_names_fixed[j] + "', " + $
              "strtrim(iindex[i]." + t_names_fixed[j] + ",2), " + $
              "strtrim(oindex[i]." + t_names_fixed[j] + ",2), " + $
              "strtrim(iindex_test[i]." + t_names_fixed[j] + ",2), " + $
              "strtrim(oindex_test[i]." + t_names_fixed[j] + ",2), " + $
              "format = '$(a12, a20, a20, a20, a20)'"
        result = execute(cmd)
      endfor
      print, ''
      if keyword_set(do_pause) then dum = get_kbrd()
    endfor
  endif

; Update headers in situ:
  if keyword_set(do_write) then begin
    for i=0, n_head-1 do begin
      if exist(dir_orig) then $
        spawn, 'cp -p ' + files[i] + ' ' + files_orig[i]
      if exist(dir_mod) then $
        spawn, 'cp -p ' + files[i] + ' ' + files_out[i]

; FXHMODIFY, FILENAME, NAME, VALUE, COMMENT, BEFORE=BEFORE,   $
;   AFTER=AFTER, FORMAT=FORMAT, EXTENSION=EXTENSION, ERRMSG=ERRMSG,$
;   NOGROW=NOGROW

      fxhmodify, files_out[i], 'platescl', platescl_fix[i]
      fxhmodify, files_out[i], 'cdelt1',   cdelt1_fix[i]
      fxhmodify, files_out[i], 'cdelt2',   cdelt2_fix[i]
      fxhmodify, files_out[i], 'xscale',   xscale_fix[i]
      fxhmodify, files_out[i], 'yscale',   yscale_fix[i]
      fxhmodify, files_out[i], 'fovx',     fovx_fix[i]
      fxhmodify, files_out[i], 'fovy',     fovy_fix[i]

      fxhmodify, files_out[i], 'p1row',    p1row_fix[i]
      fxhmodify, files_out[i], 'p1col',    p1col_fix[i]
      fxhmodify, files_out[i], 'p2row',    p2row_fix[i]
      fxhmodify, files_out[i], 'p2col',    p2col_fix[i]

      fxhmodify, files_out[i], 'crpix1',   crpix1_fix[i]
      fxhmodify, files_out[i], 'crpix2',   crpix2_fix[i]

      fxhmodify, files_out[i], 'crval1',   crval1_fix[i]
      fxhmodify, files_out[i], 'crval2',   crval2_fix[i]

      fxhmodify, files_out[i], 'flflg',    flflg_fix[i]
      fxhmodify, files_out[i], 'obs_mode', obs_mode_fix[i]

; If requested, poke pointing tags (XCEN, YCEN, CRVAL1, CRVAL2):
      if keyword_set(do_pnt) then begin
        fxhmodify, files_out[i], 'x_offset', x_offset_fix[i]
        fxhmodify, files_out[i], 'y_offset', y_offset_fix[i]
        fxhmodify, files_out[i], 'xcen',     xcen_fix[i]
        fxhmodify, files_out[i], 'ycen',     ycen_fix[i]
        fxhmodify, files_out[i], 'crval1',   crval1_fix[i]
        fxhmodify, files_out[i], 'crval2',   crval2_fix[i]
      endif

; If requested, poke the XRT filter wheel tags (EC_FW1, EC_FW1_, EC_FW2, EC_FW2_):
      if keyword_set(do_kathy) then begin
        fxhmodify, files_out[i], 'ec_fw1',   oindex[i].ec_fw1
        fxhmodify, files_out[i], 'ec_fw1_',  oindex[i].ec_fw1_
        fxhmodify, files_out[i], 'ec_fw2',   oindex[i].ec_fw2
        fxhmodify, files_out[i], 'ec_fw2_',  oindex[i].ec_fw2_
      endif

; If requested, poke or add planning tags:
      if keyword_set(do_planning) then begin
        fxhmodify, files_out[i], 'obstitle', obstitle_fix[i]
        fxhmodify, files_out[i], 'target',   target_fix[i]
        fxhmodify, files_out[i], 'sci_obj',  sci_obj_fix[i]
        fxhmodify, files_out[i], 'sci_obs',  sci_obs_fix[i]
        fxhmodify, files_out[i], 'obs_dec',  obs_dec_fix[i]
        fxhmodify, files_out[i], 'join_sb',  join_sb_fix[i]
        fxhmodify, files_out[i], 'obs_num',  obs_num_fix[i]
        fxhmodify, files_out[i], 'jop_id',   jop_id_fix[i]
        fxhmodify, files_out[i], 'noaa_num', noaa_num_fix[i]
        fxhmodify, files_out[i], 'observer', observer_fix[i]
        fxhmodify, files_out[i], 'planner',  planner_fix[i]
        fxhmodify, files_out[i], 'tohbans',  tohbans_fix[i]
      endif
      
      for j=0,n_hist_new-1 do $
	fxhmodify, files_out[i], 'history', history_fix[j, i]

      if keyword_set(verbose) then $
        if i mod 200 eq 0 then $
          print, ' Finished with ' + string(i,format='$(i4.4)') + ' of ' + $
                   strtrim(n_head,2) + ' images for ' + iindex[i].date_obs

    endfor
  endif

  end
