#!/bin/bash

# Requires packages: mplayer mencoder

syntax="Syntax: <b>mpegrotate</b> [cw|ccw] inputfilename\n"
rotatedsuffix=".rotated"
if [ $# -lt 2 ]; then
	echo $syntax
	exit 0
fi

if [ "$1" == "cw" ]; then
	rotation=1
elif [ "$1" == "ccw" ]; then
	rotation=2
else
	echo $syntax
	exit 1
fi

# For Bash scripting, see http://tldp.org/LDP/abs/html/
# Now, if our script is called e.g. as "mpegrotate cw *.mpg", $2 will NOT contain "*.mpg"; it will contain the first element in the expansion of this (globbing happens before the script is called).
# So use $@ to represent all arguments instead.
# Or, to iterate over 2-n not 1-n, use the indirection syntax below: http://stackoverflow.com/questions/1769140/how-to-iterate-over-positional-parameters-in-a-bash-script
# Or use shift: http://tldp.org/LDP/abs/html/othertypesv.html#EX19

for ((i=2; i<$#; i++))
do
	infile=${!i}
	outfile=$infile$rotatedsuffix
	/usr/bin/mencoder -ovc lavc -vf rotate=$rotation -oac copy $infile -o $outfile
	# -ovc lavc = encode with a libavcodec codec
	# -oac copy = no audio encoding, just streamcopy
	# -vf adds video filters:
	# -vf rotate=
	#	0 Rotate by 90 degrees clockwise and flip (default).
	#	1 Rotate by 90 degrees clockwise.
	#	2 Rotate by 90 degrees counterclockwise.
	#	3 Rotate by 90 degrees counterclockwise and flip.
done

exit 0
