#!/bin/sh

# matlab_png2avi
# Create an AVI animation from a sequence of MATLAB PNG figures.
# Miroslav Broz (miroslav.broz@email.cz), Jul 26th 2004

# HISTORY
# Jul 26th 2004: -small argument for one predefined set of arguments
# Feb 17th 2004: -noerase argument to save all temporary files
# Jan 5th 2004: -TMP argument allowing resumption of the convert process
# Oct 9th 2003: Encoding via SGI file format, what solves problems
#   with grayscale JPEGs!

if [ "$1" = "" ] ; then
  echo "Usage: matlab_png2avi [OPTIONS] FILE"
  echo "FILE*.png are input images and FILE.avi is the output animation"
  exit
fi

# default values of command-line parameters
SX=2048
SY=1152
DX=1024
DY=576
FPS=25
NOERASE=0

# resolve command-line arguments
FILE=""
I=1
while [ $I -le $# ] ; do
  ARG=`eval echo "$"{${I}}`
  if [ "$ARG" = "-SX" ] ; then
    I=`expr ${I} + 1`
    SX=`eval echo "$"{${I}}`
  else if [ "$ARG" = "-SY" ] ; then
    I=`expr ${I} + 1`
    SY=`eval echo "$"{${I}}`
  else if [ "$ARG" = "-DX" ] ; then
    I=`expr ${I} + 1`
    DX=`eval echo "$"{${I}}`
  else if [ "$ARG" = "-DY" ] ; then
    I=`expr ${I} + 1`
    DY=`eval echo "$"{${I}}`
  else if [ "$ARG" = "-FPS" ] ; then
    I=`expr ${I} + 1`
    FPS=`eval echo "$"{${I}}`
  else if [ "$ARG" = "-TMP" ] ; then
    I=`expr ${I} + 1`
    TMP=`eval echo "$"{${I}}`
  else if [ "$ARG" = "-noerase" ] ; then
    NOERASE=1
  else if [ "$ARG" = "-small" ] ; then
    SX=640
    SY=360
    DX=$SX
    DY=$SY
  else
    FILE=$ARG
  fi fi fi fi fi fi fi fi
  I=`expr $I + 1`
done

if [ "$FILE" = "" ] ; then
  echo "No filename on command-line."
  exit 1
fi

DIR=`pwd`
#TMP=/tmp/matlab_png2avi$$
if [ "$TMP" = "" ] ; then
  TMP=/scratch/matlab_png2avi$$
fi

mkdir $TMP

for F in $FILE[0-9]*.png ; do
  echo $F
  if [ ! -e $TMP/$F.sgi ] ; then
    convert -crop $SX"x"$SY+0+0 -geometry $DX"x"$DY"!" $F $TMP/$F.sgi
    if [[ -e core ]] ; then
      echo "matlab_png2avi: Warning: Core dumped, trying convert once more."
      convert -crop $SX"x"$SY+0+0 -geometry $DX"x"$DY"!" $F $TMP/$F.sgi
      rm core
    fi
  fi
done

LAVCOPTS="vcodec=mpeg4:vhq:vbitrate=2400:v4mv:mbd=2:trell:autoaspect"

cd $TMP
mencoder \
  -mf fps=$FPS:type=sgi \
  -ovc lavc -lavcopts $LAVCOPTS:vpass=1 \
  -o $DIR/$FILE.avi \
  "mf://$FILE*.sgi"

mencoder \
  -mf fps=$FPS:type=sgi \
  -ovc lavc -lavcopts $LAVCOPTS:vpass=2 \
  -o $DIR/$FILE.avi \
  "mf://$FILE*.sgi"

#  -ovc lavc -lavcopts vcodec=mjpeg:vhq:vbitrate=16000:vqscale=2 \

#echo "If mencoder crashes, convert greyscale jpeg files by jpg24bit!"

## a poor quality compression for line graphics:
#mencoder \
#  -mf on:w=$DX:h=$DY:fps=10:type=jpg \
#  -ovc lavc -lavcopts vcodec=mpeg1video \
#  -o $DIR/$1.avi \
#  $1\*.jpg

cd $DIR
if [ "$NOERASE" = "0" ] ; then
  rm -r $TMP
fi


