#!/bin/sh
#
# batchcharmapper
#
# version 0.2.0
#
#
# 0.2.0  06/02/15 - Changed to use the sh shell, removed IRIX suport.
# 0.1.0a ??/??/?? - Changed to use nuance
# 0.1.0  02/27/01 - Initial version.
#
#
uname_out=`uname`
if [ "$uname_out" = "Linux" ]; then
  AWK=awk
else
  echo "Unknown platform."
  exit 1
fi

if [ $# -lt 4 ]; then
  echo ""
  echo "Usage:"
  echo "  batchcharmapper [-output_tag <tag>] <cm project> <output motion type>"
  echo "                  <anim> <output dir>"
  echo ""
  echo "  Note that this script only functions properly with single layered"
  echo "  charmapper projects."
  echo ""
  echo "  If -output_tag is used, the tag is inserted before the output"
  echo "  motion's .<output motion type> in the file name.  For example if"
  echo "  the output motion name would be mymotion.bmo without using -output_tag,"
  echo "  then the output file name would be mymotion_cm.bmo if \"-output_tag _cm\""
  echo "  was used."
  echo ""
  echo "  Example:"
  echo ""
  echo "    batchcharmapper ./project.cpj bmo \"/somepath/client1*.anm\" /myresults/"
  echo ""
  exit 1;
fi

output_tag=""

if [ $1 = "-output_tag" ]; then
  shift;
  output_tag=$1
  shift
fi

cm_project=$1
output_motion_type=$2
anims=$3
output_dir=${4%/} # take off the last slash, if exists

for anim in $anims; do
  input_motion_type="bmo"
  input_motion=`$AWK '$1=="MOTION:" { print $2 }' <$anim`
  eval "input_motion=$input_motion"

  if [ "$input_motion" = "" ]; then
    input_motion=`$AWK '$1=="AMC:" { print $2 }' <$anim`
    eval "input_motion=$input_motion"
    input_motion_type="amc"
  fi

  if [ "$input_motion" != "" ]; then
    if [ "$output_dir" != "" ]; then
      output_motion=$output_dir/`basename $input_motion`
    else
      output_motion=$input_motion
    fi

    output_motion=${output_motion%.$input_motion_type*}$output_tag.$output_motion_type

    if [ "$input_motion" = "$output_motion" ]; then
      echo ""
      echo "Cowardly refusing to overwrite input motion for anim: $anim"
      echo ""
    else
      echo nuance -cm_batch $cm_project -layer 1 $input_motion $output_motion
      nuance -cm_batch $cm_project -layer 1 $input_motion $output_motion
    fi
  else
    echo ""
    echo "  Input anim: $anim has no bmo or amc motion."
    echo ""
  fi
done
