#!/bin/bash
(

prg=$0
if [ ! -e "$prg" ]; then
  case $prg in
    (*/*) exit 1;;
    (*) prg=$(command -v -- "$prg") || exit;;
  esac
fi
dir=$(
  cd -P -- "$(dirname -- "$prg")" && pwd -P
) || exit
prg=$dir/$(basename -- "$prg") || exit 

top=`dirname -- "$prg"`

export PATH="\
$top/../software/fmc-adc-100m14b4cha-sw/tools:\
$top/../software/fmc-adc-100m14b4cha-sw/libtools:\
$PATH"

# remove old data
rm -f /tmp/data.bin

# prepare the FMC ID in a format used by fald-acq
fmcid=`printf "%02x00" $3`

# prepare the path to the FMC files
adcpath="/sys/bus/zio/devices/adc-100m14b-${fmcid}/"

# read current software trigger setting
swen=`cat ${adcpath}/cset0/trigger/sw-trg-enable`

if [ $swen -eq 0 ];
then 
	# enable the software trigger if it wasn't already
	echo 1 > "${adcpath}/cset0/trigger/sw-trg-enable"
	# seems that there must be considerable delay after this change
	sleep 5
fi

# configure the acquisition
# b - samples before trigger
# a - samples after trigger
# r - range (1V or 10V)
# B - output binary location
fald-acq -b 0 -a $1 -r $2 -B /tmp/data.bin "0x${fmcid}" &

# wait for the program to start
sleep 1

# manually trigger the acquisition
echo 1 > "${adcpath}/cset0/trigger/sw-trg-fire"

# wait for the detached program to return
wait

)


