;+
; Name:
;   HOP130_TIMINGS
;
; Purpose:
;   Calculate the timings for the HOP 130 pointings taking into
;   account SAAs and XTW.
;   http://www.isas.jaxa.jp/home/solar/hinode_op/hop.php?hop=0130
;
; Calling Sequence:
;      IDL> hop130_timings, saafile, starttime, pointingsfile=pointingsfile,  ofile=ofile
;
; Inputs:
;     SAAFILE       :  SAA file. Tipically: obev_YYYYMMDDTTTT.evt
;
;     STARTTIME     : suggested initial time. The routine will
;                     accommodate that time according to duration
;                     of the study and SAA times and durations.
; Outputs:
;     1) Textfile "hop130_pointing_times.txt" with timing and pointing information.
;     2) Onscreen plot.
;         - SAA periods in green.
;         - XTW periods in yellow (when in XTW season).
;         - Re-pointing: dotted line.
;         - End of study: dashed line.
;
;     3) Textfile: "hop130_cpformat_pointings.txt"  [New: 2021/04/05 - DHB]
;        This text file can be passed to the Chief Planner (CP) for automatic reading
;        of pointings by the CP pointing tool.
;
; Keywords:
;     OFILE : name for the output text file.
;             Default: hop130_pointing_times.txt'
;     POINTINGSFILE :  text file with pointings information. If not set, it uses the
;                      default "hinode_pointings.txt" file on SSW (preferred call).
;
;                      Format: 4 columns
;                        Index     X_pointing    Y_pointing    Duration
;
;                      Duration= time duration of the observing sequence at that pointing.
;
; Example:
;       New call (2016/05/16) - Pointing file set as default. Can be changed through keyword.
;
;       IDL> hop130_timings, 'obev_200909108000.evt', '10-Sept-2009 11:00'
;
;       X-ray twilight example:
;       IDL> hop130_timings, 'obev_201004240100.evt', '25-Apr-2010 07:00'
;
;
; Modification History:
;     2009/09/10  I. Ugarte-Urra. NRL.
;     2009/09/11  IUU. Check size of screen to make plots.
;     2010/04/23  IUU. Take into account X-ray twilight (XTW).
;     2010/09/27  IUU. Issue warning if no SAAs after START TIME.
;     2016/05/16  IUU. Changed input variable POINTINGSFILE to keyword.
;     2016/06/21  IUU. Improved output.
;     2017/04/18  HPW. Added output for EIS planner.
;     2021/04/05  DHB. Added output for automatic reading by CP pointing software.
;-

PRO hop130_timings, saafile, starttime, ofile=ofile, xs=xs, ys=ys, pointingsfile=pointingsfile

  findpro,'hop130_timings.pro',dir=prodir,/noprint
  if not KEYWORD_SET(pointingsfile) then pointingsfile=concat_dir(prodir,'hinode_pointings.txt')

  tsafe_saa = 360.        ; SAA safe margin: 5 min.
  tsafe_rep = 60.         ; Added time after study end and before repointing.
  tsafe_exp = 120.        ; time between repoint and first EIS exposure

  screen=get_screen_size()
  xs=1500<screen(0)
  ys=600 <screen(0)/2.5

  saa=rd_ascii(saafile)

  pts_saa=where(strmid(saa,0,3) eq 'SAA')
  pts_xtw=where(strmid(saa,0,3) eq 'XTW')

  if pts_xtw[0] ne -1 then xtw_season=1 else xtw_season=0

  if xtw_season then begin
    xtw=saa(pts_xtw)
    pts_xtw_entry=where(strmid(saa,0,9) eq 'XTW_ENTRY')
    pts_xtw_exit =where(strmid(saa,0,8) eq 'XTW_EXIT')
    xtw_entry=saa(pts_xtw_entry)
    xtw_exit=saa(pts_xtw_exit)
    t_xtw= anytim2tai(str_replace(strmid(xtw,13,19),'.',' '))
    t1_xtw=anytim2tai(str_replace(strmid(xtw_entry,13,19),'.',' '))
    t2_xtw=anytim2tai(str_replace(strmid(xtw_exit ,13,19),'.',' '))
  endif

  saa=saa(pts_saa)
  pts_entry=where(strmid(saa,0,9) eq 'SAA_ENTRY')
  pts_exit =where(strmid(saa,0,8) eq 'SAA_EXIT')
  saa_entry=saa(pts_entry)
  saa_exit=saa(pts_exit)
  t_saa= anytim2tai(str_replace(strmid(saa,13,19),'.',' '))
  t1_saa=anytim2tai(str_replace(strmid(saa_entry,13,19),'.',' '))
  t2_saa=anytim2tai(str_replace(strmid(saa_exit ,13,19),'.',' '))
  nsaa=n_elements(t1_saa)
  t1_gap = t2_saa(0:nsaa-2)
  t2_gap = t1_saa(1:nsaa-1)
  dt_gap = t2_gap - t1_gap

  hinode=rd_tfile(pointingsfile,4)
  npointings=n_elements(hinode(0,*))

  times=strarr(npointings)
  times_end=strarr(npointings)

  t0=anytim2tai(starttime)
  timerange=[anytim2utc(anytim2tai(t0)-(2*3600.),/ecs),anytim2utc(anytim2tai(t0)+(7*3600.),/ecs)]

  if t2_saa[n_elements(t2_saa)-1] lt t0 then begin
    message,'No SAA entries after START TIME.',/info
    message,'Please check SAA file (newer file?) or START TIME and rerun.',/info
    return
  endif

  dt_gap=0.
  print,''
  print,'Spacecraft pointings for daily meeting: '
  print,' #'+string('Start time','(a11)')+string('End time','(a22)')+string('Spacecraft pointing','(a37)')+string('EIS Start Time','(a19)')+string('EIS Pointing','(a20)')
  for i=0,npointings-1 do begin
    dt=float(hinode(3,i))
    diff=min(abs(t1_saa-t0),pt)
    if t0 ge t1_saa(pt) and t0 le t2_saa(pt) then in_saa=1 else in_saa=0

    if pt+1 ge n_elements(t1_saa) then begin
      message,'Error. sReached last SAA entry in file: ('+anytim2utc(t1_saa[-1],/ecs,/trunc)+', '+anytim2utc(t2_saa[-1],/ecs,/trunc)+')',/info
      message,'Please check SAA file (newer file?) or change START TIME and rerun.',/info
      return
    endif

    if in_saa then t0 = t2_saa(pt) + tsafe_saa
    t2=t1_saa(pt)
    if t0 gt t2 then  t2=t1_saa(pt+1)

    ;;- Check whether whithin X-ray twilight.
    if xtw_season then begin
      diff=min(abs(t1_xtw-t0),pt_xtw)
      if (t0 ge t1_xtw(pt_xtw) and t0 le t2_xtw(pt_xtw)) or (t0+dt ge t1_xtw(pt_xtw) and t0+dt le t2_xtw(pt_xtw)) then in_xtw=1 else in_xtw=0
      if in_xtw then t0=t2_xtw(pt_xtw)
    endif

    ;;- Make sure there is time to fit study. Else calculate new t0.
    dt_avail=t2-t0
    while dt_avail lt dt do begin
      t0=t2_saa(pt) + tsafe_saa
      t2=t1_saa(pt+1)
      dt_avail=t2-t0
      pt=pt+1
    end

    ;;- Check again (new t0) whether whithin X-ray twilight.
    if xtw_season then begin
      diff=min(abs(t1_xtw-t0),pt_xtw)
      if (t0 ge t1_xtw(pt_xtw) and t0 le t2_xtw(pt_xtw)) or (t0+dt ge t1_xtw(pt_xtw) and t0+dt le t2_xtw(pt_xtw)) then in_xtw=1 else in_xtw=0
      if in_xtw then t0=t2_xtw(pt_xtw)
    endif

    t_start=anytim2utc(t0,/ecs)
    t_end  =anytim2utc(t0+float(hinode(3,i)),/ecs)
    t0 = anytim2tai(t_end)+tsafe_rep
    outold = trim(i+1,'(i2.2)')+' '+trim(t_start)+' '+trim(t_end)+'   X: '+string(hinode(1,i),'(f6.1)') + '   Y: '+string(hinode(2,i),'(f6.1)')

    ;; --- print output for EIS planner
    t_hinode_pointing = t_start
    t_eis_start = anytim(anytim(t_start)+tsafe_exp,/ecs,/trun)
    if i+1 eq 6 or i+1 eq 10 or i+1 eq 11 or i+1 eq 15 then begin
      if i+1 eq 6 or i+1 eq 10 then offset = 186 else offset = -286
      eis_xcen = float(hinode[1,i])
      eis_ycen = float(hinode[2,i])+offset
      str = string(eis_xcen[0],format='(i5)')+','+string(eis_ycen[0],format='(i5)')
    endif else begin
      eis_xcen = float(hinode[1,i])
      eis_ycen = float(hinode[2,i])+[186,-286]
      str = string(eis_xcen[0],format='(i5)')+','+string(eis_ycen[0],format='(i5)')+' '+$
          string(eis_xcen[0],format='(i5)')+','+string(eis_ycen[1],format='(i5)')
    endelse
    outnew = ' | ' + t_eis_start + ' ' + str

    out = outold + outnew
    print, out

    times(i)=t_start
    times_end(i)=t_end
  endfor

  str_times=strarr(npointings)
  str_times_end=strarr(npointings)
  for i=0,npointings-1 do str_times(i)='POINTING '+trim(hinode(0,i),'(i2.2)')+' '+times(i)+'   X: '+string(hinode(1,i),'(f6.1)') + '   Y: '+string(hinode(2,i),'(f6.1)')
  for i=0,npointings-1 do str_times_end(i)='END SEQ.    '+times_end(i)

  if xtw_season then begin
    all=[t_saa,t_xtw,anytim2tai(times),anytim2tai(times_end)]
    all_string=['-- '+saa,'-- '+xtw,'++ '+str_times,'   '+str_times_end]
  endif else begin
    all=[t_saa,anytim2tai(times),anytim2tai(times_end)]
    all_string=['-- '+saa,'++ '+str_times,'   '+str_times_end]
  endelse
  output=all_string(sort(all))

  all=all(sort(all))
  timerange_tai=anytim2tai(timerange)
  good=where(all ge timerange_tai(0) and all le timerange_tai(1))

  output=output(good)

  if not keyword_set(ofile) then ofile='hop130_pointing_times.txt'
  openw,lun,ofile,/get_lun
  for i=0,n_elements(output)-1 do printf,lun,output(i)
  free_lun,lun

  ; added new output in the CP pointing tool format - this can be read automatically
  tmp = output
  ofile_cp='hop130_cpformat_pointings.txt'
  openw, unit,ofile_cp, /get_lun
    printf, unit, 'POINTING:'
    cnt = 0
    for i = 0,n_elements(tmp)-1 do begin
      cpout = tmp[i]
      if stregex(cpout,'POINTING') ne -1 then begin
        cnt = cnt+1
        cpout = strmid(cpout, 15, strlen(cpout)-15)
        cpout = str_replace(cpout, 'X:', ' |')
        cpout = str_replace(cpout, 'Y:', ' |')
        cpout = cpout+'  | HOP130 '+trim(cnt, '(i2.2)')+'/15'
        printf, unit, cpout
      endif
      if (cnt eq 15) AND (stregex(cpout,'END') ne -1) then begin
        cpout = strmid(cpout, 15, strlen(cpout)-15)
        cpout = cpout+'    |    0.0    |    0.0  | End of HOP130 '
        printf, unit, cpout
      endif
    endfor
    printf, unit, 'EOP'
  free_lun, unit

  print,''
  print,'######################### ADDITIONAL OUTPUTS #############################################'
  print,'1- Spacecraft pointings file for the Chief Planner:   '+ofile_cp
  print,'2- File with spacecraft pointings, SAA and XTW times: '+ofile
  print,'3- For EIS pointings to be inserted in EIS planning tool, see on-screen output above or check PDF file at: '+prodir
  print,'Preferred alignment in Planning Tool is: "2. - EIS/AIA". Other alignments can be used too.'
  print,'##########################################################################################'

  linecolors
  window,0,xs=xs,ys=ys
  !p.multi=[0,1,2]
  utplot,t_saa-t_saa(0),replicate(1,nsaa),anytim2utc(t_saa(0),/ecs), ytickformat="(A1)", yticks=1, title='Full SAA file range'
  if xtw_season then for i=0,min([n_elements(t1_xtw),n_elements(t2_xtw)])-1 do polyfill,[t1_xtw(i),t1_xtw(i),t2_xtw(i),t2_xtw(i)]-t_xtw(0),[0,1,1,0], color=5
  for i=0,n_elements(t2_saa)-1 do polyfill,[t1_saa(i),t1_saa(i),t2_saa(i),t2_saa(i)]-t_saa(0),[0,1,1,0], color=7
  !p.multi=[2,1,2,0,0]
  utplot,t_saa-t_saa(0),replicate(1,nsaa),anytim2utc(t_saa(0),/ecs), ytickformat="(A1)", yticks=1, /noerase
  plots,anytim2tai(timerange)-t1_saa(0),1.0,color=2,thick=2

  !p.multi=[1,1,2,0,0]
  utplot,t_saa-t_saa(0),replicate(1,nsaa),anytim2utc(t_saa(0),/ecs), timerange=timerange, xs=1, ytickformat="(A1)", tick_unit=3600.,yticks=1, title='CLOSE-UP'
  if xtw_season then for i=0,min([n_elements(t1_xtw),n_elements(t2_xtw)])-1 do polyfill,[t1_xtw(i),t1_xtw(i),t2_xtw(i),t2_xtw(i)]-t_saa(0),[0,1,1,0], color=5
  for i=0,n_elements(t2_saa)-1 do polyfill,[t1_saa(i),t1_saa(i),t2_saa(i),t2_saa(i)]-t_saa(0),[0,1,1,0], color=7
  for i=0,n_elements(times)-1 do plots,anytim2tai(times(i))-t_saa(0),!y.crange, line=1
  for i=0,n_elements(times)-1 do plots,anytim2tai(times_end(i))-t_saa(0),!y.crange, line=2
  for i=0,npointings-1 do xyouts,anytim2tai(times(i))+hinode(3,i)/3.-t_saa(0),0.6,trim(hinode(0,i))
  for i=0,npointings-1 do xyouts,anytim2tai(times(i))+hinode(3,i)/4.-t_saa(0),0.4,trim(hinode(3,i)/60.)+'m'
  !p.multi=[1,1,2,0,0]
  utplot,t_saa-t_saa(0),replicate(1,nsaa),anytim2utc(t_saa(0),/ecs), timerange=timerange, xs=1, ytickformat="(A1)", tick_unit=3600.,yticks=1,/noerase
  plots,anytim2tai(timerange)-t1_saa(0),1.0,color=2,thick=2

END
