#!/bin/bash 

# A script that moves the motor through a specified number of steps in 
# range [min, max] and logs the value of potPV in each position.
#
# The values are logged in a csv format in $logfile

#
# Author : Matjaz Bercic, 
# Email  : mbercic@slac.stanford.edu and matjaz.bercic@cosylab.com
# Date   : 2013-10-02


# comment this out to not print debug info
# set -x
logfile="pot_values_log.dat"

echo "Set the variables :"
read -p "Range min = " min
read -p "Range max = " max 
read -p "Motor PV  = " motorPV 
read -p "Pot   PV  = " potPV 
read -p "N. points = " npoints 

# min="4.5"
# max="24.7"
# motorPV="NewportXPS:C:TESTSTAND:MOTOR"
# potPV="NewportXPS:B:TESTSTAND:MOTOR"
# npoints="10"
 
echo "Confirm the values :"
echo "Range min = $min"
echo "Range max = $max"
echo "Motor PV  = $motorPV"
echo "Pot   PV  = $potPV" 
echo "N. points = $npoints"
read -p "Are the settings correct ? (y to confirm, anything else to cancel)" ttt 
if [ "$ttt" != "y" ]
then 
  echo "Canceling"
  exit 1
fi 

ret=""
function mcalc {
ret=$(echo "$1" | bc -l )
}

for i in $(seq 0 ${npoints}) 
do 
mcalc "$i*($max - $min)/$npoints + $min"
echo "point X = $ret"
# echo caputt "${motorPV}.VAL" "$ret"
caput "${motorPV}.VAL" "$ret"
read -p "Press return when motion completes" ttt 
motor=$(caget "${motorPV}.RBV")
motorval=$(echo "$motor" | awk '{print $2}')
pot=$(caget "$potPV")
potval=$(echo "$pot" | awk '{print $2}')
time=$(date +%F-%H:%M:%S.%N)
printf "Pot value = $potval, motor position = $motorval, time = $time\n"
printf "%40s , %40s , %40s , %40s , %40s , %40s , \n" "$time" "$motorPV" "$potPV" "$ret" "$motorval" "$potval" >> ${logfile}
done 
echo "Values appended to \"$logfile\""
