#!/bin/bash
(

	###########################################
	######### prepare environment #############
	###########################################

	#finding top directory location
	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 directory location stored in variable
	top=`echo "$prg" | sed 's/fmcdac600m12b1chadds.*/fmcdac600m12b1chadds\//'`

	# format adc identifier
	id=`printf "%02x00" $3`

	# prepare adc interface path
	adcpath="/sys/bus/zio/devices/adc-100m14b-$id/"
	
	###########################################
	############# clean up  ##################
	###########################################

	# kill acquisition program
	pid=`ps aux | awk '$11 == "fald-acq" {print $2}'`
	if [ -n "$pid" ]
	then
		echo "killing: $pid"
		kill -9 $pid
	fi

	# then data buffer
	rm -f /tmp/data.bin


	###########################################
	############# acquire data ################
	###########################################
	
	# configure software trigger
	echo 1 > "${adcpath}/cset0/trigger/sw-trg-enable"
	sleep 1

	# run acquisition program detached from current terminal
	timeout 10 "$top/software/fmc-adc-100m14b4cha-sw/libtools/fald-acq" -b 0 -a $1 -r $2 -B /tmp/data.bin "0x${id}" &
	
	# wait
	sleep 1

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

	# wait for fald-acq to return
	# it will either return after acquisition or with timeout
	wait $!

	if [ "$?" -eq 0 ]
	then
		echo "fald-acq retured succesfully"
		exit 0 
	else
		# echo "fald-acq retured with status $?"
		echo "$(tput setab 1)fald-acq retured with status $?(tput sgr 0)"
		echo "retrying with bigger delay"
		
		# kill acquisition program
		pid=`ps aux | awk '$11 == "fald-acq" {print $2}'`
		if [ -n "$pid" ]
		then
			echo "killing: $pid"
			kill -9 $pid
		fi

		# then data buffer
		rm -f /tmp/data.bin 

		# run acquisition program detached from current terminal
		timeout 15 "$top/software/fmc-adc-100m14b4cha-sw/libtools/fald-acq" -b 0 -a $1 -r $2 -B /tmp/data.bin "0x${id}" &
		
		# wait
		sleep 5

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

		wait $!

		if [ "$?" -eq 0 ]
		then
			echo "fald-acq retured succesfully"
			exit 0 
		else
			echo "fald-acq retured with status $?"
			echo "abording"
			exit 1 
		fi
	fi
	

)


