#!/bin/bash

PLEE_THE_BEAR=../../bear-engine/bin/running-bear
MODE="$1"
ARGS='--log-level=warning --log-concise --game-name="Plee the Bear" --screen-width=800 --screen-height=600 --stats-destination=http://plee-the-bear.sourceforge.net/stats.php --active-area=500 --data-path=../data --item-library=../../bear-engine/bin/libbear_generic_items.so --item-library=../bin/libplee_the_bear.so --start-level=level/title_screen.cl'

shift

export LD_LIBRARY_PATH="../bin:../../bear-engine/bin:$LD_LIBRARY_PATH"

rm -f *.timelog

if [ "$MODE" == "gdb" ]
then
    echo Parameters : $ARGS $@
    gdb $PLEE_THE_BEAR
elif [ "$MODE" == "valgrind" ]
then
  echo $ARGS "$MODE" "$@" | xargs valgrind --leak-check=full --show-reachable=yes --error-limit=no $PLEE_THE_BEAR 2>&1
else
  echo $ARGS "$MODE" "$@" | xargs $PLEE_THE_BEAR
fi

if which mencoder >/dev/null \
   && ls ~/.plee_the_bear/*.seq >/dev/null 2>/dev/null
then
  for SEQ in ~/.plee_the_bear/*.seq
  do
    BASE=$(echo $SEQ | sed 's/\.seq$//')
    FPS=$(cat $SEQ | cut -d' ' -f1)

    echo $BASE $FPS
    mencoder mf://$BASE-*.bmp \
      -mf w=800:h=600:fps=$FPS:type=bmp -ovc x264 \
      -oac copy -o $BASE.avi
  done
fi

rm -f $HOME/.plee_the_bear/s-*.bmp
rm -f $HOME/.plee_the_bear/*.seq

if ls *.timelog >/dev/null 2>/dev/null && which gnuplot >/dev/null
then
  ( echo 'set term svg'
    echo 'set output "timelog.svg'
    echo -n "plot "
    for f in *.timelog
    do
      echo '"'$f'" title "'$(basename $f .timelog)'" with lines, \'
    done
    echo "0 notitle with points 0"

  ) | gnuplot 2>/dev/null
fi
