#!/bin/bash

FFMPEG_PARAMS="-r 15 -b 325"
if [ -f "$HOME/.ffmpeg-palmrc" ]; then
        . $HOME/.ffmpeg-palmrc
fi

file=$1
out=${2:-$file.out.avi}

if [ ! -f "$file" ] ; then
        echo "Usage: $0 <input file> [<output file>]"
        exit
fi

if [ -e "$out" ] ; then
        echo "Output file already exists!"
        exit
fi

x=`ffmpeg -i "$file" 2>&1 | grep Video | grep -oE " [0-9]{2,}x[0-9]{2,}" | grep -oE "[0-9]{2,}x"`
y=`ffmpeg -i "$file" 2>&1 | grep Video | grep -oE " [0-9]{2,}x[0-9]{2,}" | grep -oE "x[0-9]{2,}"`

y=${y:1} # Removing trailing 'x'

# Use (length - 1) to removing leading 'x'
t=${#x}
let 't--'
x=${x:0:t}

let 'z = 160 * y / x'
let 'z *= 2'
size="320x$z"

echo ffmpeg -i "$file" -s $size $FFMPEG_PARAMS "$out"
ffmpeg -i "$file" -s $size $FFMPEG_PARAMS "$out"
