#!/bin/bash 
#-*-sh-*-
#==============================================================
#
#  Abs:   Lists "names" in the aida schema matching the given pattern.
#
#  Name:  wsdata
#
#  Rem:   This script returns the "instance" (and optionally "attributes"
#         too) matching the sqlplus pattern given in the arguments. It can
#         also tell you from where AIDA would get the data, using the -m arg.
#
#         aidalist examines the value of AIDA_MODE to see which aida
#         directory to look in.
#
#  Usage: wsdata [-help or -m] <device-name> [<step-size>]
#
#         See help for examples.
#
#  Side:  Accesses Oracle
#
#  Auth:  dd-mm-2015, Gasper Jansa  (gasper):
#  Rev:   dd-mmm-yyyy, Whoever       (username):
#--------------------------------------------------------------
# Mods:
#         21-Jan-2016, K. Luchini   (luchini)
#           modify original script, input arguments,
#           help and standard header.
#
#==============================================================
#
function usage {
    echo "
Usage: `basename $0` [-h] device [step-size]
   -h   Show this help

   \"instance\" is an Wire Scanner instance name, such as a device name
    echo "
wirescanData is used to collect data from a slow wire scanner for calibration,
using the lvdt position and motor position data.


Example:
            wsdata WIRE:LTU1:538
    echo
    exit 0
}

# Process options and arguments. There is only one option, -h, meaning help.
# There must be 1 argument, the instance name.
#
while getopts hm opt; do
    case $opt in
        h) usage ;;
        *) printf "option \"$opt\" not recognized. Try wirescanData -h for help\n" 
    esac
done

if [ $# -ne 1 ]; then
    echo "The device name must be given. Try wirescanData -h for help." 
    exit 1
fi


step=`caget -t "$1:MOTR.TWV"`
if [ $step -lt 1000 ]; then
  echo "Motor step-size of" "$step" "is too small, default to 1000." 
  step=1000;
fi
lowerLimit=`caget -t $1:MOTR.LLM`
upperLimit=`caget -t $1:MOTR.HLM`
range=$((upperLimit-lowerLimit))
num=$((range/step))
if [ $num -lt 0 ]; then 
  num=$((num*-1))
fi
echo "$1" 
echo "step size: $step" 
echo "upper limit: $upperLimit" 
echo "lower Limit: $lowerLimit" 
echo "range: $range"
echo "number points: $num" 
echo "Starting for loop"
for ((i=1; i<=num; i++)); do
 curpos=`caget -t -f 0 "$1:MOTR"`  
 curpos=`echo $curpos + $step | bc`
 if (( $curpos > $upperLimit )) ; then
   echo "attempting to set motor to $curpos, which is beyond upper limit of $upperLimit" 
   exit 1
 fi
 if (( $curpos < $lowerLimit )) ; then
   echo "attempting to set motor to $curpos, which is beyond the lower limit $lowerLimit" 
   exit 1
 fi
 echo "sending motor to position" "$curpos" 
 caput $1:MOTR "$curpos"

 sleep 2

 echo "aquiring data"
 lvdt=`caget -t -f 0 "$1:LVRAW"`  
 motor=`caget -t -f 0 "$1:MOTR.RBV"`  
 echo "$i: $lvdt" "$motor"
 echo "$lvdt" "$motor" 1>> output.txt
done

# End of script

