#!/bin/sh
#
# fixmotionfieldcount
#
# version 0.1.1
#
# history
# 0.1.1  07/14/2015  Updated to handle motion tags.
#        01/24/2003  Changed to /bin/sh
# 0.1.0  09/18/2000  Added version number.
#                    Updated to work under linux.
#
uname_out=`uname`
if [ `expr $uname_out : 'IRIX'` = 4 ]; then
  AWK=nawk
elif [ "$uname_out" = "Linux" ]; then
  AWK=awk
else
  echo "Unknown platform."
  exit 1
fi
motion=$1
if [ ! -f "$motion" ]; then
  echo "$motion does not exist"
  exit 1
fi
varcount=`head -4 "$motion" | sed -n '4p'`
firstfield=`head -5 "$motion" | sed -n '5p' | $AWK '{ print $4+0; }'`

# Start 1000 lines from the bottom looking for frames
lines=`expr $varcount + 1000`
lastfield=`
tail -$lines "$motion" | $AWK '
{
  if ($1=="Results" && $2=="for") {
    last_frame_id=$4+0
  }
}
END {
  print last_frame_id
}
'
`
fieldcount=`expr $lastfield - $firstfield + 1`
echo "Motion contains $fieldcount fields $firstfield - $lastfield" >&2
sed '3c\
'$fieldcount'
' <"$motion" >"$motion.new$$"
mv "$motion.new$$" "$motion"
