!******************************************************************************!
! Tests Jeff's snapper "MODE" change by adding button and logic to perform
! a pipe init, specify new pipe processing, pipe run
! This models Jeff Shoen's Snapper Code
! Arguments: None
!
! @bug      NXM-3360 Jeff is getting timeline WARN: ERROR messages on his "MODE"
!                    changes which trigger pipe inits
! @since    NeXtMidas 3.9.1
! @author:  Jeanette McCall
!******************************************************************************!
startmacro S:throttle["REAL"]
  switch INTERACTIVE interAct GET DEF=TRUE  SDEF=TRUE
  switch BASELINE    baseline GET DEF=FALSE SDEF=TRUE

  switch ERASE         eraseFiles     GET DEF=FALSE  SDEF=TRUE ! erase the large files created/used by this test
  switch RANDOMJITTER  randomJitter   GET DEF=TRUE  SDEF=TRUE  ! jitter varied randomly (versus by count)
  switch TIMELINEKW    timelinekw     GET DEF="TIMELINE"       ! TimeLine keywords "TIMELINE" or "TC"
  switch TLL           timelineLength GET DEF=-1               ! TimeLine length default is GROW_AS_NEEDED

  env get IOOptions origIOOptions
  !env set IOOptions +FixPipeRestartTimeLines               ! No longer needed in 3.9.4
  !env set IOOptions +DoNotPropagateTimelineKeywordsInPipe  ! No longer needed in 3.9.4

  ! Only allow interAct if PANEL command Exists - may be running in LIBNXM mode
  invoke panelExists reg.shell.M.dictionary.isDictionaryEntry(PANEL)

  if interAct AND panelExists then
    set instructions "1) Click towards the updating line in the plot (to the left of it)\n&
                      2) Click 'PIPE_INIT'\n&
                      3) Click right after the restart\n&
                      4) The time at first click should be before the time at second click\n&
                      3) There should not be any errors or warnings"
    
    set started false
    set format sf
    set sr 1e4
    set over 0
    set sfreq sr/10
    set chirpamt sfreq/4
    set amp 1e4
    set noiseamp 1e2
    set fsize 512
    !set numelem 10e10
    set numelem 10e20
    set xferlength 256   ! should match smallest frame size
    set L:timelineLength -1
    set tolr     0
    set maxJitter  0.99e-3  ! should be greater than tolerance
    set firstClick true
    set randomJitter false

    res initTime "2018:01:02::08:00:00"
    new nxm.sys.lib.Time(^initTime) starttime

    res quals {USEBLUETCTIMELINE=true,TLT=^tolr,TLL=^timelineLength}
    set testfile timeline_pipe_init_testfiletmp^quals
    pipe on
      
      panel/msgid=MAIN/setup/controls=gc

      gcontrol label  macro   "MACRO"
      gcontrol menu main "Exit with Status = " "PASS,FAIL" /tleft
      set gc.main.itemColors {PASS=GREEN,FAIL=RED}
      gcontrol text idtext "Instructions" "^instructions" 20 8 /title
      
      gcontrol label  plot  "PLOT/TIMELINE"
      gcontrol button "PIPE_INIT" "" "PIPE_INIT"
      gcontrol tval   timeAtPos1 "Time at 1st click" 0 0 -1 /flags="NoMsg|NoEdit"
      gcontrol tval   timeAtPos2 "Time at 2nd click" 0 0 -1 /flags="NoMsg|NoEdit"
      pipe init
        call pipeaction ! all the waveform / fft / plot action
      pipe run
    pipe off
  endif
  call completetest
  env set IOOptions origIOOptions ! restore original IOOptions
endmacro

!******************************************************************************!
procedure processMessage m:msg
  if msg.name eqs "MAIN" then
    assert/text="^reg.main.name: User indicated tests" msg.data eqss "PASS"
    pipe stop
  elseif msg.name eqs "WARM_START" then
    message send id=warmstart name="OPENFILE" info=-1 data=_fft2
  elseif msg.name eqs "PIPE_INIT" then
    invoke reg.wavechirp.close()
    rem reg.wavechirp
    invoke reg.jitter.close()
    rem reg.jitter
    pipe init
      call pipeaction
    pipe run
  elseif msg.name eqs "DRAGBOX"  then
    if msg.fid eqss "IDPLOTFFT" then
      result tmin msg.data.tmin
      result tmax msg.data.tmax
      timex tmin d:gc.tmin.value
      timex tmax d:gc.tmax.value
      if msg.fid eqs "IDPLOTFFTC" then
        ! second fft from signal with noise added in 3.7.3
        set box2.setBoundsFromTable(msg.data)
      else
        set box1.setBoundsFromTable(msg.data)
      endif
    endif
  elseif msg.name eqs "MARK"
    ! set the "Time At # Click" gcontrols
    if firstClick then
      res gc.timeAtPos1.value msg.data.time
      res firstClick false
    else
      res gc.timeAtPos2.value msg.data.time
      res firstClick true
    endif
  elseif msg.name eqs "UNZOOM"
    if msg.fid eqs "IDPLOTFFT" then
      invoke reg.idplotfft.refresh()
    elseif msg.fid eqs "IDPLOTNOOP" then
      invoke reg.idplotnoop.refresh()
    endif
  elseif msg.name eqs "ZOOM"
  else
    say "Unhandled message name=^msg.name info=^msg.info fid=^msg.fid data=^msg.data"
  endif

return

!***********************************************************************
! put the real action in the pipe in here
! so we can simulate Jeff's mode change
!******************************************************************f*****
procedure pipeaction
  ! pipe file containing chirped waveform and BLUE TC TIMELINE
  waveform/id=wavechirp/throttle=real _wavechirp^quals format ^numelem cos freq=sfreq amp=amp delta=1/sr chirp=^chirpamt start=starttime
  nxm.sys.test.addjitter/id=jitter in=_wavechirp^quals out=_wavechirptl^quals jitter=^maxJitter /TL=xferlength /RANDOM=randomJitter
  fft/dbf/id=fftc _wavechirptl^quals _fftchirp^quals fsize over=over
  noop _fftchirp^quals ^testfile /TL=1
  ! plot the ffts only once
  if started isFalse
    plot/id=idplotfftc/msgid=MAIN/READOUT=Show|OnAxis|T|dT|extPrec|DateString _fftchirp^quals view=iXY
    plot/id=warmstart/msgid=MAIN/READOUT=Show|OnAxis|T|dT _fftchirp view=iXY
    res started true
  endif
  ! add box feature to plot for creating a user selectable dragbox on the raster plot
  FEATURE/id=box1 label=box1 table={NAME=BOX1,TYPE=BOX,COLOR=WHITE,ENABLE=1} plot=idplotfftc
return

! Function to perform final assertion and cleanup
! It will grab the first three times and check that the difference is within tolerance.
procedure completetest
  key ^testfile get TC_WHOLE_1 tcwhole1 TC_WHOLE_2 tcwhole2 TC_WHOLE_3 tcwhole3 TC_FRAC_1 tcfrac1 TC_FRAC_2 tcfrac2 TC_FRAC_3 tcfrac3
  calc time1 tcwhole1 tcfrac1 +
  calc time2 tcwhole2 tcfrac2 +
  calc time3 tcwhole3 tcfrac3 +
  calc diff1 time2 time1 -
  calc diff2 time3 time2 -
  assert/text="^reg.main.name: Timecode diffs within tolerance" diff1 EQT diff2 /TOL=.001
  erase ^testfile 
return
!************************************************************************************************
