#!/bin/sh
# $Id: xvidenc, v 6.7, 2007/05/31, gn Exp $
# UUID: 1ff8ecff-b178-4d64-b084-71ebd7972fe7
#
# Encode DVDs/video files to the Xvid format
# using MEncoder from MPlayer
#
# Copyright (C) 2006, 2007 - Grozdan Nikolov
#
# This program is free software ; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation ; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY ; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program ; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

export PATH=$PATH:/usr/local/bin
version=6.7

case "$1" in
	"")
	echo "Usage: `basename $0` [-1p|-2p|-fq|-o|-v|-p help] [-p {ulq|vlq|lq|mq|nq|hq|vhq|ehq|uhq}]"
	echo "       For more info use the --help option"
	exit 1
	;;
	-v)
	echo "xvidenc $version"
	exit 0
	;;
	--help)
	echo ""
	echo "+=======================================================+"
	echo "| xvidenc - a step-by-step encoding helper shell script |"
	echo "+=======================================================+"
	echo ""
	echo "xvidenc is a small script which uses the encoding utility"
	echo "MEncoder from MPlayer to encode a DVD or a video file to"
	echo "the high-quality MPEG-4 codec called Xvid. The Xvid codec"
	echo "is the Open Source version of the famous DivX(R) codec and"
	echo "provides a better quality (and speed) than the commercial"
	echo "DivX(R) codec can offer."
	echo "Note: this script supports only Xvid 1.1.x or higher and"
	echo "MPlayer/MEncoder 1.0rc1 or higher!"
	echo "For more information, read the man page of xvidenc (man xvidenc)"
	echo ""
	echo "Options"
	echo "~~~~~~~"
	echo " -1p         Encode the DVD/video file is one pass mode"
	echo ""
	echo " -2p         Encode the DVD/video file in two pass mode"
	echo ""
	echo " -fq         Encode the DVD/video file in fixed quant mode"
	echo ""
	echo " -o          Load a options file generated by *this* script from"
	echo "             a previous encoding. This will skip *all* internal"
	echo "             options of the script and will directly execute"
	echo "             MEncoder with the options from the given file."
	echo "             NOTE: this is not recommended and is only ment for"
	echo "                   debugging purposes! The options file is only"
	echo "                   useful if you want to encode the *exact* same"
	echo "                   DVD or video file one more time, or if you have"
	echo "                   found a bug in this script and want to inspect"
	echo "                   where it went wrong in collecting and passing the"
	echo "                   options to MEncoder"
	echo ""
	echo " -v          Dispaly version of this script and exit"
	echo ""
	echo " -p help     Display quick help on available quality presets and how"
	echo "             to use them."
	echo ""
	echo " <passmode> -p <preset>"
	echo ""
	echo "             Use a predefined Xvid quality preset, where <passmode> is the"
	echo "             desired encoding mode (-1p or -2p or -fq) and <preset> is the"
	echo "             desired quality preset to use (see below). Presets are supported"
	echo "             by all encoding modes and do not work if you use the -o option."
	echo "             You can choose from 10 different presets:"
	echo ""
	echo "                     ulq -> Ultra Low Quality (ULQ) preset"
	echo "                     elq -> Extreme Low Quality (ELQ) preset"
	echo "                     vlq -> Very Low Quality (VLQ) preset"
	echo "                     lq --> Low Quality (LQ) preset"
	echo "                     mq --> Medium Quality (MQ) preset"
	echo "                     nq --> Normal Quality (NQ) preset"
	echo "                     hq --> High Quality (HQ) preset"
	echo "                     vhq -> Very High Quality (VHQ) preset (recommended)"
	echo "                     ehq -> Extreme High Quality (EHQ) preset (recommended)"
	echo "                     uhq -> Ultra High Quality (UHQ) preset (recommended)"
	echo ""
	echo "             Example of presets usage: xvidenc -2p -p ehq"
	echo ""
	echo "             The above example will encode the DVD or input video file"
	echo "             in 2-pass mode using the Extreme High Quality (EHQ) preset"
	echo ""
	echo " --help      Display this help screen and exit"
	echo ""
	echo "For bug reporting, suggestions, comments, questions or if this script"
	echo "was useful to you, send me an e-mail at <microchip@chello.be>"
	echo ""
	exit 0
	;;
	-p)
	# If user needs quick help/info on quality
	# presets, display it and exit
	case "$2" in
		help)
		echo ""
		echo "Available Quality Presets"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "ulq -> Ultra Low Quality (ULQ)"
		echo "elq -> Extreme Low Quality (ELQ)"
		echo "vlq -> Very Low Quality (VLQ)"
		echo "lq --> Low Quality (LQ)"
		echo "mq --> Medium Quality (MQ)"
		echo "nq --> Normal Quality (NQ)"
		echo "hq --> High Quality (HQ)"
		echo "vhq -> Very High Quality (VHQ) (recommended)"
		echo "ehq -> Extreme High Quality (EHQ) (recommended)"
		echo "uhq -> Ultra High Quality (UHQ) (recommended)"
		echo ""
		echo "Example of preset usage: xvidenc -2p -p hq"
		echo ""
		echo "Above example will encode the DVD or video file"
		echo "in 2-pass mode using the High Quality (HQ) preset"
		echo ""
		echo "Need more info? Use: xvidenc --help"
		echo "or 'man xvidenc'"
		echo ""
		exit 0
		;;
		"")
		echo "-> Option '-p' requires a parameter!"
		echo "-> Use '`basename $0` --help' for more info"
		exit 1
		;;
		*)
		echo "-> Unknown parameter ($2) for option '-p'"
		echo "-> Use '`basename $0` --help' for more info"
		exit 1
		;;
	esac
	;;
	-[1-2]p|-fq|-o) true ;;
	*)
	echo "-> Unknown option: '$1'"
	echo "-> Use `basename $0` --help for more info"
	exit 1
	;;
esac

# Check if user wants
# to use presets
if [ ! -z "$2" ]; then
	case "$2" in
		-p) true ;;
		*)
		echo "-> Unknown option: '$2'"
		echo "-> Use `basename $0` --help for more info"
		exit 1
		;;
	esac
	case "$3" in
		ulq|elq|vlq|lq|mq|nq|hq|vhq|ehq|uhq) true ;;
		"")
		echo "-> No preset specified!"
		echo "-> Use '`basename $0` -p help' for quick presets usage"
		exit 1
		;;
		*)
		echo "-> Unknown preset: '$3'"
		echo "-> Use '`basename $0` -p help' for available presets"
		exit 1
		;;
	esac
fi

###############################################
#               Requirements                  #
###############################################

for i in sed df grep awk stat tr wc dirname mkdir head tail cut; do
	if [ ! -x "`which $i 2>/dev/null`" ]; then
		echo "-> Checking for utility '$i'... FAILED!"
		exit 1
	fi
done

if [ ! -x "`which mencoder 2>/dev/null`" ]; then
	echo "-> Checking for MEncoder... FAILED!"
	exit 1
else
	echo "-> Checking for MEncoder... OK"
fi

if [ -z "`mencoder -ovc help 2>/dev/null | awk '{print $1}' | grep 'xvid'`" ]; then
	echo "-> Checking for Xvid support in MEncoder... FAILED!"
	echo "-> Download the Xvid 1.1.x library and recompile MPlayer"
	exit 1
else
	echo "-> Checking for Xvid support in MEncoder... OK"
fi

if [ ! -x "`which mplayer 2>/dev/null`" ]; then
	echo "-> Checking for MPlayer... FAILED!"
	exit 1
else
	echo "-> Checking for MPlayer... OK"
fi

# Make config dir
CONFIGDIR=$HOME/.xvidenc
test -d $CONFIGDIR || mkdir -p $CONFIGDIR
rm -f $CONFIGDIR/*

###############################################################
#    Functions shared by both DVD and video file encodings    #
###############################################################

# Deinterlace function
video_deinterlace_func() {
	printf "Is the $source Interlaced? [y/n]: "
	read int
	if [ "$int" = "y" -o "$int" = "Y" ]; then
		printf "Would you like to Preserve the Interlacing? [y/n]: "
		read preint
		if [ "$preint" = "y" -o "$preint" = "Y" ]; then
			# Turn on interlacing in Xvid
			deintfilter=
			interlaced=:interlacing
		elif [ "$preint" = "n" -o "$preint" = "N" -o -z "$preint" ]; then
			interlaced=:nointerlacing
			echo ""
			echo "Available Deinterlacing Filters"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "1 -> Linear Blend Deinterlacer"
			echo "2 -> Linear Interpolating Deinterlacer"
			echo "3 -> Cubic Interpolating Deinterlacer"
			echo "4 -> Median Deinterlacer"
			echo "5 -> FFmpeg Deinterlacer"
			echo "6 -> FIR Lowpass 5 Deinterlacer"
			echo ""
			printf "Select a Deinterlacing Filter [default is 6]: "
			read df
			case "$vtype" in
				file|FILE|File)
				case "$df" in
					1) deintfilter="lb," ;;
					2) deintfilter="li," ;;
					3) deintfilter="ci," ;;
					4) deintfilter="md," ;;
					5) deintfilter="fd," ;;
					6|"") deintfilter="l5," ;;
					*)
					echo "-> Unknown deinterlacing filter: '$df'"
					exit 1
					;;
				esac
				;;
				dvd|DVD|Dvd)
				case "$df" in
					1) deintfilter="pp=lb," ;;
					2) deintfilter="pp=li," ;;
					3) deintfilter="pp=ci," ;;
					4) deintfilter="pp=md," ;;
					5) deintfilter="pp=fd," ;;
					6|"") deintfilter="pp=l5," ;;
					*)
					echo "-> Unknown deinterlacing filter: '$df'"
					exit 1
					;;
				esac
				;;
			esac
		fi
	elif [ "$int" = "n" -o "$int" = "N" -o -z "$int" ]; then
		deintfilter=
		preint=
		interlaced=:nointerlacing
	fi
}

# Check to see if any video filters are used.
# If so, then add the '-vf' option to the
# MEncoder parameters
check_video_filters_func() {
	case "$res" in
		$GETRES|"")
		if [ ! -z "$deintfilter" -o ! -z "$deblock" -o ! -z "$denoise" -o ! -z "$cropping" ]; then
			filteropt="-vf"
		else
			filteropt=
		fi
		;;
		*)
		if [ ! -z "$deintfilter" -o ! -z "$deblock" -o ! -z "$denoise" -o ! -z "$cropping" -o "$scaling" = "1" ]; then
			filteropt="-vf"
		fi
		;;
	esac
}

# Video cropping
video_crop_func() {
	mplayer "$sourcetype" $device -identify -vo null -frames 1 2>/dev/null > $CONFIGDIR/xvidenc_cropdetect
	VLENGTH=$(grep "^ID_LENGTH" $CONFIGDIR/xvidenc_cropdetect | cut -f '2' -d '=' | cut -f '1' -d '.')
	GETCROP=$(mplayer "$sourcetype" $device -vf cropdetect -nosound -vo null -frames 15 -sstep $(($VLENGTH/15)) -nocache 2>/dev/null | tr '\r' '\n' | grep "crop=" | tail -1 | awk '{print $9}' | sed 's/crop=//g; s/).//g')
	rm -f $CONFIGDIR/xvidenc_cropdetect
}

# Informant function for displaying
# the selected quality preset
display_quality_preset_func() {
	case $1 in
		ulq) echo "-> Using \"Ultra Low Quality (ULQ)\" preset" ;;
		elq) echo "-> Using \"Extreme Low Quality (ELQ)\" preset" ;;
		vlq) echo "-> Using \"Very Low Quality (VLQ)\" preset" ;;
		lq) echo "-> Using \"Low Quality (LQ)\" preset" ;;
		mq) echo "-> Using \"Medium Quality (MQ)\" preset" ;;
		nq) echo "-> Using \"Normal Quality (NQ)\" preset" ;;
		hq) echo "-> Using \"High Quality (HQ)\" preset" ;;
		vhq) echo "-> Using \"Very High Quality (VHQ)\" preset" ;;
		ehq) echo "-> Using \"Extreme High Quality (EHQ)\" preset" ;;
		uhq) echo "-> Using \"Ultra High Quality (UHQ)\" preset" ;;
		*|"") false ;;
	esac
}

########################################################
#              DVD/video file settings                 #
########################################################

echo ""
echo "+==================================================================+"
echo "| Encode DVDs/video files to the Xvid 1.1.x format using MEncoder  |"
echo "|------------------------------------------------------------------|"
echo "|         xvidenc $version - (C) 2006, 2007 Grozdan Nikolov             |"
echo "+==================================================================+"
echo ""
echo ""

case "$1" in
	-o)
	printf "Provide the options file generated by this script: "
	read optsfile
	if [ -z "$(echo $optsfile | grep '^/')" ]; then
		echo "-> You have to provide the full path to the options file!"
		exit 1
	fi
	echo ""
	. "$optsfile"
	exit $?
	;;
esac

printf "Provide a name for the Output File [default is $HOME/Xvid.avi]: "
read outfile
if [ -z "$outfile" ]; then
	OUTPUT=$HOME/Xvid.avi
	test -e $OUTPUT && mv -f $OUTPUT $OUTPUT.old
else
	if [ -z "`echo \"$outfile\" | grep '^/'`" ]; then
		echo "-> You have to specify the full path!"
		exit 1
	fi
	if [ -z "`echo \"$outfile\" | grep '\.avi'`" ]; then
		echo "-> You have to use the '.avi' extension for the output file!"
		exit 1
	fi
	OUTPUT="$outfile"
	test -e "$OUTPUT" && mv -f "$OUTPUT" "$OUTPUT.old"
	test -d "$(dirname "$OUTPUT")" || mkdir -p "$(dirname "$OUTPUT")"
fi

# Check disk space left over in the
# output location and warn user.
# Since we don't know how big the final
# encode will be and if the user wants
# to split it and/or convert it to MKV,
# just play it safe and check if it's < 4 GB

DISKSPACE_OUTPUT="$(df -m "$(dirname "$OUTPUT")" | tail -1 | awk '{print $4}')"
if [ $DISKSPACE_OUTPUT -lt 4096 ]; then
	echo ""
	echo "Note that you are running out of disk space in"
	echo "the destination output directory!"
	echo ""
	echo "This could be a problem if you want to convert"
	echo "the final encode to Matroska or if you want to"
	echo "split it. It is recommended to free up some disk"
	echo "space before continuing with the encoding process"
	echo "if you intend to do some of the above tasks!"
	echo ""
	echo "Space left over in '$(dirname "$OUTPUT")': $DISKSPACE_OUTPUT MB"
	echo ""
fi

printf "Would you like to encode a Video File or a DVD? [FILE/DVD]: "
read vtype
case "$vtype" in
	file|FILE|File)
	source="video file"
	printf "Provide the Input Video File: "
	read infile
	if [ -z "`echo \"$infile\" | grep '^/'`" ]; then
		echo "-> You have to provide the full path to the video file!"
		exit 1
	fi
	if [ ! -f "$infile" ]; then
		echo "-> No such file! ($infile)"
		exit 1
	fi 
	sourcetype="$infile"
	if [ "$sourcetype" = "$OUTPUT" ]; then
		echo "-> You cannot use the same name for the input and output file!"
		exit 1
	fi
	video_deinterlace_func
	printf "Would you like to Deblock/Dering the Video File? [y/n]: "
	read db
	if [ "$db" = "y" -o "$db" = "Y" ]; then
		echo ""
		echo "Difference/Flatness Thresholds For Deblocking"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "Here you can specify the difference and flatness"
		echo "thresholds used by the deblocking filter."
		echo ""
		echo "Difference threshold -> higher value = more deblocking"
		echo "Flatness threshold ---> lower value = more deblocking"
		echo ""
		printf "Specify the Difference Threshold value [default is 70]: "
		read df_deblock
		if [ -z "$df_deblock" ]; then
			difference_deblock=70
		else
			difference_deblock=$df_deblock
		fi
		printf "Specify the Flatness Threshold value [default is 15]: "
		read fl_deblock
		if [ -z "$fl_deblock" ]; then
			flatness_deblock=15
		else
			flatness_deblock=$fl_deblock
		fi
		if [ ! -z "$deintfilter" ]; then
			deblock="pp=ha:$difference_deblock:$flatness_deblock/va/dr/"
		elif [ -z "$deintfilter" ]; then
			deblock="pp=ha:$difference_deblock:$flatness_deblock/va/dr,"
		fi
	elif [ "$db" = "n" -o "$db" = "N" -o -z "$db" -a -z "$deintfilter" ]; then
		deblock=
	elif [ "$db" = "n" -o "$db" = "N" -o -z "$db" -a ! -z "$deintfilter" ]; then
		deblock="pp="
	fi
	printf "Would you like to Crop the Video File? [y/n]: "
	read crop
	if [ "$crop" = "y" -o "$crop" = "Y" ]; then
		echo ""
		echo "-> Getting crop values with cropdetect..."
		video_crop_func
		if [ ! -z "$GETCROP" ]; then
			echo "-> Found crop values: $GETCROP"
		else
			echo ""
			echo "-> Failed to get crop values!"
			echo "-> You have to specify them yourself!"
			echo "-> The format is as follows: width:height:x:y"
			GETCROP="???"
		fi
		echo ""
		printf "Specify the crop values [default is $GETCROP]: "
		read cropvalues
		if [ -z "$cropvalues" -a "$GETCROP" = "???" ]; then
			echo "-> You have to specify the crop values!"
			exit 1
		fi
		if [ -z "$cropvalues" ]; then
			cropping="crop=$GETCROP,"
		else
			cropping="crop=$cropvalues,"
		fi
	elif [ "$crop" = "n" -o "$crop" = "N" -o -z "$crop" ]; then
		cropping=
		GETCROP=
	fi
	device=
	chapters=
	sid=
	spuaa=
	denoise=
	aid=
	;;
	dvd|DVD|Dvd)
	source=DVD
	echo ""
	if [ ! -x "`which lsdvd 2>/dev/null`" ]; then
		echo "-> Checking for lsdvd... FAILED!"
		exit 1
	else
		echo "-> Checking for lsdvd... OK"
	fi
	echo ""
	# Get available devices and
	# display them. Skip if nothing found
	if [ -r /proc/sys/dev/cdrom/info ]; then
		MEDIA_DEVICES=$(grep "drive name" /proc/sys/dev/cdrom/info | sed 's/drive name://g')
		if [ ! -z "$MEDIA_DEVICES" ]; then
			for i in $MEDIA_DEVICES; do
				echo "-> Found device: /dev/$i"
			done
		fi
	fi
	if [ -L /dev/dvd ]; then
		echo "-> Found symbolic link to DVD device: $(ls -l /dev/dvd | grep -o "/dev.*")"
	fi
	echo ""
	printf "Specify the DVD Device [default is /dev/dvd]: "
	read dev
	if [ -z "$dev" ]; then
		device="-dvd-device /dev/dvd"
	else
		if [ -z "`echo \"$dev\" | grep '^/'`" ]; then
			echo "-> You have to provide the full path to the DVD device!"
			exit 1
		fi
		device="-dvd-device $dev"
	fi
	if [ ! -e "`echo $device | awk '{print $2}'`" ]; then
		echo "-> DVD device does not exist! ($(echo $device | awk '{print $2}'))"
		exit 1
	fi
	# Before scanning the DVD with 'lsdvd' it has to be
	# unlocked or 'lsdvd' will fail to read it, so we
	# run mplayer here just to unlock it.
	echo ""
	echo "-> Unlocking the DVD disc..."
	mplayer dvd://1 $device -nosound -vo null -frames 1 >/dev/null 2>&1
	sleep 1
	echo "-> Scanning for longest DVD title..."
	ALLTITLES=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep "^Title" | awk '{print $1,$2,$3,$4}' | sed 's/,/ -/g' | cut -f '1' -d '.')
	DVDTITLE=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep "Longest" | awk '{print $3}' | sed 's/^0//')
	TITLE_LENGTH=$(lsdvd -t $DVDTITLE $(echo $device | awk '{print $2}') 2>/dev/null | grep "Length" | awk '{print $4}' | cut -f '1' -d '.')
	TOTAL_TITLES=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep "^Title" | sed 's/,//g' | awk 'END{print $2}' | sed 's/^0//')
	echo ""
	if [ -z "$DVDTITLE" ]; then
		echo "$ALLTITLES"
		echo ""
		echo "-> Titles On Disc: $TOTAL_TITLES"
		echo "-> Failed to detect longest DVD title!"
		echo "-> You have to specify it yourself!"
		DVDTITLE="???"
	else
		echo "$ALLTITLES"
		echo ""
		echo "-> Titles On Disc: $TOTAL_TITLES"
		echo "-> Longest Title:  $DVDTITLE - Title Length: $TITLE_LENGTH"
		
	fi
	echo ""
	printf "Specify the DVD title for encoding [default/longest is $DVDTITLE]: "
	read title
	if [ -z "$title" -a "$DVDTITLE" = "???" ]; then
		echo "-> You have to specify the DVD title for encoding!"
		exit 1
	fi
	if [ -z "$title" ]; then
		sourcetype=dvd://$DVDTITLE
	else
		sourcetype=dvd://$title
	fi
	printf "Would you like to encode only Specific Chapters? [y/n]: "
	read chap
	if [ "$chap" = "y" -o "$chap" = "Y" ]; then
		echo ""
		echo "-> Scanning for chapters in title $(echo $sourcetype | sed 's,dvd://,,')..."
		CHAPS=$(mplayer $sourcetype $device -nosound -vo null -frames 1 2>/dev/null | grep "chapters")
		if [ ! -z "$CHAPS" ]; then
			echo "-> $CHAPS"
		else
			echo "-> Could not detect any chapters in this DVD title!"
		fi
		echo ""
		printf "Which chapter(s) to encode from this DVD title? [example: 1-3]: "
		read ct
		if [ -z "$ct" ]; then
			chapters=
		else
			chapters="-chapter $ct"
		fi
	elif [ "$chap" = "n" -o "$chap" = "N" -o -z "$chap" ]; then
		chapters=
	fi
	printf "Would you like to include a Subtitle? [y/n]: "
	read sub
	if [ "$sub" = "y" -o "$sub" = "Y" ]; then
		echo ""
		echo "-> Scanning for subtitles..."
		mplayer $sourcetype $device -nosound -vo null -frames 1 2>/dev/null > $CONFIGDIR/xvidenc_subs
		SUBS=$(grep "^subtitle" $CONFIGDIR/xvidenc_subs)
		rm -f $CONFIGDIR/xvidenc_subs
		echo ""
		echo "Available Subtitles On Disc"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		if [ ! -z "$SUBS" ]; then
			echo "$SUBS"
		else
			echo "-> No subtitles on disc or failed to detect them!"
		fi
		echo ""
		printf "Specify the subtitle sid number: "
		read subnum
		if [ ! -z "`echo $subnum | grep '[a-zA-Z]'`" ]; then
			echo "-> You have to specify the subtitle number (sid), not the language code!"
			exit 1
		fi
		if [ -z "$subnum" ]; then
			sid=
		else
			sid="-sid $subnum"
		fi
		echo ""
		echo "Subtitle Anti-Aliasing Modes"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> None (fastest, very ugly)"
		echo "1 -> Approximate (broken?)"
		echo "2 -> Full (slow)"
		echo "3 -> Bilinear (fast and not too bad)"
		echo "4 -> Gaussian Blur (looks very good)"
		echo ""
		printf "Select the Subtitle Anti-Aliasing Mode [default is 4]: "
		read saam
		if [ -z "$saam" ]; then
			spuaa="-spuaa 4"
		else
			spuaa="-spuaa $saam"
		fi
	elif [ "$sub" = "n" -o "$sub" = "N" -o -z "$sub" ]; then
		sid=
		spuaa=
	fi
	video_deinterlace_func
	printf "Would you like to Denoise the DVD? [y/n]: "
	read dn
	if [ "$dn" = "y" -o "$dn" = "Y" ]; then
		echo ""
		echo "High-Quality Denoise Filter"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "This filter aims to reduce image noise producing"
		echo "smooth images and making still images really still"
		echo "This also should enhance compressibility"
		echo ""
		echo "There are 3 values you have to specify here"
		echo "The Spatial Luma Strength, the Spatial Chroma Strength"
		echo "and the Temporal Strength. The higher the values, the"
		echo "more filtering will be done"
		echo ""
		echo "The format is as follows: luma:chroma:temporal"
		echo ""
		printf "Specify the Denoise Filter Parameters [default is 2:1:2]: "
		read dfp
		if [ -z "$dfp" ]; then
			denoise="hqdn3d=2:1:2,"
		else
			denoise="hqdn3d=$dfp,"
		fi
	elif [ "$dn" = "n" -o "$dn" = "N" -o -z "$dn" ]; then
		denoise=
	fi
	printf "Would you like to Crop the DVD? [y/n]: "
	read crop
	if [ "$crop" = "y" -o "$crop" = "Y" ]; then
		echo ""
		echo "-> Getting crop values with cropdetect..."
		video_crop_func
		if [ ! -z "$GETCROP" ]; then
			echo "-> Found crop values: $GETCROP"
		else
			echo ""
			echo "-> Failed to get crop values!"
			echo "-> You have to specify them yourself!"
			echo "-> The format is as follows: width:height:x:y"
			GETCROP="???"
		fi
		echo ""
		printf "Specify the crop values [default is $GETCROP]: "
		read cropvalues
		if [ -z "$cropvalues" -a "$GETCROP" = "???" ]; then
			echo "-> You have to specify the crop values!"
			exit 1
		fi
		if [ -z "$cropvalues" ]; then
			cropping="crop=$GETCROP,"
		else
			cropping="crop=$cropvalues,"
		fi
	elif [ "$crop" = "n" -o "$crop" = "N" -o -z "$crop" ]; then
		cropping=
		GETCROP=
	fi
	deblock=
	;;
	*)
	echo "-> You have to specify the input source (file or dvd)!"
	exit 1
	;;
esac

# This can be a bit tricky if we
# deal with mixed Progressive NTSC/NTSC
# content
echo ""
echo "-> Detecting source FPS value..."
mencoder "$sourcetype" $device -ss 00:01:00 -nosound -ovc lavc -o /dev/null 2>/dev/null > $CONFIGDIR/xvidenc_fps_resolution & PID=$!; sleep 6; kill $PID;
case "$vtype" in
	FILE|file|File)
	GETFPS=$(grep "^VIDEO" $CONFIGDIR/xvidenc_fps_resolution | awk '{print $5}')
	;;
	DVD|dvd|Dvd)
	GETFPS=$(grep "^VIDEO" $CONFIGDIR/xvidenc_fps_resolution | awk '{print $6}')
	;;
esac

# For NTSC/Progressive Scan display a
# notification that MEncoder defaults
# to 25 FPS. We do not make the decision
# automatically here for the user by
# passing the detected FPS value to
# MEncoder, because we don't have a
# clue what the user wants. Maybe he
# wants to convert NTSC -> PAL or
# Progressive Scan -> PAL... who knows

case "$GETFPS" in
	25.000)
	echo "-> Detected $GETFPS FPS (PAL/SECAM - MEncoder format: 26000/1001)"
	;;
	29.970)
	echo "-> Detected $GETFPS FPS (NTSC - MEncoder format: 30000/1001)"
	echo ""
	echo "-> Note that MEncoder defaults to 25 FPS. If you want to keep"
	echo "   the NTSC frame rate, you have to set it by answering the"
	echo "   question below."
	;;
	23.976)
	echo "-> Detected $GETFPS FPS (Progressive NTSC - MEncoder format: 24000/1001)"
	echo ""
	echo "-> Note that MEncoder defaults to 25 FPS. If you want to keep"
	echo "   the NTSC frame rate, you have to set it by answering the"
	echo "   question below."
	;;
	"")
	echo "-> Failed to detect source FPS value!"
	echo ""
	echo "-> Note that MEncoder defaults to 25 FPS. For other frame rates"
	echo "   you have to set it manually by answering the question below."
	;;
	*)
	echo "-> Detected $GETFPS FPS (??? - ???)"
	echo ""
	echo "-> Note that MEncoder defaults to 25 FPS. For other frame rates"
	echo "   you have to set it manually by answering the question below."
	;;
esac
echo ""

printf "Would you like to set the Output Frame Rate value (FPS)? [y/n]: "
read outfps
if [ "$outfps" = "y" -o "$outfps" = "Y" ]; then
	echo ""
	echo "Frame Rate Configuration"
	echo "~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> PAL/SECAM (25 FPS - MEncoder format: 26000/1001)"
	echo "1 -> NTSC (29.970 FPS - MEncoder format: 30000/1001)"
	echo "2 -> Progressive NTSC (23.976 FPS - MEncoder format: 24000/1001)"
	echo "3 -> User Defined"
	echo ""
	printf "Select a Frame Rate format [default is 0]: "
	read frf
	case "$frf" in
		0|"") ofps="-ofps 26000/1001" ;;
		1) ofps="-ofps 30000/1001" ;;
		2) ofps="-ofps 24000/1001" ;;
		3)
		printf "Specify the Frame Rate value [default is 26000/1001]: "
		read frame_rate
		if [ -z `echo "$frame_rate" | grep '/'` ]; then
			echo "-> You have to use the MEncoder format (see above)!"
			exit 1
		fi
		# 'wc' increases the printed value by 1 !
		if [ $(($(echo "$frame_rate" | tr '/' ' ' | awk '{print $1}' | wc -m)-1)) != "5" ]; then
			echo "-> First value of the frame rate does not contain 5 digits!"
			exit 1
		fi
		if [ `echo "$frame_rate" | tr '/' ' ' | awk '{print $2}'` != "1001" ]; then
			echo "-> Second value of the frame rate must be 1001!"
			exit 1
		fi
		if [ -z "$frame_rate" ]; then
			ofps="-ofps 26000/1001"
		else
			ofps="-ofps $frame_rate"
		fi
		;;
		*) ofps= ;;
	esac
elif [ "$outfps" = "n" -o "$outfps" = "N" -o -z "$outfps" ]; then
	ofps=
	frf=
fi

# Get resolution from the source and ask
# user if he wants to keep it. If cropping
# was used, then default resolution value
# will be that of the visible area left
# over after the cropping. If no cropping
# was used, then default resolution value
# will be the original one from the source
echo ""
if [ ! -z "$GETCROP" ]; then
	echo "-> Detecting cropped resolution..."
	GETRES=$(echo $GETCROP | tr ':' ' ' | awk '{print $1,$2}' | sed 's/ /x/')
	if [ ! -z "$GETRES" ]; then
		echo "-> Resolution after cropping is: $GETRES"
	else
		echo ""
		echo "-> Failed to detect cropped resolution!"
		echo "-> You have to provide it yourself!"
		GETRES="???"
	fi
else
	echo "-> Detecting original resolution..."
	GETRES=$(grep "^VIDEO" $CONFIGDIR/xvidenc_fps_resolution | awk '{print $3}')
	if [ ! -z "$GETRES" ]; then
		echo "-> Original resolution is: $GETRES"
	else
		echo ""
		echo "-> Failed to detect original resolution!"
		echo "-> You have to provide it yourself!"
		GETRES="???"
	fi
fi
rm -f $CONFIGDIR/xvidenc_fps_resolution
echo ""
printf "Specify the Desired Resolution [default is $GETRES]: "
read res
if [ -z "$res" -a "$GETRES" = "???" ]; then
	echo "-> You have to specify the resolution!"
	exit 1
fi

# Bypass the scaling stuff if user
# decides to keep the original resolution
# of the source
case "$res" in
	$GETRES|"")
	check_video_filters_func
	scale=
	iss=
	scaler=
	ss_parameters=
	accurate_vertical=
	;;
	*)
	scaling=1
	check_video_filters_func
	scale="scale=$(echo $res | tr '[:alpha:]' ':')"
	
	# Deinterlacing parameters for
	# the scale filter
	if [ "$preint" = "y" -o "$preint" = "Y" ]; then
		iss=:1:0
	elif [ "$preint" = "n" -o "$preint" = "N" -o -z "$preint" ]; then
		iss=:0:0
	fi
	echo ""
	echo "Available Software Scalers"
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 --> Fast Bilinear"
	echo "1 --> Bilinear"
	echo "2 --> Bicubic"
	echo "3 --> Experimental"
	echo "4 --> Nearest Neighbor/Point"
	echo "5 --> Area Averaging"
	echo "6 --> Luma Bicubic/Chroma Bilinear"
	echo "7 --> Gaussian"
	echo "8 --> Sinc"
	echo "9 --> Lanczos"
	echo "10 -> Natural Bicubic Spline"
	echo ""
	printf "Select a Software Scaler [default is 10]: "
	read ss
	if [ -z "$ss" ]; then
		scaler="-sws 10"
	else
		scaler="-sws $ss"
	fi
	# software scaler tuning, only supported
	# by bicubic, bicubic spline, gaussian
	# and lanczos scalers
	case $(echo "$scaler" | awk '{print $2}') in
		2|10)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			echo "Software Scaler Parameters"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "Here you can tune some parameters of"
			echo "the Bicubic/Natural Bicubic Spline"
			echo "software scalers. The first value"
			echo "represents the amount of blurring while"
			echo "the second value represents the amount"
			echo "of ringing. The higher the values, the"
			echo "more blurring/ringing you'll get."
			echo ""
			echo "Format is as follows: blurring:ringing"
			echo "Below are some frequently used settings"
			echo ""
			echo "0.00:0.60 -> Default"
			echo "0.00:0.75 -> VirtualDub's \"Precise Bicubic\""
			echo "0.00:0.50 -> Catmull-Rom Spline"
			echo "0.33:0.33 -> Mitchell-Netravali Spline"
			echo "1.00:0.00 -> Cubic B-Spline"
			echo ""
			printf "Specify the Software Scaler Parameters [default is 0.00:0.60]: "
			read ssparam
			if [ -z "$ssparam" ]; then
				ss_parameters=
			else
				ss_parameters=":$ssparam"
			fi
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			ss_parameters=
		fi
		;;
		7)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			echo "Software Scaler Parameters"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "Here you can tune the sharpness of the"
			echo "Gaussian software scaler. Values are"
			echo "between 0 and 100. The higher the value"
			echo "the sharper the image will be"
			echo ""
			printf "Specify the Software Scaler Parameter [default is 0]: "
			read ssparam
			if [ -z "$ssparam" ]; then
				ss_parameters=
			else
				ss_parameters=":$ssparam"
			fi
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			ss_parameters=
		fi
		;;
		9)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			echo "Software Scaler Parameters"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "Here you can tune the filter length of"
			echo "the Lanczos software scaler. Values are"
			echo "between 1 and 10. The higher the value"
			echo "the sharper the image will be"
			echo ""
			printf "Specify the Software Scaler Parameter [default is 1]: "
			read ssparam
			if [ -z "$ssparam" ]; then
				ss_parameters=
			else
				ss_parameters=":$ssparam"
			fi
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			ss_parameters=
		fi
		;;
		*)
		ss_parameters=
		;;
	esac
	# accurate rounding for the
	# vertical software scaler
	printf "Would you like to use Accurate Rounding for the Vertical Scaler? [y/n]: "
	read accurate
	if [ "$accurate" = "y" -o "$accurate" = "Y" ]; then
		if [ ! -z "$ss_parameters" ]; then
			accurate_vertical="::0:1"
		else
			accurate_vertical="::::0:1"
		fi
	elif [ "$accurate" = "n" -o "$accurate" = "N" -o -z "$accurate" ]; then
		accurate_vertical=
	fi
	;;
esac

#################################################
#                Xvid Settings                  #
#################################################

echo ""
echo "+==================================+"
echo "| Xvid 1.1.x Encoder Configuration |"
echo "+==================================+"
echo ""
case "$1" in 
	-[1-2]p)
	# NOTE: in 2-pass mode, bitrate for the first
	# pass is ignored -> Xvid encodes first pass
	# in fixed quant mode
	printf "Specify the Desired Video Bitrate [default is 1200]: "
	read vb
	if [ -z "$vb" ]; then
		vbitrate="bitrate=1200"
	else
		vbitrate="bitrate=$vb"
	fi
	;;
	-fq)
	printf "Specify the Desired Quantizer [1.0-31.0 - default is 2]: "
	read quant
	if [ -z "$quant" ]; then
		vbitrate="fixed_quant=2"
	else
		vbitrate="fixed_quant=$quant"
	fi
	;;
esac

# Use a predefined Xvid preset.
# I'm strongly against video
# presets but a lot of people
# want them.... oh well, here
# we go :)
if [ ! -z "$2" ]; then
	echo ""
	echo "-> Skipping manual Xvid configuration"
	case "$3" in
		ulq)
		display_quality_preset_func $3
		me_quality=":me_quality=0"
		vhq=":vhq=0"
		max_bframes=":max_bframes=0"
		bvhq=":bvhq=0"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":notrellis"
		chroma_me=":nochroma_me"
		chroma_opt=":nochroma_opt"
		hq_ac=":nohq_ac"
		lumi_mask=":lumi_mask"
		advopts=":rc_reaction_delay_factor=15:rc_averaging_period=100"
		case "$1" in
			-2p)
			turbo=":turbo"
			;;
			*)
			turbo=
			;;
		esac
		;;
		elq)
		display_quality_preset_func $3
		me_quality=":me_quality=2"
		vhq=":vhq=0"
		max_bframes=":max_bframes=0"
		bvhq=":bvhq=0"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":notrellis"
		chroma_me=":nochroma_me"
		chroma_opt=":nochroma_opt"
		hq_ac=":nohq_ac"
		lumi_mask=":lumi_mask"
		advopts=":rc_reaction_delay_factor=15:rc_averaging_period=100"
		case "$1" in
			-2p)
			turbo=":turbo"
			;;
			*)
			turbo=
			;;
		esac
		;;
		vlq)
		display_quality_preset_func $3
		me_quality=":me_quality=4"
		vhq=":vhq=0"
		max_bframes=":max_bframes=0"
		bvhq=":bvhq=0"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":notrellis"
		chroma_me=":nochroma_me"
		chroma_opt=":nochroma_opt"
		hq_ac=":nohq_ac"
		lumi_mask=":lumi_mask"
		advopts=":rc_reaction_delay_factor=15:rc_averaging_period=100"
		case "$1" in
			-2p)
			turbo=":turbo"
			;;
			*)
			turbo=
			;;
		esac
		;;
		lq)
		display_quality_preset_func $3
		me_quality=":me_quality=6"
		vhq=":vhq=0"
		max_bframes=":max_bframes=0"
		bvhq=":bvhq=0"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":notrellis"
		chroma_me=":nochroma_me"
		chroma_opt=":nochroma_opt"
		hq_ac=":nohq_ac"
		lumi_mask=":nolumi_mask"
		advopts=":rc_reaction_delay_factor=5:rc_averaging_period=100"
		case "$1" in
			-2p)
			turbo=":turbo"
			;;
			*)
			turbo=
			;;
		esac
		;;
		mq)
		display_quality_preset_func $3
		me_quality=":me_quality=6"
		vhq=":vhq=1"
		max_bframes=":max_bframes=2"
		bvhq=":bvhq=0"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":trellis"
		chroma_me=":chroma_me"
		chroma_opt=":nochroma_opt"
		hq_ac=":nohq_ac"
		lumi_mask=":nolumi_mask"
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
		turbo=
		;;
		nq)
		display_quality_preset_func $3
		me_quality=":me_quality=6"
		vhq=":vhq=1"
		max_bframes=":max_bframes=2"
		bvhq=":bvhq=1"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":trellis"
		chroma_me=":chroma_me"
		chroma_opt=":nochroma_opt"
		hq_ac=":hq_ac"
		lumi_mask=":nolumi_mask"
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
		turbo=
		;;
		hq)
		display_quality_preset_func $3
		me_quality=":me_quality=6"
		vhq=":vhq=2"
		max_bframes=":max_bframes=2"
		bvhq=":bvhq=1"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":trellis"
		chroma_me=":chroma_me"
		chroma_opt=":chroma_opt"
		hq_ac=":hq_ac"
		lumi_mask=":nolumi_mask"
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
		turbo=
		;;
		vhq)
		display_quality_preset_func $3
		me_quality=":me_quality=6"
		vhq=":vhq=3"
		max_bframes=":max_bframes=2"
		bvhq=":bvhq=1"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":noqpel"
		gmc=":nogmc"
		trellis=":trellis"
		chroma_me=":chroma_me"
		chroma_opt=":chroma_opt"
		hq_ac=":hq_ac"
		lumi_mask=":nolumi_mask"
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
		turbo=
		;;
		ehq)
		display_quality_preset_func $3
		me_quality=":me_quality=6"
		vhq=":vhq=4"
		max_bframes=":max_bframes=2"
		bvhq=":bvhq=1"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":qpel"
		gmc=":nogmc"
		trellis=":trellis"
		chroma_me=":chroma_me"
		chroma_opt=":chroma_opt"
		hq_ac=":hq_ac"
		lumi_mask=":nolumi_mask"
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
		turbo=
		;;
		uhq)
		display_quality_preset_func $3
		me_quality=":me_quality=6"
		vhq=":vhq=4"
		max_bframes=":max_bframes=2"
		bvhq=":bvhq=1"
		packed=":nopacked"
		quant_type=":quant_type=h263"
		qpel=":qpel"
		gmc=":gmc"
		trellis=":trellis"
		chroma_me=":chroma_me"
		chroma_opt=":chroma_opt"
		hq_ac=":hq_ac"
		lumi_mask=":nolumi_mask"
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
		turbo=
		;;
	esac
	echo ""
else
	echo ""
	echo "Motion Estimation Quality"
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> Off"
	echo "1 -> Very Low"
	echo "2 -> Low"
	echo "3 -> Medium"
	echo "4 -> High"
	echo "5 -> Very High"
	echo "6 -> Ultra High"
	echo ""
	printf "Select the Motion Estimation Quality (me_quality) [default is 6]: "
	read meq
	if [ -z "$meq" ]; then
		me_quality=":me_quality=6"
	else
		me_quality=":me_quality=$meq"
	fi
	echo ""
	echo "Motion Search Algorithm (Frequency Domain)"
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> Off            -> Algorithm disabled"
	echo ""
	echo "1 -> Mode Decision  -> Inter/Intra Macroblocks"
	echo ""
	echo "2 -> Limited Search -> Inter/Intra Macroblocks"
	echo "                    -> Halfpel 16x16 Refine"
	echo "                    -> Quarterpel 16x16 Refine"
	echo ""
	echo "3 -> Medium Search  -> Inter/Intra Macroblocks"
	echo "                    -> Halfpel 16x16 & 8x8 Refine"
	echo "                    -> Quarterpel 16x16 & 8x8 Refine"
	echo "                    -> Prediction Check"
	echo ""
	echo "4 -> Wide Search    -> Inter/Intra Macroblocks"
	echo "                    -> Halfpel 16x16 & 8x8 Refine"
	echo "                    -> Quarterpel 16x16 & 8x8 Refine"
	echo "                    -> Prediction Check"
	echo "                    -> Extended Search"
	echo ""
	printf "Select the Motion Search Algorithm (vhq) [default is 1]: "
	read msa
	if [ -z "$msa" ]; then
		vhq=":vhq=1"
	else
		vhq=":vhq=$msa"
	fi
	# use appropriate keyframe interval
	# based on the output frame rate
	case "$frf" in
		0|"") keyvalue=250 ;;
		1) keyvalue=290 ;;
		2) keyvalue=230 ;;
		3) keyvalue="$(($(echo $ofps | awk '{print $2}')))0" ;;
		*) keyvalue=250 ;;
	esac
	printf "Specify the Keyframe Interval (max_key_interval) [default is $keyvalue]: "
	read keyint
	if [ -z "$keyint" ]; then
		max_key_interval=":max_key_interval=$keyvalue"
	else
		max_key_interval=":max_key_interval=$keyint"
	fi
	case "$1" in 
		-[1-2]p)
		printf "Would you like to set the Min/Max I/P/B Quantizers? [y/n]: "
		read setquant
		if [ "$setquant" = "y" -o "$setquant" = "Y" ]; then
			printf "Specify the Minimum I-Frame Quantizer [1-31 - default is 2]: "
			read miniquant
			if [ -z "$miniquant" ]; then
				min_iquant=2
			else
				min_iquant=$miniquant
			fi
			printf "Specify the Maximum I-Frame Quantizer [1-31 - default is 31]: "
			read maxiquant
			if [ -z "$maxiquant" ]; then
				max_iquant=31
			else
				max_iquant=$maxiquant
			fi
			printf "Specify the Minimum P-Frame Quantizer [1-31 - default is 2]: "
			read minpquant
			if [ -z "$minpquant" ]; then
				min_pquant=2
			else
				min_pquant=$minpquant
			fi
			printf "Specify the Maximum P-Frame Quantizer [1-31 - default is 31]: "
			read maxpquant
			if [ -z "$maxpquant" ]; then
				max_pquant=31
			else
				max_pquant=$maxpquant
			fi
			printf "Specify the Minimum B-Frame Quantizer [1-31 - default is 2]: "
			read minbquant
			if [ -z "$minbquant" ]; then
				min_bquant=2
			else
				min_bquant=$minbquant
			fi
			printf "Specify the Maximum B-Frame Quantizer [1-31 - default is 31]: "
			read maxbquant
			if [ -z "$maxbquant" ]; then
				max_bquant=31
			else
				max_bquant=$maxbquant
			fi
			quantizers=":min_iquant=$min_iquant:max_iquant=$max_iquant:min_pquant=$min_pquant:max_pquant=$max_pquant:min_bquant=$min_bquant:max_bquant=$max_bquant"
		elif [ "$setquant" = "n" -o "$setquant" = "N" -o -z "$setquant" ]; then
			quantizers=
		fi
		;;
		-fq) quantizers= ;;
	esac
	printf "Would you like to use a Specific Xvid Profile? [y/n]: "
	read specpro
	if [ "$specpro" = "y" -o "$specpro" = "Y" ]; then
		echo ""
		echo "Xvid Profiles"
		echo "~~~~~~~~~~~~~"
		echo "Note that these profiles should be used in"
		echo "conjunction with the appropriate ffourcc."
		echo "Generally DX50 is applicable, as some players"
		echo "do not recognize Xvid but most recognize DivX"
		echo ""
		echo "0 --> Unrestricted                      (max resolution: unrestricted)"
		echo "1 --> Simple Profile @ level 0          (max resolution: 176x144)"
		echo "2 --> Simple Profile @ level 1          (max resolution: 176x144)"
		echo "3 --> Simple Profile @ level 2          (max resolution: 352x288)"
		echo "4 --> Simple Profile @ level 3          (max resolution: 352x288)"
		echo "5 --> Advanced Simple Profile @ level 0 (max resolution: 176x144)"
		echo "6 --> Advanced Simple Profile @ level 1 (max resolution: 176x144)"
		echo "7 --> Advanced Simple Profile @ level 2 (max resolution: 352x288)"
		echo "8 --> Advanced Simple Profile @ level 3 (max resolution: 352x288)"
		echo "9 --> Advanced Simple Profile @ level 4 (max resolution: 352x576)"
		echo "10 -> Advanced Simple Profile @ level 5 (max resolution: 720x576)"
		echo "11 -> DXN Handheld profile              (max resolution: 176x144)"
		echo "12 -> DXN protable NTSC profile         (max resolution: 352x240)"
		echo "13 -> DXH portable PAL profile          (max resolution: 352x288)"
		echo "14 -> DXN home theater NTSC profile     (max resolution: 720x480)"
		echo "15 -> DXN home theater PAL profile      (max resolution: 720x576)"
		echo "16 -> DXN HDTV profile                  (max resolution: 1280x720)"
		echo ""
		printf "Which profile to use? [default is 0]: "
		read usepro
		case "$usepro" in
			0|"") profile= ;;
			1) profile=":profile=sp0" ;;
			2) profile=":profile=sp1" ;;
			3) profile=":profile=sp2" ;;
			4) profile=":profile=sp3" ;;
			5) profile=":profile=asp0" ;;
			6) profile=":profile=asp1" ;;
			7) profile=":profile=asp2" ;;
			8) profile=":profile=asp3" ;;
			9) profile=":profile=asp4" ;;
			10) profile=":profile=asp5" ;;
			11) profile=":profile=dxnhandheld" ;;
			12) profile=":profile=dxnportntsc" ;;
			13) profile=":profile=dxnportpal" ;;
			14) profile=":profile=dxnhtntsc" ;;
			15) profile=":profile=dxnhtpal" ;;
			16) profile=":profile=dxnhdtv" ;;
			*)
			echo "-> Unknown Xvid profile: '$usepro'"
			exit 1
			;;
		esac
		case "$usepro" in
			0|"")
			ffourcc=
			;;
			*)
			printf "Which ffourcc to use? [default is DX50]: "
			read useff
			if [ -z "$useff" ]; then
				ffourcc="-ffourcc DX50"
			else
				ffourcc="-ffourcc $useff"
			fi
			;;
		esac
	elif [ "$specpro" = "n" -o "$specpro" = "N" -o -z "$specpro" ]; then
		profile=
		ffourcc=
	fi
	printf "How many B-Frames to use between I/P-Frames (max_bframes)? [default is 2]: "
	read bframes
	if [ -z "$bframes" ]; then
		max_bframes=":max_bframes=2"
	else
		max_bframes=":max_bframes=$bframes"
	fi
	if [ "`echo $max_bframes | sed 's/:max_bframes=//'`" != "0" ]; then
		printf "Specify the B-Frames Threshold (bf_threshold) [-255 to 255 - default is 0]: "
		read bthreshold
		if [ -z "$bthreshold" ]; then
			bf_threshold=
		else
			bf_threshold=":bf_threshold=$bthreshold"
		fi
		printf "Would you like to use High-Quality B-Frames (bvhq)? [y/n]: "
		read hqbf
		if [ "$hqbf" = "y" -o "$hqbf" = "Y" ]; then
			bvhq=":bvhq=1"
		elif [ "$hqbf" = "n" -o "$hqbf" = "N" -o -z "$hqbf" ]; then
			bvhq=":bvhq=0"
		fi
	else
		bf_threshold=
		bvhq=":bvhq=0"
	fi
	case "$1" in
		-2p)
		printf "Would you like to use Turbo Mode for the First Pass? [y/n]: "
		read tmode
		if [ "$tmode" = "y" -o "$tmode" = "Y" ]; then
			turbo=":turbo"
		elif [ "$tmode" = "n" -o "$tmode" = "N" -o -z "$tmode" ]; then
			turbo=
		fi
		;;
		-1p|-fq) turbo= ;;
	esac
	printf "Would you like to use DivX5/6 Compatibility Mode - Packed Bitstream? [y/n]: "
	read divx
	if [ "$divx" = "y" -o "$divx" = "Y" ]; then
		packed=":packed"
	elif [ "$divx" = "n" -o "$divx" = "N" -o -z "$divx" ]; then
		packed=":nopacked"
	fi
	# MPEG quantizer are only recommended
	# for high bitrate encodes, when used
	# in low bitrate encodes they produce
	# more ringing
	printf "Would you like to use MPEG Quantizers instead of H.263? [y/n]: "
	read qtype
	if [ "$qtype" = "y" -o "$qtype" = "Y" ]; then
		quant_type=":quant_type=mpeg"
	elif [ "$qtype" = "n" -o "$qtype" = "N" -o -z "$qtype" ]; then
		quant_type=":quant_type=h263"
	fi
	# QPEL
	printf "Would you like to use Quarter Pel Motion Compensation (qpel)? [y/n]: "
	read qpmc
	if [ "$qpmc" = "y" -o "$qpmc" = "Y" ]; then
		qpel=":qpel"
	elif [ "$qpmc" = "n" -o "$qpmc" = "N" -o -z "$qpmc" ]; then
		qpel=":noqpel"
	fi
	# GMC
	printf "Would you like to use Global Motion Compensation (gmc)? [y/n]: "
	read gmcomp
	if [ "$gmcomp" = "y" -o "$gmcomp" = "Y" ]; then
		gmc=":gmc"
	elif [ "$gmcomp" = "n" -o "$gmcomp" = "N" -o -z "$gmcomp" ]; then
		gmc=":nogmc"
	fi
	printf "Would you like to use Trellis Searched Quantization (trellis)? [y/n]: "
	read trell
	if [ "$trell" = "y" -o "$trell" = "Y" ]; then
		trellis=":trellis"
	elif [ "$trell" = "n" -o "$trell" = "N" -o -z "$trell" ]; then
		trallis=":notrellis"
	fi
	printf "Would you like to use Chroma Motion Estimation (chroma_me)? [y/n]: "
	read cme
	if [ "$cme" = "y" -o "$cme" = "Y" ]; then
		chroma_me=":chroma_me"
	elif [ "$cme" = "n" -o "$cme" = "N" -o -z "$cme" ]; then
		chroma_me=":nochroma_me"
	fi
	printf "Would you like to use a Chroma Optimized Prefilter (chroma_opt)? [y/n]: "
	read cop
	if [ "$cop" = "y" -o "$cop" = "Y" ]; then
		chroma_opt=":chroma_opt"
	elif [ "$cop" = "n" -o "$cop" = "N" -o -z "$cop" ]; then
		chroma_opt=":nochroma_opt"
	fi
	printf "Would you like to use High-Quality AC Coefficient Prediction (hq_ac)? [y/n]: "
	read hqac
	if [ "$hqac" = "y" -o "$hqac" = "Y" ]; then
		hq_ac=":hq_ac"
	elif [ "$hqac" = "n" -o "$hqac" = "N" -o -z "$hqac" ]; then
		hq_ac=":nohq_ac"
	fi
	# Psychosensory
	printf "Would you like to use Luminance Masking (lumi_mask)? [y/n]: "
	read lumi
	if [ "$lumi" = "y" -o "$lumi" = "Y" ]; then
		lumi_mask=":lumi_mask"
	elif [ "$lumi" = "n" -o "$lumi" = "N" -o -z "$lumi" ]; then
		lumi_mask=":nolumi_mask"
	fi
	# For anime :)
	printf "Would you like to activate the Cartoon Mode (cartoon)? [y/n]: "
	read cm
	if [ "$cm" = "y" -o "$cm" = "Y" ]; then
		cartoon=":cartoon"
	elif [ "$cm" = "n" -o "$cm" = "N" -o -z "$cm" ]; then
		cartoon=":nocartoon"
	fi
	# Check for SMP/HyperThreading/Multicore
	# systems
	SMP=$(sed -n -e '/^processor/p' /proc/cpuinfo | wc -l)
	if [ "$SMP" != "1" ]; then
	printf "How many Threads to use (threads)? [default is 0]: "
		read threads
		if [ -z "$threads" ]; then
			use_threads=
		else
			use_threads=":threads=$threads"
		fi
	else
		use_threads=
	fi

	# Advanced options for experienced
	# users only
	printf "Would you like to set some Advanced Options? [y/n]: "
	read adv
	if [ "$adv" = "y" -o "$adv" = "Y" ]; then
		echo ""
		echo "+========================================+"
		echo "| Advanced Options For Experienced Users |"
		echo "+========================================+"
		echo ""
		printf "Specify the Ratecontrol Reaction Delay Factor [default is 0]: "
		read rrdf
		if [ -z "$rrdf" ]; then
			rc_reaction_delay_factor=":rc_reaction_delay_factor=0"
		else
			rc_reaction_delay_factor=":rc_reaction_delay_factor=$rrdf"
		fi
		printf "Specify the Ratecontrol Averaging Period [default is 100]: "
		read rap
		if [ -z "$rap" ]; then
			rc_averaging_period=":rc_averaging_period=100"
		else
			rc_averaging_period=":rc_averaging_period=$rap"
		fi
		printf "Specify the Ratecontrol Buffer Size [default is 100]: "
		read rcbuf
		if [ -z "$rcbuf" ]; then
			rc_buffer=
		else
			rc_buffer=":rc_buffer=$rcbuf"
		fi
		printf "Specify the B-Frame Quantizer Ratio [default is 150]: "
		read bfr
		if [ -z "$bfr" ]; then
			bquant_ratio=
		else
			bquant_ratio=":bquant_ratio=$bfr"
		fi
		printf "Specify the B-Frame Quantizer Offset [default is 100]: "
		read bo
		if [ -z "$bo" ]; then
			bquant_offset=
		else
			bquant_offset=":bquant_offset=$bo"
		fi
		case "$1" in
			-2p)
			printf "Specify the Keyframe Boost Threshold [0-1000 - default is 0]: "
			read kbt
			if [ -z "$kbt" ]; then
				keyframe_boost=
			else
				keyframe_boost=":keyframe_boost=$kbt"
			fi
			printf "Specify the Keyframe Threshold [default is 0]: "
			read kt
			if [ -z "$kt" ]; then
				kfthreshold=
			else
				kfthreshold=":kfthreshold=$kt"
			fi
			printf "Specify the Keyframe Reduction [0-100 - default is 30]: "
			read kr
			if [ -z "$kr" ]; then
				kfreduction=
			else
				kfreduction=":kfreduction=$kr"
			fi
			printf "Specify the Low Curve Compression [0-100 - default is 0]: "
			read lcc
			if [ -z "$lcc" ]; then
				curve_compression_low=
			else
				curve_compression_low=":curve_compression_low=$lcc"
			fi
			printf "Specify the High Curve Compression [0-100 - default is 0]: "
			read hcc
			if [ -z "$hcc" ]; then
				curve_compression_high=
			else
				curve_compression_high=":curve_compression_high=$hcc"
			fi
			printf "Specify the Overflow Control Strength [0-100 - default is 5]: "
			read ocs
			if [ -z "$ocs" ]; then
				overflow_control_strength=
			else
				overflow_control_strength=":overflow_control_strength=$ocs"
			fi
			printf "Specify the Maximum Overflow Improvement [0-100 - default is 5]: "
			read maxoi
			if [ -z "$maxoi" ]; then
			max_overflow_improvement=
			else
				max_overflow_improvement=":max_overflow_improvement=$maxoi"
			fi
			printf "Specify the Maximum Overflow Degradation [0-100 - default is 5]: "
			read maxod
			if [ -z "$maxod" ]; then
				max_overflow_degradation=
			else
				max_overflow_degradation=":max_overflow_degradation=$maxod"
			fi
			;;
			-1p|-fq)
			keyframe_boost=
			kfthreshold=
			kfreduction=
			curve_compression_low=
			curve_compression_high=
			overflow_control_strength=
			max_overflow_improvement=
			max_overflow_degradation=
			;;
		esac
		printf "Would you like to load custom Intra/Inter Matrix files? [y/n]: "
		read iim
		if [ "$iim" = "y" -o "$iim" = "Y" ]; then
			# When using intra/inter matrices
			# MPEG quantizers must be used!
			quant_type=":quant_type=mpeg"
			printf "Provide the Intra Matrix file: "
			read intrafile
			if [ -z "`echo \"$intrafile\" | grep '^/'`" ]; then
				echo "-> You have to provide the full path to the file!"
				exit 1
			fi
			if [ ! -f "$intrafile" ]; then
				echo "-> No such file! ($intrafile)"
				exit 1
			fi
			intramatrix=":quant_intra_matrix=$intrafile"
			printf "Provide the Inter Matrix file: "
			read interfile
			if [ -z "`echo \"$interfile\" | grep '^/'`" ]; then
				echo "-> You have to provide the full path to the file!"
				exit 1
			fi
			if [ ! -f "$interfile" ]; then
				echo "-> No such file! ($interfile)"
				exit 1
			fi
			intermatrix=":quant_inter_matrix=$interfile"
		elif [ "$iim" = "n" -o "$iim" = "N" -o -z "$iim" ]; then
			intramatrix=
			intermatrix=
		fi
		advopts="$rc_reaction_delay_factor$rc_averaging_period$rc_buffer$bquant_ratio$bquant_offset$keyframe_boost$kfthreshold$kfreduction$curve_compression_low$curve_compression_high$overflow_control_strength$max_overflow_improvement$max_overflow_degradation$intramatrix$intermatrix"
	elif [ "$adv" = "n" -o "$adv" = "N" -o -z "$adv" ]; then
		# use script's default
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
	fi
fi

# Statistics
printf "Display PSNR Statistics after encoding? [y/n]: "
read statistics
if [ "$statistics" = "y" -o "$statistics" = "Y" ]; then
	stats=":psnr"
elif [ "$statistics" = "n" -o "$statistics" = "N" -o -z "$statistics" ]; then
	stats=
fi

# Set priority (nice value) of the whole
# encoding process
printf "Would you like to set the encoder priority level? [y/n]: "
read priolevel
if [ "$priolevel" = "y" -o "$priolevel" = "Y" ]; then
	echo ""
	echo "Encoder Priority Level"
	echo "~~~~~~~~~~~~~~~~~~~~~~"
	if [ $UID != 0 ]; then
		echo "You can adjust the encoder priority level so that"
		echo "you can get a more responsive system even with the"
		echo "encoding process going in the background. This can"
		echo "be achieved by adjusting the 'nice' value of the"
		echo "encoder. Because you are running as an unprivileged"
		echo "user and not as root, you can only use 'nice' values"
		echo "between 0 and 19, where 0 stands for 'normal priority'"
		echo "and 19 for 'the lowest possible priority'. The higher"
		echo "the 'nice' value is, the lower the encoder priority"
		echo "will be, thus making the overall system more responsive"
		echo "to other actions during the encoding process."
		echo ""
		printf "Specify the encoder priority level [0-19 - default is 0]: "
		read nice_value
		case "$nice_value" in
			[0-9]|1[0-9])
			priority_level="nice -n $nice_value"
			;;
			-[1-9]|-1[0-9]|-20)
			echo ""
			echo "-> You do not have the privilege to set a negative 'nice' value!"
			echo "-> Continuing with default 'nice' value of 0"
			priority_level="nice -n 0"
			;;
			*|"")
			priority_level="nice -n 0"
			;;
		esac
	else
		echo "Because you are using this script as root user, you"
		echo "can trade encoder priority for system responsiveness"
		echo "and the other way around. For the root user, all 'nice'"
		echo "values are allowed (from -20 up to 19). The lower the"
		echo "'nice' value is, the higher the priority level of the"
		echo "encoder will be, thus making the overall system less"
		echo "responsive to other actions during the encoding process."
		echo "The higher the 'nice' value is, the more responsive your"
		echo "system will be."
		echo ""
		printf "Specify the encoder priority level [-20-19 - default is 0]: "
		read nice_value
		case "$nice_value" in
			-[1-9]|-1[0-9]|-20|[0-9]|1[0-9])
			priority_level="nice -n $nice_value"
			;;
			*|"")
			priority_level="nice -n 0"
			;;
		esac
	fi
elif [ "$priolevel" = "n" -o "$priolevel" = "N" -o -z "$priolevel" ]; then
	priority_level="nice -n 0"
fi

##################################################
#               Audio Settings                   #
##################################################

# Resample function
audio_resample_func() {
	printf "Would you like to Resample the Audio? [y/n]: "
	read rsmp
	if [ "$rsmp" = "y" -o "$rsmp" = "Y" ]; then
		printf "Specify the new Sample Rate in Hertz [default is 44100]: "
		read hz
		case "$audiocodec" in
			MP[2-3]|mp[2-3]|PCM|pcm|AAC|aac|ADPCM|adpcm)
			case "$hz" in
				8000|11025|12000|16000|22050|24000|32000|44100|48000|"") true ;;
				*)
				echo "-> '$hz' is not a valid sample rate!"
				echo "-> Valid rates are: 8000|11025|12000|16000|22050|24000|32000|44100|48000"
				exit 1
				;;
			esac
			;;
			AC3|ac3)
			# AC3 supports only these
			# sampling rates!
			case "$hz" in
				32000|44100|48000|"") true ;;
				*)
				echo "-> '$hz' is not a valid AC3 sample rate!"
				echo "-> Valid rates are: 32000|44100|48000"
				exit 1
				;;
			esac
			;;
		esac
		if [ -z "$hz" ]; then
			# Try to use floating point processing
			# (if possible) with exact frequency
			# conversion for best quality
			# Note: ARM doesn't have an FPU !!!
			case `uname -m` in
				i?86|x86_64|ia64|k[5-6]|k6_2|k6_3|k6-[2-3]|pentium*|celeron*|athlon*|opteron*|duron*|sempron*|turion*|phenom*|itanium*|xeon*|core*|i586_i686|i586-i686|ppc*|macppc|sh[3-4]|sun4u|sparc*|alpha*|mips*|s390x|parisc*|hppa*|9000*) 
				resample="resample=44100:0:2"; srate="-srate 44100" ;;
				*)
				resample="resample=44100:0:1"; srate="-srate 44100" ;;
			esac
		else
			case `uname -m` in
				i?86|x86_64|ia64|k[5-6]|k6_2|k6_3|k6-[2-3]|pentium*|celeron*|athlon*|opteron*|duron*|sempron*|turion*|phenom*|itanium*|xeon*|core*|i586_i686|i586-i686|ppc*|macppc|sh[3-4]|sun4u|sparc*|alpha*|mips*|s390x|parisc*|hppa*|9000*) 
				resample="resample=$hz:0:2"; srate="-srate $hz" ;;
				*)
				resample="resample=$hz:0:1"; srate="-srate $hz" ;;
			esac
		fi
	elif [ "$rsmp" = "n" -o "$rsmp" = "N" -o -z "$rsmp" ]; then
		resample=
		srate=
	fi
}

# Volume normalizing function.
# Must be called after the
# audio resample function
audio_volnorm_func() {
	case "$audiocodec" in
		AC3|ac3)
		# Note that the 'volnorm' variable holds
		# the volnorm, the resample and the surround filters!!!
		printf "Would you like to Normalize the Audio Volume? [y/n]: "
		read norm
		if [ "$norm" = "y" -o "$norm" = "Y" ]; then
			if [ ! -z "$resample" -a -z "$surround" ]; then
				volnorm="-af volnorm=2,$resample"
			elif [ -z "$resample" -a ! -z "$surround" ]; then
				volnorm="-af volnorm=2,`echo $surround | sed 's/,//'`"
			elif [ -z "$resample" -a -z "$surround" ]; then
				volnorm="-af volnorm=2"
			fi
		elif [ "$norm" = "n" -o "$norm" = "N" -o -z "$norm" -a -z "$resample" -a -z "$surround" ]; then
			volnorm=
		elif [ "$norm" = "n" -o "$norm" = "N" -o -z "$norm" -a ! -z "$resample" -a -z "$surround" ]; then
			volnorm="-af $resample"
		elif [ "$norm" = "n" -o "$norm" = "N" -o -z "$norm" -a -z "$resample" -a ! -z "$surround" ]; then
			volnorm="-af `echo $surround | sed 's/,//'`"
		elif [ "$norm" = "n" -o "$norm" = "N" -o -z "$norm" -a ! -z "$resample" -a ! -z "$surround" ]; then
			volnorm="-af $surround$resample"
		fi
		;;
		MP2|mp2|AAC|aac|PCM|pcm|ADPCM|adpcm)
		printf "Would you like to Normalize the Audio Volume? [y/n]: "
		read norm
		if [ "$norm" = "y" -o "$norm" = "Y" ]; then
			if [ ! -z "$resample" ]; then
				volnorm="-af volnorm=2,"
			elif [ -z "$resample" ]; then
				volnorm="-af volnorm=2"
			fi
		elif [ "$norm" = "n" -o "$norm" = "N" -o -z "$norm" -a ! -z "$resample" ]; then
			volnorm="-af "
		elif [ "$norm" = "n" -o "$norm" = "N" -o -z "$norm" -a -z "$resample" ]; then
			volnorm=
		fi
		;;
	esac
}

# Check availability of the
# selected audio codec in
# MEncoder
check_audio_codec_func() {
	case "$audiocodec" in
		mp2|MP2|ac3|AC3|adpcm|ADPCM)
		if [ -z "`mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc'`" ]; then
			echo "-> MEncoder does not support the libavcodecs audio collection!"
			echo "-> Download the official MPlayer package or use a different"
			echo "   audio codec."
			exit 1
		fi
		;;
		mp3|MP3|"")
		if [ -z "`mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame'`" ]; then
			echo "-> MEncoder does not support MP3 audio encoding!"
			echo "-> Download LAME and recompile MPlayer or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
		aac|AAC)
		if [ -z "`mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'faac'`" ]; then
			echo "-> MEncoder does not support AAC audio encoding!"
			echo "-> Download 'faac' and recompile MPlayer or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
		pcm|PCM)
		if [ -z "`mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm'`" ]; then
			echo "-> MEncoder does not support PCM audio encoding!"
			echo "-> Download the official MPlayer package or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
		copy|COPY)
		if [ -z "`mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'copy'`" ]; then
			echo "-> MEncoder does not support audio stream copy!"
			echo "-> Download the official MPlayer package or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
	esac
}

echo ""
echo "+=====================+"
echo "| Audio Configuration |"
echo "+=====================+"
echo ""
case "$vtype" in
	dvd|DVD|Dvd)
	echo "-> Scanning for audio channels..."
	mplayer $sourcetype $device -nosound -vo null -frames 1 2>/dev/null > $CONFIGDIR/xvidenc_audiostreams
	STREAMS=$(grep "^audio stream" $CONFIGDIR/xvidenc_audiostreams)
	rm -f $CONFIGDIR/xvidenc_audiostreams
	echo ""
	if [ ! -z "$STREAMS" ]; then
		echo "$STREAMS"
	else
		echo "-> Could not detect any audio streams!"
	fi
	echo ""
	printf "Specify the DVD Audio Channel (aid) [default is 128]: "
	read dac
	if [ ! -z "`echo $dac | grep '[a-zA-Z]'`" ]; then
		echo "-> You have to specify the 'aid' number, not the language code!"
		exit 1
	fi
	if [ -z "$dac" ]; then
		aid="-aid 128"
	else
		aid="-aid $dac"
	fi
	;;
	file|FILE|File)
	# If input source contains more than
	# one audio stream (like MPEG TS or
	# Matroska files), then offer the
	# user a option to select the channel
	# he/she wants. If input source has
	# only 1 or none at all audio streams
	# then skip the channel selection
	echo "-> Scanning for audio channels..."
	mplayer "$sourcetype" -nosound -vo null -identify -frames 1 2>/dev/null > $CONFIGDIR/xvidenc_audiostreams
	if [ $(grep "^ID_AUDIO_ID" $CONFIGDIR/xvidenc_audiostreams | wc -l) -le 1 ]; then
		aid=
		echo "-> Zero or one audio channel found"
		echo "-> Skipping channel selection"
		echo ""
	else
		echo ""
		for i in $(grep "^ID_AUDIO_ID" $CONFIGDIR/xvidenc_audiostreams); do
			echo "Audio channel: $(echo $i | sed 's/ID_AUDIO_ID=//g')"
		done
		echo ""
		AID=$(grep "^ID_AUDIO_ID" $CONFIGDIR/xvidenc_audiostreams | sed 's/ID_AUDIO_ID=//g')
		printf "Specify the Audio Channel number [default is $(echo $AID | awk '{print $1}')]: "
		read dac
		if [ -z "$dac" ]; then
			aid="-aid $(echo $AID | awk '{print $1}')"
		else
			aid="-aid $dac"
		fi
	fi
	rm -f $CONFIGDIR/xvidenc_audiostreams
	;;
esac

printf "Specify the Audio Codec [MP2/MP3/AC3/AAC/PCM/ADPCM/COPY/NOSOUND - default is MP3]: "
read audiocodec
case "$audiocodec" in
	MP2|mp2)
	check_audio_codec_func
	printf "Specify the Audio Bitrate [default is 128]: "
	read ab
	case "$ab" in
		32|40|48|56|64|80|96|112|128|160|192|224|256|320|"") true ;;
		*)
		echo "-> '$ab' is not a valid MP2 audio bitrate!"
		echo "-> Valid bitrates are: 32|40|48|56|64|80|96|112|128|160|192|224|256|320"
		exit 1
		;;
	esac
	if [ -z "$ab" ]; then
		abitrate=128
	else
		abitrate=$ab
	fi
	audio_resample_func
	audio_volnorm_func
	acodec="-oac lavc -lavcopts acodec=mp2:abitrate=$abitrate"
	afilters="$volnorm$resample $srate"
	channels=
	ac3drc=
	;;
	MP3|mp3|"")
	# The volume normalizing filter is not
	# used when encoding to MP3 audio 'cause
	# LAME provides an audio input gain option
	# where user can set the amount of gain
	# he wants
	check_audio_codec_func
	printf "Specify the MP3 Audio Encoding Mode [ABR/CBR/VBR - default is ABR]: "
	read mp3mode
	case "$mp3mode" in
		ABR|abr|a*|A*|"")
		printf "Specify the Average Audio Bitrate [default is 140]: "
		read ab
		if [ -z "$ab" ]; then
			abitrate="abr:br=140"
		else
			abitrate="abr:br=$ab"
		fi
		;;
		CBR|cbr|C*|c*)
		printf "Specify the Audio Bitrate [default is 128]: "
		read ab
		case "$ab" in
			32|40|48|56|64|80|96|112|128|160|192|224|256|320|"") true ;;
			*)
			echo "-> '$ab' is not a valid CBR bitrate!"
			echo "-> Valid bitrates are: 32|40|48|56|64|80|96|112|128|160|192|224|256|320"
			exit 1
			;;
		esac
		if [ -z "$ab" ]; then
			abitrate="cbr:br=128"
		else
			abitrate="cbr:br=$ab"
		fi
		;;
		VBR|vbr|V*|v*)
		printf "Specify the Desired Quality [0-9 - default is 3]: "
		read ab
		if [ -z "$ab" ]; then
			abitrate="q=3"
		else
			abitrate="q=$ab"
		fi
		;;
		*)
		echo "-> Unknown MP3 encoding mode: '$mp3mode'"
		exit 1
		;;
	esac
	printf "Specify the Algorithmic Quality [0-9 - default is 4]: "
	read aq
	if [ -z "$aq" ]; then
		aquality=":aq=4"
	else
		aquality=":aq=$aq"
	fi
	printf "Specify the Audio Input Gain [0.0-10.0 - default is 1.5]: "
	read aig
	if [ -z "$aig" ]; then
		again=":vol=1.5"
	else
		again=":vol=$aig"
	fi
	echo ""
	echo "MP3 Channel Modes"
	echo "~~~~~~~~~~~~~~~~~"
	echo "0 -> Stereo"
	echo "1 -> Joint-Stereo"
	echo "2 -> Dual Channel"
	echo "3 -> Mono"
	echo ""
	printf "Select the MP3 Channel Mode [default is 1]: "
	read mp3chan
	case "$mp3chan" in
		0) mp3channel=":mode=0" ;;
		1|"") mp3channel=":mode=1" ;;
		2) mp3channel=":mode=2" ;;
		3) mp3channel=":mode=3" ;;
		*)
		echo "-> Unknown MP3 channel mode: '$mp3chan'"
		exit 1
		;;
	esac
	printf "Specify the MP3 Highpass Frequency in Hertz [default is 0 (auto)]: "
	read mp3highpass
	if [ -z "$mp3highpass" ]; then
		highpassfreq=":highpassfreq=0"
	else
		highpassfreq=":highpassfreq=$mp3highpass"
	fi
	printf "Specify the MP3 Lowpass Frequency in Hertz [default is 0 (auto)]: "
	read mp3lowpass
	if [ -z "$mp3lowpass" ]; then
		lowpassfreq=":lowpassfreq=0"
	else
		lowpassfreq=":lowpassfreq=$mp3lowpass"
	fi
	audio_resample_func
	acodec="-oac mp3lame -lameopts $abitrate$aquality$again$mp3channel$highpassfreq$lowpassfreq"
	channels=
	ac3drc=
	if [ ! -z "$resample" ]; then
		afilters="-af $resample $srate"
	else
		afilters=
	fi
	;;
	AC3|ac3)
	check_audio_codec_func
	printf "Specify the AC3 Audio Bitrate [default is 192]: "
	read ab
	case "$ab" in
		32|40|48|56|64|80|96|112|128|160|192|224|256|320|384|448|512|576|640|"") true ;;
		*)
		echo "-> '$ab' is not a valid AC3 audio bitrate!"
		echo "-> Valid bitrates are: 32|40|48|56|64|80|96|112|128|160"
		echo "                       192|224|256|320|448|512|576|640"
		exit 1
		;;
	esac
	if [ -z "$ab" ]; then
		abitrate=192
	else
		abitrate=$ab
	fi
	printf "Would you like to use/have more than 2 Audio Channels? [y/n]: "
	read chan
	if [ "$chan" = "y" -o "$chan" = "Y" ]; then
		echo ""
		echo "AC3 Channels Configuration"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "2 -> Dolby AC3 Stereo      (2 front)"
		echo "4 -> Dolby AC3 Quadro 4.0  (2 front + 2 rear)"
		echo "6 -> Dolby AC3 Digital 5.1 (2 front + 2 rear + 1 center + LFE)"
		echo ""
		printf "How much channels to add/use? [default is 2]: "
		read uc
		case "$uc" in
			2|4|6) true ;;
			*)
			echo "-> Unknown channels option: '$uc'"
			exit 1
			;;
		esac
		if [ -z "$uc" ]; then
			channels="-channels 2"
		else
			channels="-channels $uc"
		fi
		# Ask user if he wants to add surround effect
		# to the encoded file -> only for file encodings
		# as most video files come with stereo channels
		# which contain matrix encoded data -> won't be as
		# good as real surround when downmixing from 5.1 to
		# 4 channels though
		case "$uc" in
			4)
			case "$vtype" in
				file|FILE|File)
				printf "Would you like to add a Surround Effect? [y/n]: "
				read sur
				if [ "$sur" = "y" -o "$sur" = "Y" ]; then
					printf "Specify the Delay Time for the Rear Speakers in ms [default is 20]: "
					read ms
					if [ -z "$ms" ]; then
						surround="surround=20,"
					else
						surround="surround=$ms,"
					fi
				elif [ "$sur" = "n" -o "$sur" = "N" -o -z "$sur" ]; then
					surround=
				fi
				;;
				dvd|DVD|Dvd)
				surround=
				;;
			esac
			;;
			2|6)
			surround=
			;;
		esac
	elif [ "$chan" = "n" -o "$chan" = "N" -o -z "$chan" ]; then
		channels=
		surround=
	fi
	printf "Specify the AC3 Dynamic Range Compression [0.0-1 - default is 1 (full)]: "
	read drc
	if [ -z "$drc" ]; then
		ac3drc="-a52drc 1"
	else
		ac3drc="-a52drc $drc"
	fi
	audio_resample_func
	audio_volnorm_func
	acodec="-oac lavc -lavcopts acodec=ac3:abitrate=$abitrate"
	afilters="$volnorm $srate"
	;;
	AAC|aac)
	check_audio_codec_func
	printf "Specify the AAC Audio Encoding Mode [ABR/VBR - default is ABR]: "
	read aacmode
	case "$aacmode" in
		ABR|abr|A*|a*|"")
		printf "Specify the Average Audio Bitrate [default is 140]: "
		read abitrate
		if [ -z "$abitrate" ]; then
			br="br=140"
		else
			br="br=$abitrate"
		fi
		;;
		VBR|vbr|V*|v*)
		printf "Specify the Audio Quality [1-1000 - default is 200]: "
		read abitrate
		if [ -z "$abitrate" ]; then
			br="quality=200"
		else
			br="quality=$abitrate"
		fi
		;;
		*)
		echo "-> Unknown AAC audio encoding mode: '$aacmode'"
		exit 1
		;;
	esac
	printf "Enable Temporal Noise Shaping? [y/n]: "
	read tempns
	if [ "$tempns" = "y" -o "$tempns" = "Y" ]; then
		tns=":tns"
	elif [ "$tempns" = "n" -o "$tempns" = "N" -o -z "$tempns" ]; then
		tns=
	fi
	audio_resample_func
	audio_volnorm_func
	acodec="-oac faac -faacopts $br$tns"
	afilters="$volnorm$resample $srate"
	channels=
	ac3drc=
	;;
	PCM|pcm)
	check_audio_codec_func
	audio_resample_func
	audio_volnorm_func
	acodec="-oac pcm"
	afilters="$volnorm$resample $srate"
	channels=
	ac3drc=
	;;
	ADPCM|adpcm)
	check_audio_codec_func
	audio_resample_func
	audio_volnorm_func
	acodec="-oac lavc -lavcopts acodec=adpcm_ima_wav"
	afilters="$volnorm$resample $srate"
	channels=
	ac3drc=
	;;
	COPY|copy)
	check_audio_codec_func
	acodec="-oac copy"
	afilters=
	channels=
	;;
	NOSOUND|nosound)
	acodec="-nosound"
	afilters=
	channels=
	ac3drc=
	;;
	*)
	echo "-> Unknown audio codec: '$audiocodec'"
	exit 1
	;;
esac

echo ""
echo "+=============================+"
echo "| Miscellaneous Configuration |"
echo "+=============================+"
echo ""

# Ask user if he wants to calculate the video
# bitrate based on target file size, audio bitrate
# and video source length. This only works for
# 1- and 2-pass modes so skip it for fixed quant.
# At the moment, there's only support for lossy
# audio codecs. This actually shouldn't be here
# (it should be in the video options) but since
# this script is linear and processes video options
# before the audio options, there's no way how to
# know which audio codec and bitrate the user has
# chosen.

# According to LAME's documentation, these
# are the corresponding quality values -> bitrates
#
# q=0 -> ~240 kbps
# q=1 -> ~210 kbps
# q=2 -> ~190 kbps
# q=3 -> ~175 kbps
# q=4 -> ~165 kbps
# q=5 -> ~130 kbps
# q=6 -> ~115 kbps
# q=7 -> ~100 kbps
# q=8 -> ~85 kbps
# q=9 -> ~64 kbps

case "$1" in
	-1p|-2p)
	case "$audiocodec" in
		MP2|mp2|MP3|mp3|AC3|ac3|AAC|aac|"")
		printf "Would you like xvidenc to calculate the video bitrate? [y/n]: "
		read calcvidbit
		if [ "$calcvidbit" = "y" -o "$calcvidbit" = "Y" ]; then
			# Currently the script does not support
			# quality values -> bitrate conversion
			# for the AAC codec. Have to dig more
			# info on that one
			if [ "$aacmode" = "VBR" -o "$aacmode" = "vbr" -o "$aacmode" = "V" -o "$aacmode" = "v" ]; then
				echo ""
				echo "-> You have chosen to use quality based audio mode (VBR)."
				echo "-> Currently xvidenc does not support video bitrate"
				echo "   calculation with VBR AAC audio!"
				echo ""
			else
				echo ""
				echo "Video Bitrate Calculation"
				echo "~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "xvidenc can calculate the video bitrate for you"
				echo "based on the video length, chosen audio bitrate and"
				echo "target file size. The only thing you have to provide"
				echo "here is the desired target size in Megabytes for the"
				echo "encode. After that, you can choose to keep the bitrate"
				echo "calculated by xvidenc, or you can provide a new one."
				echo ""
				printf "Specify the desired Target File Size in Megabytes [default is 700]: "
				read tfsm
				if [ -z "$tfsm" ]; then
					TARGET_SIZE=700
				else
					TARGET_SIZE=$tfsm
				fi
				# Get the chosen audio bitrate
				case "$audiocodec" in
					MP2|mp2)
					AUDIO_BITRATE=$abitrate
					;;
					MP3|mp3|"")
					case "$mp3mode" in
						CBR|cbr|C*|c*|ABR|abr|A*|a*|"")
						AUDIO_BITRATE=$(echo $abitrate | cut -f '2' -d '=')
						;;
						VBR|vbr|V*|v*)
						APPRO="~"
						# Use 10 kbps lesser compared
						# to the LAME specs
						case "$abitrate" in
							q=0) AUDIO_BITRATE=230 ;;
							q=1) AUDIO_BITRATE=200 ;;
							q=2) AUDIO_BITRATE=180 ;;
							q=3) AUDIO_BITRATE=165 ;;
							q=4) AUDIO_BITRATE=155 ;;
							q=5) AUDIO_BITRATE=120 ;;
							q=6) AUDIO_BITRATE=105 ;;
							q=7) AUDIO_BITRATE=90 ;;
							q=8) AUDIO_BITRATE=75 ;;
							q=9) AUDIO_BITRATE=54 ;;
						esac
						;;
					esac
					;;
					AC3|ac3)
					AUDIO_BITRATE=$abitrate
					;;
					AAC|aac)
					AUDIO_BITRATE=$(echo $br | cut -f '2' -d '=')
					;;
				esac
				# Get video length and calculate the video bitrate
				# based on the length, audio bitrate and target file
				# size.
				echo ""
				echo "-> Detecting video length..."
				mplayer "$sourcetype" $device -identify -vo null -frames 1 2>/dev/null > $CONFIGDIR/video_length
				VIDEO_LENGTH=$(grep "^ID_LENGTH" $CONFIGDIR/video_length | cut -f '2' -d '=' | cut -f '1' -d '.')
				if [ -z "$VIDEO_LENGTH" ]; then
					echo ""
					echo "-> Could not detect video length!"
					echo "-> Will skip video bitrate calculation!"
					echo ""
				else
					EST_BITRATE=$(($(($TARGET_SIZE*8192/$VIDEO_LENGTH))-$AUDIO_BITRATE))
					rm -f $CONFIGDIR/video_length
					echo ""
					echo "-> Video length is $(($VIDEO_LENGTH/60)) minutes"
					echo "-> Chosen audio bitrate is $APPRO$AUDIO_BITRATE kbps"
					echo ""
					echo "-> Estimated video bitrate for $TARGET_SIZE MB is: $EST_BITRATE kbps"
					echo ""
					printf "Specify the new video bitrate [default is $EST_BITRATE]: "
					read new_bitrate
					if [ -z "$new_bitrate" ]; then
						vbitrate="bitrate=$EST_BITRATE"
					else
						vbitrate="bitrate=$new_bitrate"
					fi
				fi
			fi
		fi
		;;
	esac
	;;
esac

###############################################################
#                     MEncoder stuff                          #
###############################################################

# MEncoder encoding
# configuration

# Log file for 2-pass
PASSLOG=$CONFIGDIR/xvid.log

mencoder_opts() {
	case "$1" in
		-1p|-fq)
		echo "$priority_level mencoder \"$sourcetype\" $chapters $device $ffourcc $ofps $filteropt $cropping$deblock$deintfilter$denoise$scale$iss$ss_parameters$accurate_vertical $scaler $sid $spuaa $aid $afilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts $vbitrate$me_quality$vhq$use_threads$max_key_interval$quantizers$max_bframes$bf_threshold$bvhq$packed$qpel$gmc$trellis$quant_type$interlaced$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$cartoon$stats$advopts:closed_gop:autoaspect \
		-o \"$OUTPUT\""
		;;
		-2p)
		# Pass one
		echo "$priority_level mencoder \"$sourcetype\" $chapters $device $ffourcc $ofps $filteropt $cropping$deblock$deintfilter$denoise$scale$iss$ss_parameters$accurate_vertical $scaler $sid $spuaa \
		-nosound -ovc xvid -xvidencopts pass=1$me_quality$vhq$use_threads$max_key_interval$quantizers$max_bframes$bf_threshold$bvhq$turbo$packed$qpel$gmc$trellis$quant_type$interlaced$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$cartoon$advopts:closed_gop:autoaspect \
		-passlogfile $PASSLOG -o /dev/null"
		echo ""
		# Pass two
		echo "$priority_level mencoder \"$sourcetype\" $chapters $device $ffourcc $ofps $filteropt $cropping$deblock$deintfilter$denoise$scale$iss$ss_parameters$accurate_vertical $scaler $sid $spuaa $aid $afilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts pass=2:$vbitrate$me_quality$vhq$use_threads$max_key_interval$quantizers$max_bframes$bf_threshold$bvhq$packed$qpel$gmc$trellis$quant_type$interlaced$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$cartoon$stats$advopts:closed_gop:autoaspect \
		-passlogfile $PASSLOG -o \"$OUTPUT\""
		;;
	esac
}

# Export the MEncoder parameters to file(s)
# These files will be used to execute MEncoder
# with its parameters.

XVID1PFQ=$CONFIGDIR/xvidenc_1pfq
XVID2P1=$CONFIGDIR/xvidenc_pass_one
XVID2P2=$CONFIGDIR/xvidenc_pass_two

case "$1" in
	-1p|-fq)
	$(mencoder_opts $1 > $XVID1PFQ)
	;;
	-2p)
	$(mencoder_opts $1 > $CONFIGDIR/xvidenc_2pass)
	
	# Split 2pass file
	# into two files
	
	cat $CONFIGDIR/xvidenc_2pass | head -n1 > $XVID2P1
	cat $CONFIGDIR/xvidenc_2pass | tail -n1 > $XVID2P2
	rm -f $CONFIGDIR/xvidenc_2pass
	;;
esac

# Display the options before encoding.
# This was a request from a few users :)
# Currently, there's no way how to modify
# these options if the user wants it

printf "Would you like to inspect the MEncoder options? [y/n]: "
read inspect
if [ "$inspect" = "y" -o "$inspect" = "Y" ]; then
	echo ""
	echo "+===========================+"
	echo "| MEncoder encoding options |"
	echo "+===========================+"
	echo ""
	case "$1" in
		-1p|-fq)
		echo $(cat $XVID1PFQ)
		;;
		-2p)
		echo "First pass options"
		echo "~~~~~~~~~~~~~~~~~~"
		echo $(cat $XVID2P1)
		echo ""
		echo "Second pass options"
		echo "~~~~~~~~~~~~~~~~~~~"
		echo $(cat $XVID2P2)
		;;
	esac
	echo ""
fi

# Ask user to save the MEncoder parameters so
# he/she can use them again. This is actually
# a bad idea, espacially if user has used the
# cropping filter since these parameters will
# only work on the same video source with the
# exact same cropping values. There are some
# special cases where 2 different DVDs will
# have the *exact* same crop values but in
# reality, it's very rare. And I haven't even
# mentioned DVD audio channels, (de)interlacing,
# frame rates, etc... hehe.
# But this was actually a user request I got,
# so I'm including it :). It can also be very
# useful for debugging purposes where one wants
# to inspect the options generated by this script
# and see where it went wrong.

printf "Would you like to save the used options to a file? [y/n]: "
read saveopts
if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
	echo ""
	echo "Note that this is actually a (very) bad idea,"
	echo "espacially if you have used the cropping filter"
	echo "since these options will only work on the same"
	echo "video source with the exact same cropping values."
	echo "There are some special cases where 2 different"
	echo "DVDs will have the *exact* same cropping values"
	echo "but in reality, it's very rare. And I haven't even"
	echo "mentioned DVD audio channels, (de)interlacing,"
	echo "frame rates, etc..."
	echo "So do not expect that they will work correctly on"
	echo "every video file or DVD you throw at them!!!"
	echo "This option is actually here only for debugging!"
	echo ""
	printf "Where to store the options? [default is $HOME/xvidenc_options]: "
	read storeopts
	case "$1" in
		-1p|-fq)
		OPTSFILE=$HOME/xvidenc_options
		if [ -z "$storeopts" ]; then
			echo $(cat $XVID1PFQ) > $OPTSFILE
		else
			if [ -z "$(echo $storeopts | grep '^/')" ]; then
				echo "-> You have to provide the full path!"
				echo "-> Will skip saving the options"
			else
				test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
				echo $(cat $XVID1PFQ) > "$storeopts"
			fi
		fi
		;;
		-2p)
		OPTSFILE=$HOME/xvidenc_options
		if [ -z "$storeopts" ]; then
			echo $(cat $XVID2P1) > $OPTSFILE
			echo "" >> $OPTSFILE
			echo $(cat $XVID2P2) >> $OPTSFILE
		else
			if [ -z "$(echo $storeopts | grep '^/')" ]; then
				echo "-> You have to provide the full path!"
				echo "-> Will skip saving the options"
			else
				test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
				echo $(cat $XVID2P1) > "$storeopts"
				echo "" >> "$storeopts"
				echo $(cat $XVID2P2) >> "$storeopts"
			fi
		fi
		;;
	esac
fi

# Ask user if he wants to convert
# from AVI to Matroska container

printf "Would you like to convert the final encode from AVI to Matroska? [y/n]: "
read avi_mkv
if [ "$avi_mkv" = "y" -o "$avi_mkv" = "Y" ]; then
	# Check for mkvmerge
	if [ ! -x "$(which mkvmerge 2>/dev/null)" ]; then
		avi_to_mkv=no
		echo ""
		echo "-> Utility 'mkvmerge' is missing!"
		echo "-> Will skip AVI to Matroska conversion!"
	else
		avi_to_mkv=yes
	fi
elif [ "$avi_mkv" = "n" -o "$avi_mkv" = "N" -o -z "$avi_mkv" ]; then
	avi_to_mkv=no
fi

echo ""
case "$1" in
	-1p)
	echo "-> Starting to encode the $source in 1 pass mode"
	display_quality_preset_func $3
	echo "-> Will use '$OUTPUT' as output file"
	;;
	-fq)
	echo "-> Starting to encode the $source in fixed quant mode"
	display_quality_preset_func $3
	echo "-> Will use '$OUTPUT' as output file"
	;;
	-2p)
	echo "-> Starting to encode the $source in 2 pass mode"
	display_quality_preset_func $3
	echo "-> Will use '/dev/null' as output for the first pass"
	echo "-> Will use '$OUTPUT' as output file for the second pass"
	;;
esac
echo ""

# Give user a few more
# seconds to read the above
sleep 3

# Small counter :)
count() {
	for i in 5 4 3 2 1; do
		sleep 1 && echo -n "$i "
	done
}

# Set counter color
color() {
	BLUE="\033[01;34m"
	NORMAL="\e[0;0m"
	case $1 in
		blue) printf "$BLUE" ;;
		normal) echo -ne "$NORMAL" ;;
	esac
}

color blue && printf "Starting to encode in: " && count
color normal && echo ""


# Start encoding
case "$1" in
	-1p|-fq)
	. $XVID1PFQ
	rm -f $XVID1PFQ
	;;
	-2p)
	test -f $PASSLOG && rm -f $PASSLOG
	. $XVID2P1
	rm -f $XVID2P1
	echo ""
	echo "=============================================================="
	echo ""
	color blue && printf "Starting the second pass of the encoding process in: " && count
	color normal && echo ""
	. $XVID2P2
	rm -f $XVID2P2
	rm -f $PASSLOG
	;;
esac

# Set output file for Matroska
OUTPUT_MKV="$(echo "$OUTPUT" | sed 's/\.avi/\.mkv/')"

# AVI -> MKV conversion
if [ "$avi_to_mkv" = "yes" ]; then
	# For AVI with Xvid video, there's
	# no need to detect aspect ratio
	# since mkvmerge does it for us
	# automatic by extracting the
	# aspect header stored in the
	# video.
	echo ""
	echo "-> Will convert AVI to Matroska now, please wait..."
	test -e "$OUTPUT_MKV" && mv -f "$OUTPUT_MKV" "$OUTPUT_MKV.old"
	sleep 3
	mkvmerge "$OUTPUT" -o "$OUTPUT_MKV" >/dev/null 2>&1
	echo "-> Done"
	echo ""
	printf "Delete the AVI file? [y/n]: "
	read del_avi
	if [ "$del_avi" = "y" -o "$del_avi" = "Y" ]; then
		rm -f "$OUTPUT"
	fi
fi

# Display file size
display_filesize_func() {
	echo "-> Final file size is $FSIZE MB"
}

# Ask user if he wants to split
# the final encode
case "$avi_to_mkv" in
	yes)
	# Get file size
	FSIZE="$(($(stat -c %s "$OUTPUT_MKV" 2>/dev/null)/1048576))"
	if [ $FSIZE -le 702 ]; then
		echo ""
		display_filesize_func
		echo "-> Have a nice day :)"
		echo ""
		exit 0
	fi
	echo ""
	display_filesize_func
	echo ""
	printf "Would you like to split the Matroska file into multiple files? [y/n]: "
	read split
	if [ "$split" = "y" -o "$split" = "Y" ]; then
		printf "How much Megabytes to use for each file? [default is 702]: "
		read filesize
		echo ""
		echo "-> Please wait..."
		if [ -z "$filesize" ]; then
			mkvmerge --split 702M "$OUTPUT_MKV" -o "$(echo "$OUTPUT_MKV" | sed 's/\.mkv/-.mkv/g')" >/dev/null 2>&1
		else
			mkvmerge --split ${filesize}M "$OUTPUT_MKV" -o "$(echo "$OUTPUT_MKV" | sed 's/\.mkv/-.mkv/g')" >/dev/null 2>&1
		fi
		echo "-> Done"
		echo ""
		printf "Delete original Matroska file? [y/n]: "
		read delete_mkv
		if [ "$delete_mkv" = "y" -o "$delete_mkv" = "Y" ]; then
			rm -f "$OUTPUT_MKV"
		fi
	fi
	;;
	no)
	# Get file size
	FSIZE="$(($(stat -c %s "$OUTPUT" 2>/dev/null)/1048576))"
	if [ $FSIZE -le 702 ]; then
		echo ""
		display_filesize_func
		echo "-> Have a nice day :)"
		echo ""
		exit 0
	fi
	echo ""
	display_filesize_func
	echo ""
	printf "Would you like to split the AVI file into multiple files? [y/n]: "
	read split
	if [ "$split" = "y" -o "$split" = "Y" ]; then
		# Check for avisplit
		if [ ! -x "$(which avisplit 2>/dev/null)" ]; then
			echo ""
			echo "-> Utility 'avisplit' is missing... cannot continue!"
			echo "-> Download 'transcode' to obtain 'avisplit'!"
			echo ""
			exit 1
		fi
		printf "How much Megabytes to use for each file? [default is 702]: "
		read filesize
		echo ""
		echo "-> Please wait..."
		# Split the file...
		# Note to take care of output files
		# which contain spaces in their names.
		# User might have provided a different
		# name for the output than the default
		# one.
		if [ -z "$filesize" ]; then
			avisplit -s 702 -i "$OUTPUT" -o "$(echo "$OUTPUT" | sed 's/\.avi//')" >/dev/null 2>&1
		else
			avisplit -s $filesize -i "$OUTPUT" -o "$(echo "$OUTPUT" | sed 's/\.avi//')" >/dev/null 2>&1
		fi
		echo "-> Done"
		echo ""
		printf "Delete original AVI file? [y/n]: "
		read delete_avi
		if [ "$delete_avi" = "y" -o "$delete_avi" = "Y" ]; then
			rm -f "$OUTPUT"
		fi
	fi
	;;
esac

echo ""
echo "-> Have a nice day :)"
echo ""

exit 0