#!/bin/bash

# Get motor status
MOTORSTAT=$(caget -ts  "$1":"$2"MOTORSTAT.RVAL)
caput $1:$2RECVRYMSG "Getting motor status"
sleep 2

#Get motor val
MOTORVAL=$(caget -ts  "$1":"$2"MOTOR)
caput $1:$2RECVRYMSG "Getting motor value, .VAL"
sleep 2

#Get pot val
POT=$(caget -ts  "$1":"$3")
caput $1:$2RECVRYMSG "Getting pot value"
sleep 2

#Calculate motorval-pot 
ERROR=$(echo  "scale=4; ($MOTORVAL)-($POT)" |bc )
echo error is $ERROR

#Make it into an integer
ERRORINT1=`echo $ERROR*100000 | bc -l | awk -F '.' '{print $1; exit;}'`
echo Integer error is $ERRORINT1
#echo new script 3
if [ "$ERRORINT1" -lt 0 ]; then
   ERRORINT=`echo $ERROR*-100000 | bc -l | awk -F '.' '{print $1; exit;}'`
else
   ERRORINT=`echo $ERROR*100000 | bc -l | awk -F '.' '{print $1; exit;}'`
fi
echo Integer error is $ERRORINT

#Put motor to set mode
caput $1:$2MOTOR.SET 1
caput $1:$2RECVRYMSG "Putting motor to SET mode"
sleep 2

#Override motor interlock
caput $1:$2MTNOVRRDC 1
caput $1:$2RECVRYMSG "Overriding motor interlock"
sleep 2

#reset motor position if motor communication is ok
if [ "$MOTORSTAT" -ne 1 ]; then
   #Put motor back to go
   caput $1:$2MOTOR.SPMG 3
   caput $1:$2RECVRYMSG "Putting motor back to GO"
   sleep 2
   MOTORSPMG=$(caget -tn "$1":"$2"MOTOR.SPMG)
   echo spmg = $MOTORSPMG - `caget -t "$1":"$2"MOTOR.SPMG`
   test=3
   echo test = $test
   count=0
   sleep 2
   while [ "$MOTORSPMG" != "$test" ]; do
      let "count = $count + 1"
      echo Trying $count
      caput $1:$2MOTOR.SPMG 3
      caput $1:$2RECVRYMSG "Putting motor to GO, try $count"
      sleep 2
      MOTORSPMG=$(caget -t  "$1":"$2"MOTOR.SPMG)
      if [ "$count" -gt 5 ]; then
         caput $1:$2RECVRYMSG "Cannot put motors to GO"
         break
      fi
   done
   if [ "$count" -lt 5 ]; then
      #reset using motorval
      if [ "$ERRORINT" -lt 100000 ]; then
         caput $1:$2RECVRYMSG "Resetting motor using .VAL"
         caput $1:$2MOTOR $MOTORVAL
         sleep 2
         caput $1:$2RECVRYMSG "Recovery successfull"
      else
      #reset using pot
         caput $1:$2RECVRYMSG "Resetting motor using POT"
         caput $1:$2MOTOR $POT
         sleep 2
         caput $1:$2RECVRYMSG "Recovery successfull"
      fi
   fi
else
   caput $1:$2RECVRYMSG "Fix motor communication error, reboot & power cycle motor"
fi

#Put motor to use mode
caput $1:$2MOTOR.SET 0

#Undo override motor interlock
caput $1:$2MTNOVRRDC 0
