#!/bin/bash
function usage {
echo "
  Decodes and prints the crate and module (in decimal) from 
  the bits found in the PLOC PV field of a given klystron 
  or subbooster. 
 
  Usage:
         ploc [qh] {SBST|KLYS} area unit
 
  E.g.
         ploc klys li18 61
           KLYS:LI18:61:PLOC hex = 0x3200 == cr = 3, mo = 4
         ploc -q klys li18 61
           3 4
         ploc sbst LI18 1
           SBST:LI18:1:PLOC hex = 0x2280 == cr = 2, mo = 5

  Ver. 1.0
"
}
#!---------------------------------------------------------
#! Auth: Greg White, 08-Sep-2010
#! Rev: 
#! Mod:  Greg White, 05-may-2011
#!       Fixed conditon handling from caget.
#! ========================================================

quiet=0;
while getopts qh opt
do
   case "$opt" in
      h) usage; exit 0;;
      q) quiet=1;;
      *) echo "Unknown argument, see ploc -h"; exit 1;;
   esac
done
shift $((OPTIND-1))

prim=`echo ${1} | tr '[:lower:]' '[:upper:]'`
area=`echo ${2} | tr '[:lower:]' '[:upper:]'`
unit=$3
let C1=0x1000
let cmask=0xF
let M1=0x80
let mmask=0x1F
ploc=`caget -t $prim:$area:$unit:PLOC`
stat=$?
if [ $stat != 0 ]; then 
   echo "Unable to acquire PLOC, exiting" 
   exit $stat
fi
 
export crate=$((cmask & ploc/C1))
export module=$((mmask & ploc/M1))

if [ $quiet -eq 0 ]; then
   echo $prim:$area:$unit:PLOC hex = `printf "0x%x" $ploc` == cr = $crate, mo = $module
else
   echo $crate $module
fi

exit 0
 

