#!/bin/sh

# Custom - Only intended for Kirk Wallace's HNC lathe, KW  20070823
# M101 - Reads current T word selection and rotates turret to
#        place matching tool slot in operating position. Like M6

# Read T
requested_tool=$(halcmd -s show pin iocontrol.0.tool-prep-number|cut -c 21)

# Read current turret tool position
current_tool=$(halcmd -s show pin wsum.0.sum|cut -c 24)

# If requested tool is already in position - do nothing
if [ $requested_tool = $current_tool ]
then
  exit 0
fi

# Loop one position at a time until we get a match
while [ "$current_tool" != "$requested_tool" ]; do

# rotate and park one position
  halcmd sets TurretRotate True
  sleep .2
  halcmd sets TurretStop True
  sleep .2
  halcmd sets TurretRotate False
  sleep .1
  halcmd sets TurretStop False
  sleep .1

# Read current turret tool position
current_tool=$(halcmd -s show pin wsum.0.sum|cut -c 24)

done

## Check "turret locked" sensor and e-stop if not locked, otherwise
## exit
# turret_locked=$(halcmd -s show pin ppmc.0.din.10.in|head -n 1|cut -c 20)
# if [ $turret_locked != T ]
# then 
#   # insert link to e-stop
# else
# done
exit 0
