startmacro/np=16+1/nw=16*10+1/quiet/timeout=100/ds/nmq=1k &
  a:device[PIC] n:ndev[8] n:ntun[2] n:nseg[2k] &
  n:ndec[256] n:samplerate[4*10e6] n:freq[16*78000]

local nyquist ramqual nd nt nn ii 
local osamplerate plotmax plotmin format filesize 

res nyquist samplerate/2
env set pause 0.01
calc nport ndev*ntun

! create test input file
if ramaux rexists then
  res ramqual "(CTG=1)(AUX=RAMAUX)(DET=1)"
else
  res ramqual "(CTG=1)"
endif

if /c gt 0
  res format "CI"
  calc osamplerate samplerate/ndec/2
else
  res format "SI"
  calc osamplerate samplerate/ndec
endif

calc filesize 1*osamplerate nseg*2 max round

! reset devices create test output files
loop ndev nd
  picd reset ^{device}^nd
  if /TEST gt 0 picd reset ^{device}^nd iir
  loop ntun nt
    pic create testout_^{nd}_^{nt} ^format ^filesize osamplerate
  endloop
endloop

! start test waveform playback
if /TEST
  res switches "flags=muxclk|intclk"
  res plotmax "60"
  res plotmin "-60"
else
  res switches " "
  res plotmax " "
  res plotmin " "
endif


xpipe/setup/controls on

control/wb=1 dval "Freq: "
 
loop ndev nd
loop ntun nt
  calc ii (nd-1)*ntun nt +
  sourcepic/id=10+nn/port=tuner^nt/^switches/packet/tl=nseg &
		testout_^{nd}_^{nt} _cb^ii ^{device}^nd ndec freq
endloop
endloop

if /sock gt 0
  picfunc/afn=nport/renum/tl=nseg PACK file socket /sock
else
  picfunc/afn=nport/renum/tl=nseg PACK file _mux(ps=1m) _cb
endif

xpipe off

! reset devices create test output files
loop ndev nd
  picd reset ^{device}^nd
  loop ntun nt
    erase testout_^{nd}_^{nt} 
  endloop
endloop

endmacro

startcontrols

label initialentry
xcontrol/lab=xxx menu item 0 "Macro;Exit"
return

xcontrol/name="Plot: "/lab=xchan lval nn nn 1 ntun 1
xcontrol/lab=freqx dmon w_1001

label xchan
xcontrol/over=4/name="TFreq^ii: " dval ,, freq 0 nyquist nyquist*1e-5 ww+5
xcontrol/over=5/name="TGain^ii: "/len=6 lval ,, 0 -100 100 1 ww+6
xcontrol/over=6/lab=menux menu item 0 "Plot ^nn;Start,Stop,Chan,TCode"
xcontrol/over=7/name="TDec^ii: "/len=6 lval ,, ndec 16 8192 2 ww+4
return

label freqx
xcall wgetid pid 1001
!say "Got new freq ^pfreq from ^pid"
calc nn pid-100
goto xchan

label menux
res wwp1 ww+1
if item eq 1 then
  res w_^wwp1 2
elseif item eq 2 then
  res w_^wwp1 4
elseif item eq 3 then
  if w_^wwp1 ne 0
    xcall message "Channel must be stopped first"
  else
    xcall/name="Tuner #: " lval ii ii 1 24 1
    message send "DEVICE" nn+10 ii  
    message send /TITLE/ nn+100 0 "Plot-^nn  Tuner-^ii" 
    goto xchan
  endif
elseif item eq 4 then
  message send "TC" nn+10 ,, 1 "D" -1
  message getwn "=TC" ,,,,, sample time1 time2
  timex time1|time2 tx:timecode
  say "TC = ^timecode at Sample ^sample"
endif
return

label xxx
stop
return


endcontrols
