; $Id: write_sidelobe_scheds.pro,v 1.15 2019/10/17 18:35:33 secchia Exp $
;
; Project     : STEREO SECCHI
;                   
; Name        : write_sidelobe_scheds
;               
; Purpose     : to create optimized block schedules from weekly schedules
;               
; Explanation : 
;               
; Use         : IDL> write_sidelobe_schedssc,yr,doy,doy2,ndays=ndays,nocmdfile=nocmdfile,nohtml=nohtml,outdir=outdir,sidelobe=sidelobe
;    
; Inputs      : sc = A or B
;   	    	yr = yyyy
;   	    	doy = monday works best for now weekly schedules start on mondays
;               doy2 = optional last day to schedule (default is doy +6 1 week)
;               
; Outputs     : schedules for tuesday thru the end of the available DSN contacts.
;   	    	command load file
;
; Keywords :	/NOCMDFILE  Do not write command load file in ~/attic/cmdlogs
;               NOCMDFILE = will not write itos command file
;   	    	outdir = change output directory from default (default= '~/loads/PT/flight/operations/sidelobe/(AorB)')
;		ndays=number of days/schedules to write
;		sidelobe = 1 or 2 defaults to 1
;		lightt = light travel time defaults to 15 minutes, 1st schedule start BOT - lightt + 5 minutes.
; 
; Common      : 
;               
; Restrictions: 
;               
; Side effects: 
;               
; Category    : planning 
;               
; Prev. Hist. : None.
;
; Written     : Lynn Hutting 06/17/2014 
;               
; Modified    :
;
; $Log: write_sidelobe_scheds.pro,v $
; Revision 1.15  2019/10/17 18:35:33  secchia
; changes since last commit on Aug 12
;
; Revision 1.14  2015/08/19 15:15:53  hutting
; added 34M schedules
;
; Revision 1.13  2015/08/18 14:37:27  secchia
; Add changes made since Feb
;
; Revision 1.12  2015/06/23 16:04:17  secchia
; added day minus1 to schedule to corrected for the day off feature which start on jan 1 2015
;
; Revision 1.11  2014/12/22 15:33:17  secchia
; correcct for new year
;
; Revision 1.10  2014/10/02 20:56:49  secchia
; nr - always run fix_schedule
;
; Revision 1.9  2014/09/03 17:57:42  secchia
; change upload times to 120 from 300
;
; Revision 1.8  2014/08/21 12:56:17  secchia
; added bsf file for the 3 hour or less contacts
;
; Revision 1.7  2014/08/12 19:37:49  secchia
; added plot and schedule comments to show the number of minutes in contact
;
; Revision 1.6  2014/08/11 14:54:15  secchia
; corrected for contacts that round to to 1ur long
;
; Revision 1.5  2014/08/07 15:30:43  secchia
; tested and corrected
;
; Revision 1.4  2014/08/07 13:16:09  hutting
; added sidelobe directory
;
; Revision 1.3  2014/07/23 18:45:27  hutting
; corrected first block of contact for side lobe 1
;
; Revision 1.2  2014/07/23 18:31:38  hutting
; test for side lobe 1 operations
;
; Revision 1.1  2014/06/18 14:58:00  hutting
; creates schedules for sidelobe operations based on weekly schedules
;


pro write_sidelobe_scheds,sc,yr,doy,doy2,ndays=ndays,nocmdfile=nocmdfile,nohtml=nohtml,outdir=outdir,sidelobe=sidelobe,lightt=lightt

if keyword_set(sidelobe) then sidelobe=sidelobe else sidelobe=1
if sidelobe eq 1 then begin
  bkgsched='140813_2.bsf'
  under3sched='140822_0.bsf' ;not used only for 24 hour observations.
  scndsched='140813_3.bsf'
endif else begin
  bkgsched='141219_1.bsf'
  under3sched='na' ;not used only for 24 hour observations.
  firstsched=''
  scndsched='141219_0.bsf'
endelse
sched34='141104_0.bsf'
if keyword_set(lightt) then lightt=lightt else lightt=15*60.

docmdfile=1
IF keyword_set(OUTDIR) THEN begin
    cmdfiledir=outdir 
    updir=outdir
    pltdir=outdir
ENDIF ELSE BEGIN
    cmdfiledir='~/attic/cmdlogs'
    outdir='~/loads/PT/flight/operations/sidelobe/'+strupcase(sc)
    pltdir='~/loads/PT/flight/operations/'+strupcase(sc)+'/dailyats/reports/'
    if yr ge 2015 then updir='PT/flight/operations/sidelobe/'+strupcase(sc)+'/m1day' else updir='PT/flight/operations/sidelobe/'+strupcase(sc)
ENDELSE
cmdfile=cmdfiledir+'/'+strupcase(sc)+'_weekly_schedules_'+string(yr,'(i4.4)')+'_'+string(doy,'(i3.3)')+'.csv'

   close,4
   close,5
   docmdfile=1
   IF keyword_set(NOCMDFILE) THEN docmdfile=0
   IF (docmdfile) THEN openw,5,cmdfile

  if ~keyword_set(ndays) then ndays=7 else ndays=ndays
  if datatype(doy2) eq 'UND' then doy2=doy+ndays

  sw=read_weekly_sched(sc,yr,doy, NDAYS=ndays+14,/tai,/sidelobe)
  z34=where(sw.pbrate lt 3)
;  sw=sw[z]  
  z=where(sw.sweepend ne '')
  time=sw[z[0]].sweepend

  tmp=doy2utc(fix(strmid(time,5,3)),fix(strmid(time,0,4))) & tmp.time=(long(strmid(time,9,2))*3600+long(strmid(time,12,2))*60+long(strmid(time,15,2)))*1e3 
  sweepend=utc2str(tmp)
  if sidelobe eq 1 then stimeadj=anytim2tai(sweepend) - anytim2tai(sw[z[0]].bot) else stimeadj=0;30*60+20.; to wait out sweep and SC playback
  stimeadj=fltarr(n_Elements(sw))+stimeadj
  stimeadj[z34]=0
  stime=utc2tai(sw.bot) + stimeadj - lightt ;+ 60*5.; minus lightravel time + 5 minutes

  bot2eot=sw.bot2eot

  if where(sw.mdump ne '') gt -1 then begin
    time=sw[where(sw.mdump ne '')].mdump
    tmp=doy2utc(fix(strmid(time,5,3)),fix(strmid(time,0,4))) & tmp.time=(long(strmid(time,9,2))*3600+long(strmid(time,12,2))*60+long(strmid(time,15,2)))*1e3 
    mdump=utc2str(tmp)
    coropen=[87,90]
    doortimes=anytim2tai(mdump)+(coropen*60)
    doorcmnts=['#   OPEN COR2 DOOR','#   OPEN COR1 DOOR']
    doorsched=['516CA','316CB']
    if ((anytim2tai(mdump)-(60*60+22.))-stime[where(sw.mdump ne '')])/(60*60*2) lt 1 then begin
      stime=stime[where(sw.mdump eq '')]
      bot2eot=sw[where(sw.mdump eq '')].bot2eot
      swt=sw[where(sw.mdump eq '')]
      z34=where(swt.pbrate lt 3)
    endif
  endif else mdump='no'

  ssched=strarr(n_elements(stime))+scndsched ;firstsched
  scmnt=strarr(n_elements(stime))+'# Minutes in contact ' +string((sw.bot2eot-stimeadj)/(60) < 120,'(i3)')
  etime=stime+(bot2eot-stimeadj)
  if sidelobe eq 1 then begin
    z=where(bot2eot le 60*60*3+300,cnt)
    if cnt gt 0 then ssched[z]=under3sched
  endif
  ssched[z34]=sched34
  scmnt[z34]=strarr(n_elements(z34))+'# 34M Minutes in contact ' +string((sw.bot2eot-stimeadj)/(60) < 120,'(i3)')
  
  nt=n_elements(stime)
  mtime=stime[1:nt-1]-((stime[1:nt-1]-etime[0:nt-2])/2.)

  mtest=where(mtime+(60.*60*2) lt stime[1:nt-1],cnt)

  mtime=mtime[mtest]
  if mdump ne 'no' then begin
    z=where(mtime ge anytim2tai(mdump)-(60*60*2) and  mtime le anytim2tai(mdump)+(60*60*2),mcnt)
    if mcnt gt 0 then stop
  endif
  msched=strarr(cnt) +bkgsched
  mcmnt=strarr(cnt)+'# half way schedule'
  nscheds=round((((bot2eot-(stimeadj+lightt))/(60*60))/2.)+.5)
 ; sched2=strarr(nscheds[0]-1)+scndsched & time2=dindgen(nscheds[0]-1)*(60*60*2)+(stime[0]+60*60*2)
  time2=[stime,mtime] & sched2=[ssched,msched] & cmnt2=[scmnt,mcmnt]
 for n=0,n_Elements(stime)-1 do begin
    if nscheds[n] gt 1 and ssched[n] ne under3sched then begin
      ;print,utc2str(tai2utc(stime[n])),'  ',bot2eot[n],'  ',ssched[n],'  ',nscheds[n]
      if ssched[n] eq sched34 then nc='34M ' else nc=''
      sched2=[sched2,strarr(nscheds[n]-1)+ssched[n]] & time2=[time2,dindgen(nscheds[n]-1)*(60*60*2)+(stime[n]+60*60*2)]
      cmnt2=[cmnt2,'# '+nc+'Minutes in contact '+string((bot2eot[n]-(stimeadj+lightt))/(60)-(indgen(nscheds[n]-1)*(120)+120) <120,'(i3)')]
      ;print,string((bot2eot[n]-(stimeadj+lightt))/(60)-(indgen(nscheds[n]-1)*(120)+120) <120,'(i3)')
    endif
  endfor

  if mdump ne 'no' then begin
    time2=[time2,doortimes] & sched2=[sched2,doorsched] & cmnt2=[cmnt2,doorcmnts]
  endif
  z=sort(time2)
  ttimes=time2[z] & tscheds=sched2[z] & tcmnt=cmnt2[z]

tst=where(ttimes[1:n_Elements(ttimes)-1]-ttimes[0:n_Elements(ttimes)-2] lt (60.*60.*2),cnt)

if cnt gt 0 then begin
  print,utc2str(tai2utc(ttimes[tst]))+'  '+tcmnt[tst]
  print,utc2str(tai2utc(ttimes[tst+1]))+'  '+tcmnt[tst+1]
  stop
endif

for n=0,n_Elements(ttimes)-1 do print,utc2str(tai2utc(ttimes[n])),' ',tscheds[n]
  stp=utc2tai(doy2utc(doy2+1,yr))
  strt=utc2tai(doy2utc(doy,yr))
  cdoy=utc2str(doy2utc(doy-1,yr),/date_only)
  stschedule=0
  for n=0,n_Elements(ttimes)-1 do begin
    tdoy=ttimes[n]
    schdate=utc2str(tai2utc(ttimes[n]))
    print,tdoy,doy,cdoy,schdate,tscheds[n]
    if tdoy ge strt and tdoy le stp then begin
      sthrmin=fix(strmid(schdate,11,2))*60 + fix(strmid(schdate,14,2))
      print,'sthrmin  ',sthrmin
      if sthrmin le 3 then stop
      schdate=utc2str(tai2utc(tdoy),/date_only)
      if schdate ne cdoy and sthrmin gt 3 then begin
         if (stschedule gt 0) then begin
    	    printf,4,'---00000000T16C2'
	    print,'Closing ',schfile
    	    close,4
    	    wait,2
	    cmd='fix_schedule '+schfile+' '+schfile2
	    print,cmd
	    wait,3
            spawn,cmd

    	    printf,8,'---00000000T16C2'
	    print,'Closing ',schfile
    	    close,8
    	    wait,2
	    cmd='fix_schedule '+schfilem1+' '+schfile2m1
	    print,cmd
	    wait,3
            spawn,cmd


    	    IF (docmdfile) THEN BEGIN
   	        printf,5,'loadfile,120,'+schfileup+','+schfileld+',X'
    	        dm14=utc2str(tai2utc(ttimes[n]-(14.*24.*60*60)),/DATE_ONLY)
    	        printf,5,'Command,60,FMDELETE,file,temp/'+strmid(dm14,2,2)+strmid(dm14,5,2)+strmid(dm14,8,2)+'00.sch,X'
    	        wait,2
                if ~keyword_set(nohtml) then blcksched2html, strmid(sc,2,1), strmid(blckdate,2,2)+strmid(blckdate,5,2)+strmid(blckdate,8,2),/sidelobe
	    ENDIF
            stschedule=0
	   endif         
            cdoy= schdate   
;            blckdate=utc2str(doy2utc(cdoy,yr),/DATE_ONLY)
            blckdate=utc2str(tai2utc(ttimes[n]))
 	    blckyr=strmid(blckdate,2,2)
            if fix(blckyr) ge 15 then load_blckdate=utc2str(tai2utc(ttimes[n]-(24.*60.*60))) else load_blckdate=utc2str(tai2utc(ttimes[n]))
            if fix(blckyr) ge 15 then blckyr=inttobn(fix(blckyr)-5,36,1) else blckyr=strmid(blckdate,3,1)
            stschedule=1
            schfile=outdir+'/'+sc+strmid(blckdate,2,2)+strmid(blckdate,5,2)+strmid(blckdate,8,2)+'00.tmp'
            schfile2=outdir+'/'+strmid(blckdate,2,2)+strmid(blckdate,5,2)+strmid(blckdate,8,2)+'00.sch'
            schfilem1=outdir+'/m1day/'+sc+strmid(blckdate,2,2)+strmid(blckdate,5,2)+strmid(blckdate,8,2)+'00.tmp'
            schfile2m1=outdir+'/m1day/'+strmid(blckdate,2,2)+strmid(blckdate,5,2)+strmid(blckdate,8,2)+'00.sch'
            schfileup=updir+'/'+strmid(blckdate,2,2)+strmid(blckdate,5,2)+strmid(blckdate,8,2)+'00.sch'
            schfileld='temp/'+strmid(load_blckdate,2,2)+strmid(load_blckdate,5,2)+strmid(load_blckdate,8,2)+'00.sch'

            print,'Writing ',schfile
            openw,4,schfile
            printf,4,'#;PT Schedule = ',schfile2
            printf,4,'---00000000B16B0

            print,'Writing ',schfilem1
            openw,8,schfilem1
            printf,8,'#;PT Schedule = ',schfilem1
            printf,8,'---00000000B16B0


        endif

          schdate=utc2str(tai2utc(ttimes[n]))
          if strpos(strlowcase(tcmnt[n]),'door') gt -1 and strpos(strlowcase(tcmnt[n]),'open') gt -1 then schedtxt=tscheds[n] else schedtxt='F2800'+tscheds[n]
          printf,4,blckyr,strmid(blckdate,5,2),strmid(blckdate,8,2),strmid(schdate,11,2), strmid(schdate,14,2), strmid(schdate,17,2),schedtxt
          printf,4,tcmnt[n]

          schdate=utc2str(tai2utc(ttimes[n]-(24.*60.*60)))
          if strpos(strlowcase(tcmnt[n]),'door') gt -1 and strpos(strlowcase(tcmnt[n]),'open') gt -1 then schedtxt=tscheds[n] else schedtxt='F2800'+tscheds[n]
          printf,8,blckyr,strmid(schdate,5,2),strmid(schdate,8,2),strmid(schdate,11,2), strmid(schdate,14,2), strmid(schdate,17,2),schedtxt
          printf,8,tcmnt[n]

  
  endif
endfor
close,4
IF (docmdfile) THEN BEGIN
  IF n_Elements(z34) gt 0 then begin
     lpbrate=sw[0].pbrate
     time=sw.disableque
     tmp=doy2utc(fix(strmid(time,5,3)),fix(strmid(time,0,4))) & tmp.time=((long(strmid(time,9,2))*3600+long(strmid(time,12,2))*60+long(strmid(time,15,2)))*1e3)-(10*60.*1e3)
     dtime=utc2str(tmp)
     dday=strmid(time,5,3)
     dyr=strmid(time,0,4)
     dtime=strmid(dtime,11,8)
     dtime2=strmid(time,9,8)
     time=sw.enableque
     tmp=doy2utc(fix(strmid(time,5,3)),fix(strmid(time,0,4))) & tmp.time=((long(strmid(time,9,2))*3600+long(strmid(time,12,2))*60+long(strmid(time,15,2)))*1e3)
     etime=utc2str(tmp)
     eday=strmid(time,5,3)
     eyr=strmid(time,0,4)
     etime=strmid(etime,11,8)
     etime2=strmid(time,9,8)
     stop
     for zc=1,n_Elements(sw)-1 do begin
        if sw[zc].pbrate ne lpbrate and dday[zc] ge doy and dday[zc] le doy2 then begin
           if lpbrate gt 3 then begin
  	     printf,5,'STARTTIME,'+eyr[zc]+'-'+eday[zc]+'-'+etime[zc]+','+dyr[zc]+'-'+dday[zc]+'-'+dtime2[zc]+',99999,X,X,X,X,X,X,X,X,X,X,X,X'
             printf,5,'Command,20,xrtelemmeter,which,space_weather,type,temporary,units,bits_per_sec,rate,346,X'
           endif
           if lpbrate lt 3 then  begin
  	     printf,5,'STARTTIME,'+dyr[zc-1]+'-'+dday[zc-1]+'-'+dtime[zc-1]+','+dyr[zc-1]+'-'+dday[zc-1]+'-'+dtime2[zc-1]+',99999,X,X,X,X,X,X,X,X,X,X,X,X'
             printf,5,'Command,20,xrtelemmeter,which,space_weather,type,temporary,units,bits_per_sec,rate,5330,X'
           endif
  	     print,'STARTTIME,'+eyr[zc]+'-'+eday[zc]+'-'+etime[zc]+','+dyr[zc]+'-'+dday[zc]+'-'+dtime2[zc]+',99999,X,X,X,X,X,X,X,X,X,X,X,X'
print,lpbrate
           lpbrate=sw[zc].pbrate
print,lpbrate
         endif
     endfor
   endif
   close,5
ENDIF

delcmd='/bin/rm -f '+outdir+'/*.tmp'
spawn,delcmd
delcmd='/bin/rm -f '+outdir+'/m1day/*.tmp'
spawn,delcmd
tek_color
window,xsize=800,ysize=600
tmp=intarr(n_Elements(tscheds))+1
tmp(where(tscheds eq bkgsched))=2
z=where(strpos(tscheds,'.bsf') lt 0,cnt)
if cnt gt 0 then tmp(where(strpos(tscheds,'.bsf') lt 0))=3

dates=utc2str(tai2utc(ttimes+(60*60)))
nt=where(tmp eq 1,cnt)
utplot,dates[nt],intarr(cnt)+.5,yrange=[0,1],ystyle=1,psym=5,color=0,background=1,timerange=[doy2utc(doy-1,yr),doy2utc(doy2+1,yr)],yticks=1,ytickname=[' ',' ']
nt=where(tmp eq 2,cnt)
outplot,dates[nt],intarr(cnt)+.5,psym=5,color=2
for n=0,n_Elements(sw)-1 do outplot,[sw[n].bot,sw[n].bot],[0,.7],linestyle=2,color=0
dtmp=utc2str(tai2utc(anytim2tai(sw.bot)+sw.bot2eot))
for n=0,n_Elements(sw)-1 do outplot,[dtmp[n],dtmp[n]],[0,.7],linestyle=2,color=2
xyouts,300,500,'Begining of Track',/Device,color=0
xyouts,300,475,'End of Track',/Device,color=2
xyouts,500,475,'Out of contact schedule block',/Device,color=2
xyouts,500,500,'Contact schedule block',/Device,color=0
;xyouts,500,450,'COR Doors Open',/Device,color=0
  rday=utc2str(doy2utc(doy,yr))
  pltfile=pltdir+sc+'_'+strmid(rday(0),0,4)+'_'+strmid(rday(0),5,2)+'_'+strmid(rday(0),8,2)
  t=ftvread(/png,filename=pltfile,/noprompt)
 
d1=utc2str(doy2utc(doy,yr))
d2=utc2str(doy2utc(doy2+1,yr))

sidelobe_schedule_rpt,strlowcase(strmid(sc,2,1)),d1,d2,outdir=pltdir

end
