#!/bin/bash
caput $1:RECOVERMSG1 "Starting recovery"
caput $1:RECOVERMSG2 ""

# Get status of both translation motors
TM1STAT=$(caget -t  "$1":TM1MOTORSTAT.RVAL)
TM2STAT=$(caget -t  "$1":TM2MOTORSTAT.RVAL)

# Get readback of both translation motors
TM1RBV=$(caget -ts  "$1":TM1MOTOR.RBV)
TM2RBV=$(caget -ts  "$1":TM2MOTOR.RBV)

# Calculate average between motor postitions
TM12=$(echo "scale=4; $TM1RBV+$TM2RBV" |bc)
TMGO=$(echo "scale=4; $TM12/2" |bc)

# Sum of motor status [ 0 - for normal , >1 for problems ]
let TMSTAT=TM1STAT+TM2STAT

if [ "$TMSTAT" -eq 0 ]; then
   # Set destination to both translation motors and GO
   caput $1:TMXPOSC $TMGO
   caput $1:RECOVERMSG1 "Level1 skew fixable"
   caput $1:RECOVERMSG2 "Putting motors back to GO"
   caput $1:TM1MOTOR.SPMG 3
   caput $1:TM2MOTOR.SPMG 3
   sleep 4
   # Retrieve status of motors from SPMG field (in ENUM form)
   TM1SPMG=$(caget -tn "$1":TM1MOTOR.SPMG)
   TM2SPMG=$(caget -tn "$1":TM2MOTOR.SPMG)
   # Combine status in one variable
   flag=$TM1SPMG$TM1SPMG
   test="33"
   count=0
   # Try changing state until both motors are in GO state
   while [ "$flag" != "$test" ]; do
      let "count = $count + 1"
      echo Trying $count
      caput $1:RECOVERMSG1 "Putting motors back to GO, trying $count"
      caput $1:TM1MOTOR.SPMG 3
      caput $1:TM2MOTOR.SPMG 3
      sleep 2
      TM1SPMG=$(caget -tn "$1":TM1MOTOR.SPMG)
      TM2SPMG=$(caget -tn "$1":TM2MOTOR.SPMG)
      flag=$TM1SPMG$TM1SPMG
      caput $1:RECOVERMSG2 "Motors are `caget -t  "$1":TM1MOTOR.SPMG` `caget -t  "$1":TM2MOTOR.SPMG`"
      # If unabel to put motors in GO state in 5 tries then break the loop
      if [ "$count" -gt 5 ]; then
         caput $1:RECOVERMSG2 "Cannot put motors to GO"
         break
      fi
   done
   # Set destination to both translation motors
   caput $1:TMXPOSC $TMGO
   sleep 5
   # Retrieve status of Level 1 Fault
   test=$(caget -tn "$1":LEVEL1FAULTM)
   # Report if Level 1 skew recovery was successfull
   if [ "$test" -eq 1 ]; then
      caput $1:RECOVERMSG1 "Level1 skew recovery successfull!"
      caput $1:RECOVERMSG2 "Motors are `caget -t  "$1":TM1MOTOR.SPMG` `caget -t  "$1":TM2MOTOR.SPMG`"
   else
      caput $1:RECOVERMSG1 "Level1 skew recovery not successfull"
      caput $1:TM1MOTOR.SPMG 0
      caput $1:TM2MOTOR.SPMG 0
      sleep 2
      caput $1:RECOVERMSG2 "Motors are `caget -t  "$1":TM1MOTOR.SPMG` `caget -t  "$1":TM2MOTOR.SPMG`"
   fi 
# If problem with motors, put motors in STOP state and report it 
else
   caput $1:RECOVERMSG1 "Fix motor communication error first"
   caput $1:TM1MOTOR.SPMG 0
   caput $1:TM2MOTOR.SPMG 0
fi
