#!/bin/bash
# modified
# mcmpca16.c
# chiptester-zerosup-gains.sh
# lvcard.c
#
# if arguments:
# 1 - chipnumber (as written on chip)
datadir=/home/jum/wdir/ilcdaq/data
#datadir=/home/jum/work/ilc/readout/data
 VXI settings
#=============
vxipath=$HOME/ilc/ilcdaq/chiptests/vxi11/bin
IP="192.168.4.10"
 VXI settings
#=============
vxipath=$HOME/ilc/ilcdaq/chiptests/vxi11/bin
IP="192.168.4.10"
if [ $# == 0 ]; then
    chipnumber=0
elif [ $# == 1 ]; then
    chipnumber=$1
else
    echo "Wrong number of arguments: " $#
    exit
fi
#
# create datadirectiry - if not existing
if [ ! -e ${datadir}/chip${chipnumber} ]; then
    echo " ${datadir}/chip${chipnumber} does not exist - creating it"
    mkdir ${datadir}/chip${chipnumber}
    iret=$?
    if [ $iret != 0 ]; then
	echo mkdir exiting with status $iret
	exit
    fi
fi
#
# setup serial interface
# baud rate to 38400, 8 bits, 1 stop bit, no parity:
stty -F /dev/ttyUSB0 38400 cs8 -cstopb -parenb ixoff -icrnl -opost -onlcr -isig -icanon -echo -echoe
iret=$?
if [ $iret != 0 ]; then
    echo stty exiting with status $iret
    exit
fi
#
# initialize SRU
./srupup --sruif enp3s0
#
# initialize lvcard
filename=${datadir}/chip${chipnumber}/lvcard.csv
echo $filename
./lvcard --init --filecsv $filename
iret=$?
if [ $iret != 0 ]; then
    echo lvcard --init exiting with status $iret
    exit
fi
#
# power on protomcm
./lvcard --power 1 --filecsv $filename
iret=$?
if [ $iret != 0 ]; then
    echo lvcard --power 1 exiting with status $iret
    # lvcard --power 1 exiting with status 2
    # output 20220827,122250,1,3108,3099,818,947,2,0,0
#    exit
fi
#
# switch on SALTRO
echo switch on SALTRO
./mcmpca16 --fec 0 --preamp 0 --gain 0 --shaper 0 --shutdown 0 --polarity 1 --biasctrl 1 --grst 1 --write
iret=$?
if [ $iret != 0 ]; then
    echo mcmpca16 exiting with status $iret
#    exit
fi
./lvcard --saltro 1 --filecsv $filename
iret=$?
if [ $iret != 0 ]; then
    echo lvcard --saltro 1 exiting with status $iret
    echo will try to power off
#    ./lvcard --saltro 0 --filecsv $filename
    ./lvcard --power 0 --filecsv $filename
    exit
fi
$vxipath/vxi11_send $IP "*RCL 1"
