#!/bin/bash 
# set -x 

# short script to automatically move grating Y 
# Author : Matjaz Bercic
# Email  : mbercic@slac.stanford.edu matjaz.bercic@cosylab.com

if [ "$1" == "" ]
then 
  echo "use : $0 < num of repetitions"
  exit 1
fi

# drive motor up and down for #1 number of times, if #1 == 0 do it forever
log="./log_test"
dat=$(date +%F-%H-%M-%S)
# read -p "enter log name : " log
# log="${dat}-${log}"

function clc {
echo "scale=3; ${1}" | bc -l 
}
function getpv {
pv=$(caget "${1}" | awk '{print $2}')
}
function getfield {
pv=$(caget "${1}.${2}" | awk '{print $2}')
}
function putfield {
caput "${1}.${2}" "${3}"
}
slp_time=0.2
function waitmotion {
sleep ${slp_time}
dw="0"
while [ "$dw" != "1" ]
do 
  getfield "$mtr" DMOV 
  dw="$pv"
  sleep ${slp_time}
done
}

min="-280"
max="280"
step="0.1"
mtr="GRAT:UND1:934:Y:MOTOR"
moveabs="${mtr}.VAL"
readback="${mtr}.RDB"
doesmove="${mtr}.DMOV"

nmoves="$1"

echo "Number of moves = ${nmoves}"

# 1) homeR test 
it=0
while [ "$it" -lt "$nmoves" ]
do 
  echo "REPETITION #${it}"
  it=$(( $it + 1 ))
  waitmotion
  putfield "$mtr" VAL "$max"
  waitmotion
  putfield "$mtr" VAL "$min"
done 

if [ "$2" == "0" ]
then 
  waitmotion
  putfield "$mtr" VAL "0"
fi

