#!/bin/bash
# $Id: xvidenc, v 7.8.6, 2008/04/28, gn Exp $
# UUID: 1ff8ecff-b178-4d64-b084-71ebd7972fe7
#
# Encode DVDs/video files to the Xvid 1.1.x video format
# using MEncoder from MPlayer
#
# Copyright (C) 2006-2008 - 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

shopt -u expand_aliases
export PATH=$PATH:/usr/bin
version=7.8.6

green() { echo -e "\e[1;32m$1\e[0;39;49m"; }

brown() { echo -e "\e[33m$1\e[39;49m"; }

error() { echo -e "\e[1;31m$1\e[0;39;49m"; }

case "$1" in
	"")
	echo "Usage: xvidenc [-1p|-2p|-fq|-b|-sc|-scan|-sv|-iso|-bpp|-bpb|-v|--help] [-p <preset>]"
	exit 1
	;;
	-v)
	echo "xvidenc $version"
	exit 0
	;;
	--help)
	echo ""
	echo "+=======================================================+"
	echo "|     xvidenc - the interactive shell script ripper     |"
	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.0rc2 or higher!"
	echo "For more information, read the man page of xvidenc (man xvidenc)"
	echo "or visit its Web site at http://xvidenc.sourceforge.net where"
	echo "one can find an extensive FAQ"
	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 " <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). You can choose from"
	echo "             15 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 "             nlq ------> Near Lossless Quality (NLQ) preset (only in '-fq' mode)"
	echo "             hwsdpal --> Stand-alone HW compatible SD (HWSDPAL) preset (PAL/SECAM)"
	echo "             hwsdntsc -> Stand-alone HW compatible SD (HWSDNTSC) preset (NTSC)"
	echo "             hwhdpal --> Stand-alone HW compatible HD (HWHDPAL) preset (PAL/SECAM)"
	echo "             hwhdntsc -> Stand-alone HW compatible HD (HWHDNTSC) preset (NTSC)"
	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 " -b /path/to/file/batchfile"
	echo ""
	echo "            Load a batch file generated by *this* script. This option"
	echo "            can be useful for testing or debugging the encoding parameters"
	echo "            and for batch encoding."
	echo ""
	echo " -sc        Perform a sanity check. This will check for the programs"
	echo "            which are required for the correct operation of this script"
	echo "            and it will print the status in a list. It will also display"
	echo "            which audio codecs are supported by MEncoder."
	echo ""
	echo " -scan      Scan the DVD disc and display extensive information about it."
	echo "            With this option, one can display or export the information"
	echo "            to a file on disk in text, perl, python, ruby or xml format."
	echo ""
	echo " -sv        Scan a video file and display extensive information about it."
	echo ""
	echo " -iso       Create an ISO image out of the DVD content and store it to disk."
	echo ""
	echo " -bpp       This is an informative option which lets you calculate"
	echo "            the Bits Per Pixel (bpp) values for various resolutions."
	echo "            The bpp value represents how much bits each pixel gets. The"
	echo "            higher the bpp value is, the more distinct colors the pixels"
	echo "            will have which leads to a higher overall picture quality."
	echo "            Note that these values are not absolute! For video content"
	echo "            with a lot of black in it, a bpp value of 0.14 may look"
	echo "            very good. Video content with a lot of high motion scenes"
	echo "            may still look bad with a bpp value of 0.20, so this really"
	echo "            depends on the content you are willing to encode and the"
	echo "            video bitrate and resolution you choose when scaling down."
	echo ""
	echo " -bpb       This option is similar to the -bpp one, except it calculates"
	echo "            the Bits Per Block (bpb) values for various resolutions."
	echo "            The bpb value expresses how many bits each 16x16 macroblock"
	echo "            gets. Good bpb values are between 37-52. As is the case with"
	echo "            Bits Per Pixel, the bpb values are not absolute and depend"
	echo "            on the video content you are willing to encode and the"
	echo "            video bitrate and resolution you choose when scaling down."
	echo ""
	echo " -v          Display version of this script and exit"
	echo ""
	echo " --help      Display this help screen and exit"
	echo ""
	echo "TIP: if you don't want to use an option, instead of always answering"
	echo "with 'n', just press Enter."
	echo ""
	echo "For bug reporting, suggestions, comments, questions or if this script"
	echo "was useful to you, send me an e-mail at <neutrino8@gmail.com>"
	echo ""
	exit 0
	;;
	-bpp|-bpb)
	# Bits per pixel/block calculation
	if [ ! -x "$(which bc 2>/dev/null)" ]; then
		error "-> Checking for 'bc'... FAILED!"
		exit 1
	fi
	case "$1" in
		-bpp)
		echo ""
		brown "+============================+"
		brown "| Bits Per Pixel Calculation |"
		brown "+============================+"
		echo ""
		;;
		-bpb)
		echo ""
		brown "+============================+"
		brown "| Bits Per Block Calculation |"
		brown "+============================+"
		echo ""
		;;
	esac
	cal0() {
		echo "scale=0; $1" | bc -l | sed 's@^\.@0\.@'
	}
	cal3() {
		echo "scale=3; $1" | bc -l | sed 's@^\.@0\.@'
	}
	round() {
		D_PART=$(echo "$1" | awk -F. '{print $1}')
		F_PART=$(echo "$1" | awk -F. '{print $2}')
		if [ $F_PART -lt 500 ]; then
			echo $D_PART
		else
			echo $[$D_PART+1]
		fi
	}
	printf "Provide the original unscaled resolution [default is 720x576]: "
	read O_RES
	if [ -z "$O_RES" ]; then
		R_ASP=$(cal3 "720/576")
	else
		R_ASP=$(cal3 $(echo $O_RES | tr '[:alpha:]' '/'))
	fi
	printf "Provide the original unscaled but cropped resolution [WxH]: "
	read U_RES
	if [ -z "$U_RES" ]; then
		error "-> Cropped resolution value is required!"
		exit 1
	fi
	printf "Provide the aspect ratio [16/9 or 4/3 - default is 16/9]: "
	read AR
	if [ -z "$AR" ]; then
		A_RAT=16/9
	else
		A_RAT=$AR
	fi
	printf "Provide the video bitrate: "
	read V_BTR
	if [ -z "$V_BTR" ]; then
		error "-> Video bitrate is required!"
		exit 1
	fi
	printf "Provide the video's FPS value [integer or float - default is 25]: "
	read VFPS
	if [ -z "$VFPS" ]; then
		M_FPS=25
	else
		M_FPS=$VFPS
	fi
	U_WID=$(echo $U_RES | awk -Fx '{print $1}')
	U_HEI=$(echo $U_RES | awk -Fx '{print $2}')
	E_RAT=$(cal3 "$A_RAT")
	S_WID=$(cal0 "$U_WID*$E_RAT/$R_ASP")
	S_HEI=$U_HEI
	P_AR=$(cal3 "$S_WID/$S_HEI")
	echo ""
	brown "Prescaled picture: ${S_WID}x$S_HEI - Aspect Ratio: $P_AR"
	case "$1" in
		-bpp)
		for ((WID=$(echo $U_RES | awk -Fx '{print $1}'); WID>=320; WID=WID-16)); do
			R_H=$(cal3 "$WID/$P_AR/16")
			HEI=$[16*$(round "$R_H")]
			BPP=$(cal3 "1000*$V_BTR/($WID*$HEI*$M_FPS)")
			BITRATE=$(cal0 "($WID*$HEI*$M_FPS*$BPP)/1000")
			echo "Resolution: $(green "${WID}x$HEI") -- BPP: $(green $BPP) -- Bitrate based on BPP: $(green "$BITRATE kbps")"
		done
		;;
		-bpb)
		for ((WID=$(echo $U_RES | awk -Fx '{print $1}'); WID>=320; WID=WID-16)); do
			R_H=$(cal3 "$WID/$P_AR/16")
			HEI=$[16*$(round "$R_H")]
			BPB=$(cal3 "$V_BTR*1000/($M_FPS*($WID*$HEI)/(16*16))")
			echo "Resolution: $(green "${WID}x$HEI") -- BPB: $(green $BPB)"
		done
		;;
	esac
	echo ""
	exit 0
	;;
	-b)
	if [ -z "$2" ]; then
		error "-> Option '-b' requires an input file!"
		error "-> Use: $(basename $0) --help"
		exit 1
	fi
	if [ ! -f "$2" ]; then
		error "-> No such file: '$2'"
		exit 1
	fi
	. "$2"
	exit $?
	;;
	-sc)
	echo ""
	if [ -x "$(which mplayer 2>/dev/null)" ]; then
		echo "-> Checking for 'MPlayer'..................... $(green OK)"
	else
		echo "-> Checking for 'MPlayer'..................... $(error FAILED!)"
	fi
	if [ -x "$(which mencoder 2>/dev/null)" ]; then
		echo "-> Checking for 'MEncoder'.................... $(green OK)"
		if [ -z "$(mencoder -ovc help 2>/dev/null | awk '{print $1}' | grep 'xvid')" ]; then
			echo "-> Xvid video support in MEncoder............. $(error NO)"
		else
			echo "-> Xvid video support in MEncoder............. $(green YES)"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" ]; then
			echo "-> AAC (FAAC) audio support in MEncoder....... $(error NO)"
		else
			echo "-> AAC (FAAC) audio support in MEncoder....... $(green YES)"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" ]; then
			echo "-> MP3 (LAME) audio support in MEncoder....... $(error NO)"
		else
			echo "-> MP3 (LAME) audio support in MEncoder....... $(green YES)"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc')" ]; then
			echo "-> MP2 (lavc) audio support in MEncoder....... $(error NO)"
			echo "-> AC3 (lavc) audio support in MEncoder....... $(error NO)"
			echo "-> WMA (lavc) audio support in MEncoder....... $(error NO)"
			echo "-> Sonic (lavc) audio support in MEncoder..... $(error NO)"
			echo "-> FLAC (lavc) audio support in MEncoder...... $(error NO)"
			echo "-> ADPCM (lavc) audio support in MEncoder..... $(error NO)"
		else
			echo "-> MP2 (lavc) audio support in MEncoder....... $(green YES)"
			echo "-> AC3 (lavc) audio support in MEncoder....... $(green YES)"
			echo "-> WMA (lavc) audio support in MEncoder....... $(green YES)"
			echo "-> Sonic (lavc) audio support in MEncoder..... $(green YES)"
			echo "-> FLAC (lavc) audio support in MEncoder...... $(green YES)"
			echo "-> ADPCM (lavc) audio support in MEncoder..... $(green YES)"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" ]; then
			echo "-> PCM audio support in MEncoder.............. $(error NO)"
		else
			echo "-> PCM audio support in MEncoder.............. $(green YES)"
		fi
	else
		echo "-> Checking for MEncoder...................... $(error FAILED!)"
	fi
	echo ""
	if [ -x "$(which bc 2>/dev/null)" ]; then
		echo "-> Checking for 'bc'.......................... $(green OK)"
	else
		echo "-> Checking for 'bc'.......................... $(error FAILED!)"
	fi
	if [ -x "$(which pv 2>/dev/null)" ]; then
		echo "-> Checking for 'pv'.......................... $(green OK)"
	else
		echo "-> Checking for 'pv'.......................... $(error "FAILED! [no support for DVD ISO dumps]")"
	fi
	if [ -x "$(which dd 2>/dev/null)" ]; then
		echo "-> Checking for 'dd'.......................... $(green OK)"
	else
		echo "-> Checking for 'dd'.......................... $(error "FAILED! [no support for DVD ISO dumps]")"
	fi
	if [ -x "$(which neroAacEnc 2>/dev/null)" ]; then
		echo "-> Checking for 'neroAacEnc'.................. $(green OK)"
	else
		echo "-> Checking for 'neroAacEnc'.................. $(error "FAILED! [no support for AAC+ audio]")"
	fi
	if [ -x "$(which oggenc 2>/dev/null)" ]; then
		echo "-> Checking for 'oggenc'...................... $(green OK)"
	else
		echo "-> Checking for 'oggenc'...................... $(error "FAILED! [no support for Vorbis audio]")"
	fi
	if [ -x "$(which less 2>/dev/null)" ]; then
		echo "-> Checking for 'less'........................ $(green OK)"
	else
		echo "-> Checking for 'less'........................ $(error FAILED!)"
	fi
	if [ -x "$(which lsdvd 2>/dev/null)" ]; then
		echo "-> Checking for 'lsdvd'....................... $(green OK)"
	else
		echo "-> Checking for 'lsdvd'....................... $(error "FAILED! [no support for DVD title scans]")"
	fi
	if [ -x "$(which dvdxchap 2>/dev/null)" ]; then
		echo "-> Checking for 'dvdxchap' (from ogmtools).... $(green OK)"
	else
		echo "-> Checking for 'dvdxchap' (from ogmtools).... $(error "FAILED! [no support for DVD chapters export]")"
	fi
	if [ -x "$(which mkvmerge 2>/dev/null)" ]; then
		echo "-> Checking for 'mkvmerge' (from mkvtoolnix).. $(green OK)"
	else
		echo "-> Checking for 'mkvmerge' (from mkvtoolnix).. $(error "FAILED! [no support for the Matroska container]")"
	fi
	if [ -x "$(which ogmmerge 2>/dev/null)" ]; then
		echo "-> Checking for 'ogmmerge' (from ogmtools).... $(green OK)"
	else
		echo "-> Checking for 'ogmmerge' (from ogmtools).... $(error "FAILED! [no support for the OGM container]")"
	fi
	if [ -x "$(which MP4Box 2>/dev/null)" ]; then
		echo "-> Checking for 'MP4Box' (from gpac).......... $(green OK)"
	else
		echo "-> Checking for 'MP4Box' (from gpac).......... $(error "FAILED! [no support for the MP4 container]")"
	fi
	echo ""
	exit 0
	;;
	-scan)
	echo ""
	printf "Would you like to scan a video file or a DVD? [file/dvd]: "
	read scantype
	case "$scantype" in
		file|FILE|File)
		for i in bc mplayer; do
			if [ ! -x "$(which $i 2>/dev/null)" ]; then
				error "-> Checking for '$i'... FAILED!"
				exit 1
			fi
		done
		test -d $HOME/.xvidenc || mkdir -p $HOME/.xvidenc
		printf "Provide the input video file: "
		read -e infile
		if [ -z "$infile" -o -z "$(echo "$infile" | grep '^/')" ]; then
			error "-> You didn't specify the input file or the full path to it!"
			exit 1
		fi
		if [ ! -e "$infile" ]; then
			error "-> No such file: '$infile'"
			exit 1
		fi
		echo ""
		green "-> Scanning the file..."
		INFO="$HOME/.xvidenc/info"
		mplayer "$infile" -identify -vo null -nocache -frames 1 2>/dev/null > $INFO
		echo ""
		echo "MPlayer Demuxer:   $(grep '^ID_DEMUXER' $INFO | tail -1 | awk -F= '{print $2}')"
		echo "Video Format:      $(grep '^ID_VIDEO_FORMAT' $INFO | awk -F= '{print $2}')"
		echo "Video Bitrate:     $(echo "scale=1; $(grep '^ID_VIDEO_BITRATE' $INFO | awk -F= '{print $2}')/1000" | bc -l) kbps"
		echo "Video FPS:         $(grep '^ID_VIDEO_FPS' $INFO | awk -F= '{print $2}')"
		echo "Video Resolution:  $(grep '^VIDEO:' $INFO | tail -1 | awk '{print $3}')"
		echo "Video Aspect:      $(grep '^ID_VIDEO_ASPECT' $INFO | tail -1 | awk -F= '{print $2}')"
		echo "Video Length:      $(echo "scale=1; $(grep '^ID_LENGTH' $INFO | awk -F= '{print $2}')/60" | bc -l | sed 's/^\./0\./') minutes"
		echo ""
		echo "Audio Codec:       $(grep '^ID_AUDIO_CODEC' $INFO | tail -1 | awk -F= '{print $2}')"
		echo "Audio Bitrate:     $(($(grep '^ID_AUDIO_BITRATE' $INFO | tail -1 | awk -F= '{print $2}')/1000)) kbps"
		echo "Audio Sample Rate: $(grep '^ID_AUDIO_RATE' $INFO | tail -1 | awk -F= '{print $2}') Hz"
		echo "Audio Channels:    $(grep '^ID_AUDIO_NCH' $INFO | tail -1 | awk -F= '{print $2}')"
		echo ""
		rm -f $INFO
		exit 0
		;;
		dvd|DVD|Dvd)
		# Scan the DVD disc and display
		# info about it, titles, chapters,
		# audio streams, subs, cells, etc...
		for i in lsdvd mplayer less; do
			if [ ! -x "$(which $i 2>/dev/null)" ]; then
				error "-> Checking for '$i'... FAILED!"
				exit 1
			fi
		done
		echo ""
		if [ -r /proc/sys/dev/cdrom/info ]; then
			DRIVE=$(grep "drive name" /proc/sys/dev/cdrom/info | sed 's/drive name://g')
			if [ ! -z "$DRIVE" ]; then
				for i in $DRIVE; do
					green "-> Found device: /dev/$i"
				done
			fi
		fi
		if [ -L /dev/dvd ]; then
			green "-> 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 -e dvd_dev
		if [ -z "$dvd_dev" ]; then
			device="/dev/dvd"
		else
			if [ -z "$(echo $dvd_dev | grep '^/')" ]; then
				error "-> You have to provide the full path to the DVD device!"
				exit 1
			fi
			if [ ! -e "$dvd_dev" ]; then
				error "-> No such device: '$dvd_dev'"
				exit 1
			fi
			device="$dvd_dev"
		fi
		echo ""
		green "-> Unlocking the DVD disc..."
		GET_TITLES="$(mplayer dvd://1 -dvd-device $device -nosound -nocache -vo null -frames 1 2>/dev/null | grep -m1 'titles')"
		TITLE="$(echo $GET_TITLES | awk '{print $3}')"
		green "-> $GET_TITLES"
		green "-> $(lsdvd $device 2>/dev/null | grep 'Longest' | sed 's/track:/title:/')"
		echo ""
		brown "DVD Information Menu"
		brown "~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Display Audio Streams"
		echo "1 -> Display Cells"
		echo "2 -> Display Angles"
		echo "3 -> Display Chapters"
		echo "4 -> Display Subtitles"
		echo "5 -> Display Palette Info"
		echo "6 -> Display Title/Video Info"
		echo "7 -> Display All Of The Above"
		echo "8 -> Export Info To A File"
		echo "9 -> Exit"
		echo ""
		printf "Select an option: "
		read option
		case "$option" in
			[0-8]) true ;;
			9) exit 0 ;;
			""|*)
			error "-> Option unknown or not specified!"
			exit 1
			;;
		esac
		printf "Specify the DVD title [1-$TITLE/all]: "
		read dvd_title
		if [ "$dvd_title" != "all" ]; then
			title="-t $dvd_title"
			titlenum="title$dvd_title"
		else
			title=
			titlenum="alltitles"
		fi
		case "$option" in
			0) lsdvd $title -a -Oh $device 2>/dev/null | less ;;
			1) lsdvd $title -d -Oh $device 2>/dev/null | less ;;
			2) lsdvd $title -n -Oh $device 2>/dev/null | less ;;
			3) lsdvd $title -c -Oh $device 2>/dev/null | less ;;
			4) lsdvd $title -s -Oh $device 2>/dev/null | less ;;
			5) lsdvd $title -P -Oh $device 2>/dev/null | less ;;
			6) lsdvd $title -v -Oh $device 2>/dev/null | less ;;
			7) lsdvd $title -x -Oh $device 2>/dev/null | less ;;
			8)
			printf "Which option to export? [0-7/all]: "
			read opt
			case "$opt" in
				0) info="-a" ;;
				1) info="-d" ;;
				2) info="-n" ;;
				3) info="-c" ;;
				4) info="-s" ;;
				5) info="-P" ;;
				6) info="-v" ;;
				7|all) info="-x" ;;
				""|*)
				error "-> Option unknown or not specified!"
				exit 1
				;;
			esac
			printf "In which format to export? [text/perl/python/ruby/xml]: "
			read format
			case "$format" in
				text) ext="txt" ;;
				perl) ext="pl" ;;
				python) ext="py" ;;
				ruby) ext="rb" ;;
				xml) ext="xml" ;;
				""|*)
				error "-> Format unsupported or not specified!"
				exit 1
				;;
			esac
			DT="$HOME/$(lsdvd $device 2>/dev/null | grep '^Disc Title' | awk -F': ' '{print $2}')"
			if [ ! -z "$DT" ]; then
				DISC_TITLE="$DT"
			else
				DISC_TITLE="DVD"
			fi
			store_func() {
				case "$1" in
					0) EXPORT_FILE="$DISC_TITLE-$titlenum-audiostreams.$ext" ;;
					1) EXPORT_FILE="$DISC_TITLE-$titlenum-cells.$ext" ;;
					2) EXPORT_FILE="$DISC_TITLE-$titlenum-angles.$ext" ;;
					3) EXPORT_FILE="$DISC_TITLE-$titlenum-chapters.$ext" ;;
					4) EXPORT_FILE="$DISC_TITLE-$titlenum-subtitles.$ext" ;;
					5) EXPORT_FILE="$DISC_TITLE-$titlenum-palette.$ext" ;;
					6) EXPORT_FILE="$DISC_TITLE-$titlenum-title+video.$ext" ;;
					7|all) EXPORT_FILE="$DISC_TITLE-$titlenum-allinfo.$ext" ;;
				esac
			}
			info_func() {
				echo ""
				echo "-> Saving to '$EXPORT_FILE'"
				echo ""
			}
			case "$format" in
				text)
				store_func $opt
				info_func
				lsdvd $title $info -Oh $device 2>/dev/null > $EXPORT_FILE
				;;
				perl)
				store_func $opt
				info_func
				lsdvd $title $info -Op $device 2>/dev/null > $EXPORT_FILE
				;;
				python)
				store_func $opt
				info_func
				lsdvd $title $info -Oy $device 2>/dev/null > $EXPORT_FILE
				;;
				ruby)
				store_func $opt
				info_func
				lsdvd $title $info -Or $device 2>/dev/null > $EXPORT_FILE
				;;
				xml)
				store_func $opt
				info_func
				lsdvd $title $info -Ox $device 2>/dev/null > $EXPORT_FILE
				;;
			esac
			;;
		esac
		exit 0
		;;
		*|"")
		error "-> You didn't specify the type!"
		exit 1
		;;
	esac
	;;
	-iso)
	for i in bc dd mplayer lsdvd; do
		if [ ! -x "$(which $i 2>/dev/null)" ]; then
			error "-> Checking for '$i'... FAILED!"
			exit 1
		fi
	done
	interrupt_func() {
		echo ""
		error "-> Exiting..."
		sleep 1
		rm -f "$OUTPUT" 2>/dev/null
		exit 1
	}
	trap 'interrupt_func' SIGHUP SIGTSTP SIGINT SIGQUIT SIGKILL SIGABRT SIGFPE SIGSEGV SIGTERM SIGPIPE SIGIO
	check_space_func() {
		HDSPACE="$(df -m "$(dirname "$OUTPUT")" | tail -1 | sed -r 's/^.*\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+[0-9]+%.*/\1/')"
		if [ $HDSPACE -lt 9216 ]; then
			echo ""
			error "-> You are running out of disk space in '$(dirname "$OUTPUT")'"
			error "-> Space left over: $HDSPACE MB ($(echo "scale=3; $HDSPACE/1024" | bc -l | sed 's|^\.|0\.|') GiB)"
			error "-> Please provide a different output directory!"
			echo ""
			exit 1
		fi
	}
	echo ""
	brown "+=======================+"
	brown "| DVD ISO Image Dumping |"
	brown "+=======================+"
	echo ""
	if [ -r /proc/sys/dev/cdrom/info ]; then
		DRIVE=$(grep "drive name" /proc/sys/dev/cdrom/info | sed 's/drive name://g')
		if [ ! -z "$DRIVE" ]; then
			for i in $DRIVE; do
				green "-> Found device: /dev/$i"
			done
		fi
	fi
	if [ -L /dev/dvd ]; then
		green "-> 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 -e dvd_dev
	if [ -z "$dvd_dev" ]; then
		device="/dev/dvd"
	else
		if [ -z "$(echo $dvd_dev | grep '^/')" ]; then
			error "-> You have to provide the full path to the DVD device!"
			exit 1
		fi
		if [ ! -e "$dvd_dev" ]; then
			error "-> No such device: '$dvd_dev'"
			exit 1
		fi
		device="$dvd_dev"
	fi
	echo ""
	green "-> Unlocking the DVD disc..."
	mplayer dvd://1 -dvd-device $device -vo null -nosound -nocache -frames 1 >/dev/null 2>&1
	green "-> Scanning for DVD title name..."
	TITLE="$(lsdvd $device 2>/dev/null | grep '^Disc Title' | awk -F': ' '{print $2}')"
	if [ ! -z "$TITLE" ]; then
		OUT="$HOME/$TITLE.iso"
	else
		OUT="$HOME/DVD.iso"
	fi
	test -e "$OUT" && mv -f "$OUT" "$OUT.old"
	echo ""
	printf "Specify the Output for the ISO image [default is $OUT]: "
	read -e iso_out
	if [ -z "$iso_out" ]; then
		OUTPUT="$OUT"
		check_space_func
	else
		if [ -z "$(echo $iso_out | grep '^/')" ]; then
			error "-> You have to provide the full path!"
			exit 1
		fi
		test -d "$(dirname "$iso_out")" || mkdir -p "$(dirname "$iso_out")" 2>/dev/null
		OUTPUT="$iso_out"
		check_space_func
	fi
	echo ""
	green "-> Available disk space: $HDSPACE MB ($(echo "scale=3; $HDSPACE/1024" | bc -l) GiB)"
	green "-> Dumping disc content to ISO image, please wait..."
	green "-> This can take a while..."
	echo ""
	if [ -x "$(which pv 2>/dev/null)" ]; then
		pv "$device" > "$OUTPUT"
	else
		dd if="$device" of="$OUTPUT" 2>/dev/null
	fi
	echo "-> Done"
	echo ""
	exit 0
	;;
	-[1-2]p|-fq)
	true
	;;
	*)
	error "-> Unknown option: '$1'"
	error "-> Use: '$(basename $0) --help' for more info"
	exit 1
	;;
esac

if [ -z "$3" ]; then
	error "-> No preset specified!"
	error "-> Use: xvidenc --help"
	exit 1
fi
case "$2" in
	-p)
	case "$3" in
		ulq|elq|vlq|lq|mq|nq|hq|vhq|ehq|uhq|nlq|hwsdpal|hwsdntsc|hwhdpal|hwhdntsc) true ;;
		"")
		error "-> No preset specified!"
		error "-> Use: xvidenc --help"
		exit 1
		;;
		*)
		error "-> Unknown preset: '$3'"
		error "-> Use: xvidenc --help"
		exit 1
		;;
	esac
	;;
	*)
	error "-> Unknown option: '$2'"
	error "-> Use: 'xvidenc --help' for more info"
	exit 1
	;;
esac

# The NLQ preset is suppored only in
# fixed-quant mode! Check and warn user
# about that.
if [ "$3" = "nlq" ]; then
	if [ "$1" = "-1p" -o "$1" = "-2p" ]; then
		error "-> The Near Lossless Quality (NLQ) preset is supported only in Fixed-Quant mode!"
		error "-> Use: $(basename $0) -fq -p nlq"
		exit 1
	fi
fi

# Informant function for displaying
# the selected quality preset
display_quality_preset_func() {
	case "$1" in
		ulq) green "-> Using \"Ultra Low Quality (ULQ)\" preset" ;;
		elq) green "-> Using \"Extreme Low Quality (ELQ)\" preset" ;;
		vlq) green "-> Using \"Very Low Quality (VLQ)\" preset" ;;
		lq) green "-> Using \"Low Quality (LQ)\" preset" ;;
		mq) green "-> Using \"Medium Quality (MQ)\" preset" ;;
		nq) green "-> Using \"Normal Quality (NQ)\" preset" ;;
		hq) green "-> Using \"High Quality (HQ)\" preset" ;;
		vhq) green "-> Using \"Very High Quality (VHQ)\" preset" ;;
		ehq) green "-> Using \"Extreme High Quality (EHQ)\" preset" ;;
		uhq) green "-> Using \"Ultra High Quality (UHQ)\" preset" ;;
		nlq) green "-> Using \"Near Lossless Quality (NLQ)\" preset" ;;
		hwsdpal) green "-> Using \"Stand-alone HW compatible SD (HWSDPAL)\" preset (PAL/SECAM)" ;;
		hwsdntsc) green "-> Using \"Stand-alone HW compatible SD (HWSDNTSC)\" preset (NTSC)" ;;
		hwhdpal) green "-> Using \"Stand-alone HW compatible HD (HWHDPAL)\" preset (PAL/SECAM)" ;;
		hwhdntsc) green "-> Using \"Stand-alone HW compatible HD (HWHDNTSC)\" preset (NTSC)" ;;
	esac
}

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

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

if [ ! -x "$(which mencoder 2>/dev/null)" ]; then
	error "-> Checking for MEncoder... FAILED!"
	exit 1
fi

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

if [ ! -x "$(which mplayer 2>/dev/null)" ]; then
	error "-> Checking for MPlayer... FAILED!"
	exit 1
fi

# Make config dir
test -d $HOME/.xvidenc || mkdir -p $HOME/.xvidenc

# Use unique temporary directory so we
# can run multiple instances of xvidenc
# without interference
CONFIGDIR=$(mktemp -d $HOME/.xvidenc/xvidenc.XXXXXXXX)
if [ ! -d $CONFIGDIR ]; then
	error "-> Failed to create '$CONFIGDIR' directory!"
	exit 1
fi

# User interrupt
interrupt_func() {
	echo ""
	error "-> Exiting..."
	rm -rf $CONFIGDIR
	exit 1
}

trap 'interrupt_func' SIGHUP SIGTSTP SIGINT SIGQUIT SIGKILL SIGABRT SIGFPE SIGSEGV SIGTERM SIGPIPE SIGIO

# Delete config directory
# on error
rmconf() { rm -rf $CONFIGDIR; exit 1; }

###############################################################
#### Functions shared by both DVD and video file encodings ####
###############################################################
#
# Video filters that come before the 'scale' filter
# must have a , (comma) appended at their end.
# Video filters that come after the 'scale' filter,
# must be preceded by a , (comma).
#

# Frame rate selection for
# frame doubling deinterlace
# filters. Kicks only in effect
# if the script couldn't detect
# a supported FPS value or if
# we deal with NTSC content.
deint_custom_fps_func() {
	echo ""
	brown "Deinterlace Frame Rate Selection"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 --> Silent Film @ 31.97 fps (2*16000/1001)"
	echo "1 --> Silent Film @ 35.96 fps (2*18000/1001)"
	echo "2 --> Film @ 48 fps (2*24)"
	echo "3 --> PAL/SECAM @ 50 fps (2*25)"
	echo "4 --> PAL/SECAM @ 100 fps (2*50)"
	echo "5 --> PAL/SECAM @ 200 fps (2*100)"
	echo "6 --> NTSC @ 47.95 fps (2*24000/1001)"
	echo "7 --> NTSC @ 59.94 fps (2*30000/1001)"
	echo "8 --> NTSC @ 60 fps (2*30)"
	echo "9 --> NTSC @ 119.88 fps (2*60000/1001)"
	echo "10 -> NTSC @ 239.76 fps (2*120000/1001)"
	echo ""
	printf "Select the Deinterlace double frame rate [no default!]: "
	read dfr
	case "$dfr" in
		0) deintfps="32000/1001"; deintofps="32000/1001" ;;
		1) deintfps="36000/1001"; deintofps="36000/1001" ;;
		2) deintfps="48"; deintofps="48" ;;
		3) deintfps="50"; deintofps="50" ;;
		4) deintfps="100"; deintofps="100" ;;
		5) deintfps="200"; deintofps="200" ;;
		6) deintfps="48000/1001"; deintofps="48000/1001" ;;
		7) deintfps="60000/1001"; deintofps="60000/1001" ;;
		8) deintfps="60"; deintofps="60" ;;
		9) deintfps="120000/1001"; deintofps="120000/1001" ;;
		10) deintfps="240000/1001"; deintofps="240000/1001" ;;
		""|*)
		error "-> Option unknown or deinterlace frame rate not specified!"
		rmconf
		;;
	esac
}

# Detect the source FPS value
# of the content. This function
# is used by the deinterlace and
# interlace functions
source_fps_func() {
	echo ""
	green "-> Detecting source FPS value..."
	mplayer "$sourcetype" $device $vid -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/sourcefps
	SOURCEFPS=$(grep '^ID_VIDEO_FPS' $CONFIGDIR/sourcefps | tail -1 | awk -F= '{print $2}')
	rm -f $CONFIGDIR/sourcefps
	case "$1" in
		deinterlace)
		calc_fps_func() {
			green "-> Setting input/output frame rate to $(echo "scale=3; $SOURCEFPS*2" | bc -l) FPS"
			green "-> Using '$(echo $deintfilter | sed 's/,$//')' video filter(s)"
		}
		;;
		interlace)
		calc_fps_func() {
			green "-> Setting input/output frame rate to $(echo "scale=3; $intfps" | bc -l)/$(echo "scale=3; $intofps" | bc -l) FPS"
			green "-> Using '$(echo $intfilter | sed 's/^,//')' video filter(s)"
			echo ""
		}
		;;
	esac
}

# 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 interlace-aware
			# mode in Xvid
			interlacing=":interlacing"
			deintfilter=
			field_dominance=
			deintfps=
			deintofps=
			# Ask if the user will be using denoise/deblock filters
			# so we can deinterleave the content, apply the denoising,
			# deblocking and interleave the content. This way we can
			# process the content without breaking the interlacing
			printf "Will you be using Denoise/Deblock filters later on? [y/n]: "
			read ddbc
			if [ "$ddbc" = "y" -o "$ddbc" = "Y" ]; then
				ild="il=d,"
				ili="il=i,"
			else
				ild=
				ili=
			fi
		elif [ "$preint" = "n" -o "$preint" = "N" -o -z "$preint" ]; then
			interlacing=":nointerlacing"
			echo ""
			brown "Available Deinterlacing Filters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "0 --> Linear Blend Deinterlacer"
			echo "1 --> Linear Interpolating Deinterlacer"
			echo "2 --> Cubic Interpolating Deinterlacer"
			echo "3 --> Median Deinterlacer"
			echo "4 --> FFmpeg Deinterlacer"
			echo "5 --> FIR Lowpass 5 Deinterlacer"
			echo "6 --> Donald Graft's Adaptive Kernel Deinterlacer"
			echo "7 --> Yadif Deinterlacer"
			echo "8 --> Yadif Deinterlacer (no spatial check)"
			echo "9 --> Yadif=1 & Fast Mcdeint (top fields)"
			echo "10 -> Yadif=1 & Fast Mcdeint (bottom fields)"
			echo "11 -> Yadif=3 & Fast Mcdeint (top fields)"
			echo "12 -> Yadif=3 & Fast Mcdeint (bottom fields)"
			echo "13 -> Yadif=1 & Medium Mcdeint (top fields)"
			echo "14 -> Yadif=1 & Medium Mcdeint (bottom fields)"
			echo "15 -> Yadif=3 & Medium Mcdeint (top fields)"
			echo "16 -> Yadif=3 & Medium Mcdeint (bottom fields)"
			echo "17 -> Yadif=1 & Slow Mcdeint (top fields)"
			echo "18 -> Yadif=1 & Slow Mcdeint (bottom fields)"
			echo "19 -> Yadif=3 & Slow Mcdeint (top fields)"
			echo "20 -> Yadif=3 & Slow Mcdeint (bottom fields)"
			echo "21 -> Yadif=1 & Slowest Mcdeint (top fields)"
			echo "22 -> Yadif=1 & Slowest Mcdeint (bottom fields)"
			echo "23 -> Yadif=3 & Slowest Mcdeint (top fields)"
			echo "24 -> Yadif=3 & Slowest Mcdeint (bottom fields)"
			echo "25 -> Tfields (top fields)"
			echo "26 -> Tfields (bottom fields)"
			echo "27 -> Tfields & Fast Mcdeint (top fields)"
			echo "28 -> Tfields & Fast Mcdeint (bottom fields)"
			echo "29 -> Tfields & Medium Mcdeint (top fields)"
			echo "30 -> Tfields & Medium Mcdeint (bottom fields)"
			echo "31 -> Tfields & Slow Mcdeint (top fields)"
			echo "32 -> Tfields & Slow Mcdeint (bottom fields)"
			echo "33 -> Tfields & Slowest Mcdeint (top fields)"
			echo "34 -> Tfields & Slowest Mcdeint (bottom fields)"
			echo ""
			brown "================= Frame Doubling Deinterlacers ==================="
			echo ""
			echo "35 -> Yadif @ double frame rate"
			echo "36 -> Yadif @ double frame rate (no spatial check)"
			echo "37 -> Yadif=1 & Fast Mcdeint @ double frame rate (top fields)"
			echo "38 -> Yadif=1 & Fast Mcdeint @ double frame rate (bottom fields)"
			echo "39 -> Yadif=3 & Fast Mcdeint @ double frame rate (top fields)"
			echo "40 -> Yadif=3 & Fast Mcdeint @ double frame rate (bottom fields)"
			echo "41 -> Yadif=1 & Medium Mcdeint @ double frame rate (top fields)"
			echo "42 -> Yadif=1 & Medium Mcdeint @ double frame rate (bottom fields)"
			echo "43 -> Yadif=3 & Medium Mcdeint @ double frame rate (top fields)"
			echo "44 -> Yadif=3 & Medium Mcdeint @ double frame rate (bottom fields)"
			echo "45 -> Yadif=1 & Slow Mcdeint @ double frame rate (top fields)"
			echo "46 -> Yadif=1 & Slow Mcdeint @ double frame rate (bottom fields)"
			echo "47 -> Yadif=3 & Slow Mcdeint @ double frame rate (top fields)"
			echo "48 -> Yadif=3 & Slow Mcdeint @ double frame rate (bottom fields)"
			echo "49 -> Yadif=1 & Slowest Mcdeint @ double frame rate (top fields)"
			echo "50 -> Yadif=1 & Slowest Mcdeint @ double frame rate (bottom fields)"
			echo "51 -> Yadif=3 & Slowest Mcdeint @ double frame rate (top fields)"
			echo "52 -> Yadif=3 & Slowest Mcdeint @ double frame rate (bottom fields)"
			echo "53 -> Tfields @ double frame rate (top fields)"
			echo "54 -> Tfields @ double frame rate (bottom fields)"
			echo "55 -> Tfields & Fast Mcdeint @ double frame rate (top fields)"
			echo "56 -> Tfields & Fast Mcdeint @ double frame rate (bottom fields)"
			echo "57 -> Tfields & Medium Mcdeint @ double frame rate (top fields)"
			echo "58 -> Tfields & Medium Mcdeint @ double frame rate (bottom fields)"
			echo "59 -> Tfields & Slow Mcdeint @ double frame rate (top fields)"
			echo "60 -> Tfields & Slow Mcdeint @ double frame rate (bottom fields)"
			echo "61 -> Tfields & Slowest Mcdeint @ double frame rate (top fields)"
			echo "62 -> Tfields & Slowest Mcdeint @ double frame rate (bottom fields)"
			echo "63 -> Skip deinterlacing"
			echo ""
			echo "Tip: Yadif is a good fast general purpose deinterlacer. If you"
			echo "     deal with sports, then the Linear blend deinterlacer may"
			echo "     be preferrable. Yadif & Mcdeint and Tfields & Mcdeint give"
			echo "     the best results but are pretty slow."
			echo ""
			printf "Select a Deinterlacing Filter [default is 7]: "
			read dfilter
			case "$dfilter" in
				0) deintfilter="pp=lb," ;;
				1) deintfilter="pp=li," ;;
				2) deintfilter="pp=ci," ;;
				3) deintfilter="pp=md," ;;
				4) deintfilter="pp=fd," ;;
				5) deintfilter="pp=l5," ;;
				6)
				printf "Specify the deinterlacing threshold [0-255 - default is 5]: "
				read kerntres
				if [ -z "$kerntres" ]; then
					deintfilter="kerndeint=5,"
				else
					deintfilter="kerndeint=$kerntres,"
				fi
				;;
				7|"") deintfilter="yadif=0,"; field_dominance="-field-dominance -1" ;;
				8) deintfilter="yadif=2,"; field_dominance="-field-dominance -1" ;;
				9) deintfilter="yadif=1,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
				10) deintfilter="yadif=1,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
				11) deintfilter="yadif=3,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
				12) deintfilter="yadif=3,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
				13) deintfilter="yadif=1,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
				14) deintfilter="yadif=1,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
				15) deintfilter="yadif=3,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
				16) deintfilter="yadif=3,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
				17) deintfilter="yadif=1,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
				18) deintfilter="yadif=1,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
				19) deintfilter="yadif=3,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
				20) deintfilter="yadif=3,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
				21) deintfilter="yadif=1,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
				22) deintfilter="yadif=1,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
				23) deintfilter="yadif=3,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
				24) deintfilter="yadif=3,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
				25) deintfilter="tfields=4,framestep=2,"; field_dominance="-field-dominance 0" ;;
				26) deintfilter="tfields=4,framestep=2,"; field_dominance="-field-dominance 1" ;;
				27) deintfilter="tfields=4,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
				28) deintfilter="tfields=4,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
				29) deintfilter="tfields=4,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
				30) deintfilter="tfields=4,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
				31) deintfilter="tfields=4,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
				32) deintfilter="tfields=4,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
				33) deintfilter="tfields=4,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
				34) deintfilter="tfields=4,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
				3[5-9]|4[0-9]|5[0-9]|6[0-2])
				quiet="2>/dev/null"
				case "$dfilter" in
					35) deintfilter="yadif=1,"; field_dominance="-field-dominance -1" ;;
					36) deintfilter="yadif=3,"; field_dominance="-field-dominance -1" ;;
					37) deintfilter="yadif=1,mcdeint=0:0:10,"; field_dominance="-field-dominance 0" ;;
					38) deintfilter="yadif=1,mcdeint=0:1:10,"; field_dominance="-field-dominance 1" ;;
					39) deintfilter="yadif=3,mcdeint=0:0:10,"; field_dominance="-field-dominance 0" ;;
					40) deintfilter="yadif=3,mcdeint=0:1:10,"; field_dominance="-field-dominance 1" ;;
					41) deintfilter="yadif=1,mcdeint=1:0:10,"; field_dominance="-field-dominance 0" ;;
					42) deintfilter="yadif=1,mcdeint=1:1:10,"; field_dominance="-field-dominance 1" ;;
					43) deintfilter="yadif=3,mcdeint=1:0:10,"; field_dominance="-field-dominance 0" ;;
					44) deintfilter="yadif=3,mcdeint=1:1:10,"; field_dominance="-field-dominance 1" ;;
					45) deintfilter="yadif=1,mcdeint=2:0:10,"; field_dominance="-field-dominance 0" ;;
					46) deintfilter="yadif=1,mcdeint=2:1:10,"; field_dominance="-field-dominance 1" ;;
					47) deintfilter="yadif=3,mcdeint=2:0:10,"; field_dominance="-field-dominance 0" ;;
					48) deintfilter="yadif=3,mcdeint=2:1:10,"; field_dominance="-field-dominance 1" ;;
					49) deintfilter="yadif=1,mcdeint=3:0:10,"; field_dominance="-field-dominance 0" ;;
					50) deintfilter="yadif=1,mcdeint=3:1:10,"; field_dominance="-field-dominance 1" ;;
					51) deintfilter="yadif=3,mcdeint=3:0:10,"; field_dominance="-field-dominance 0" ;;
					52) deintfilter="yadif=3,mcdeint=3:1:10,"; field_dominance="-field-dominance 1" ;;
					53) deintfilter="tfields=4,"; field_dominance="-field-dominance 0" ;;
					54) deintfilter="tfields=4,"; field_dominance="-field-dominance 1" ;;
					55) deintfilter="tfields=4,mcdeint=0:0:10,"; field_dominance="-field-dominance 0" ;;
					56) deintfilter="tfields=4,mcdeint=0:1:10,"; field_dominance="-field-dominance 1" ;;
					57) deintfilter="tfields=4,mcdeint=1:0:10,"; field_dominance="-field-dominance 0" ;;
					58) deintfilter="tfields=4,mcdeint=1:1:10,"; field_dominance="-field-dominance 1" ;;
					59) deintfilter="tfields=4,mcdeint=2:0:10,"; field_dominance="-field-dominance 0" ;;
					60) deintfilter="tfields=4,mcdeint=2:1:10,"; field_dominance="-field-dominance 1" ;;
					61) deintfilter="tfields=4,mcdeint=3:0:10,"; field_dominance="-field-dominance 0" ;;
					62) deintfilter="tfields=4,mcdeint=3:1:10,"; field_dominance="-field-dominance 1" ;;
				esac
				source_fps_func deinterlace
				case "$SOURCEFPS" in
					15.98[4-5]|15.98)
					deintfps="32000/1001"
					deintofps="32000/1001"
					green "-> Detected $SOURCEFPS FPS (Silent Film)"
					calc_fps_func
					echo ""
					;;
					17.982|17.98)
					deintfps="36000/1001"
					deintofps="36000/1001"
					green "-> Detected $SOURCEFPS FPS (Silent Film)"
					calc_fps_func
					echo ""
					;;
					24.000|24.00)
					green "-> Detected $SOURCEFPS FPS (Film)"
					calc_fps_func
					echo ""
					deintfps="48"
					deintofps="48"
					;;
					25.000|25.00)
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Film/Video)"
					calc_fps_func
					echo ""
					deintfps="50"
					deintofps="50"
					;;
					50.000|50.00)
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Double)"
					calc_fps_func
					echo ""
					deintfps="100"
					deintofps="100"
					;;
					100.000|100.00)
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Quad)"
					calc_fps_func
					echo ""
					deintfps="200"
					deintofps="200"
					;;
					23.976|23.97)
					green "-> Detected $SOURCEFPS FPS (NTSC Film)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="48000/1001"
					deintofps="48000/1001"
					;;
					29.970|29.97)
					set_manual=yes
					green "-> Detected $SOURCEFPS FPS (NTSC Video)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="60000/1001"
					deintofps="60000/1001"
					;;
					30.000|30.00)
					green "-> Detected $SOURCEFPS FPS (NTSC Video)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="60"
					deintofps="60"
					;;
					59.940|59.94)
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="120000/1001"
					deintofps="120000/1001"
					;;
					60.000|60.00)
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="120"
					deintofps="120"
					;;
					119.880|119.88)
					green "-> Detected $SOURCEFPS FPS (NTSC Quad)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="240000/1001"
					deintofps="240000/1001"
					;;
					""|*)
					green "-> Could not detect a supported frame rate!"
					green "-> You have to set it manually!"
					deint_custom_fps_func
					;;
				esac
				# Offer the user an option to set the
				# fps manually as detection of NTSC
				# is not very reliable! Damn the NTSC
				# crap!
				if [ "$set_manual" = "yes" ]; then
					printf "Continue (c) with the current setting or set FPS manually (m)? [c/m]: "
					read cfpsm
					case "$cfpsm" in
						c|C) true ;;
						m|M) deint_custom_fps_func ;;
						""|*) error "-> Option unknown or not specified!"; rmconf ;;
					esac
				fi
				;;
				63) false ;;
				*)
				error "-> Unknown deinterlacing option: '$dfilter'"
				rmconf
				;;
			esac
		fi
	elif [ "$int" = "n" -o "$int" = "N" -o -z "$int" ]; then
		interlacing=":nointerlacing"
		deintfilter=
		field_dominance=
		deintfps=
		deintofps=
	fi
}

# Video interlacing.
# Not fully functional yet,
# thus it's disabled at the
# moment.
video_interlace_func() {
	if [ -z "$deintfilter" -a "$interlacing" = ":nointerlacing" ]; then
		printf "Would you like to Interlace the encoding? [y/n]: "
		read intenc
		if [ "$intenc" = "y" -o "$intenc" = "Y" ]; then
			interlacing=":interlacing"
			echo ""
			brown "Interlace Field And Frame Orders"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "With the filters below, one can produce interlaced"
			echo "content out of progressive one. Note that only progressive"
			echo "PAL 50 and 100 fps and progressive NTSC 59.94 and 119.88"
			echo "fps content is supported as input! After the encoding is"
			echo "done, you will either have 25 or 50 fps interlaced PAL or"
			echo "29.97 or 59.94 fps interlaced NTSC encode."
			echo ""
			echo "0 -> Top field first order + odd frames output"
			echo "1 -> Top field first order + even frames output"
			echo "2 -> Bottom field first order + odd frames output"
			echo "3 -> Bottom field first order + even frames output"
			echo "4 -> Capture unknown/varying (auto) + odd frames output"
			echo "5 -> Capture unknown/varying (auto) + even frames output"
			echo "6 -> Auto-select by field flags + odd frames output"
			echo "7 -> Auto-select by field flags + even frames output"
			echo "8 -> Interleave even lines from even frames with odd"
			echo "     lines from odd frames"
			echo "9 -> Skip interlacing"
			echo ""
			printf "Select the Interlacing method [default is 1]: "
			read intmeth
			case "$intmeth" in
				0) intfilter=",phase=t,tinterlace=1" ;;
				1|"") intfilter=",phase=t,tinterlace=2" ;;
				2) intfilter=",phase=b,tinterlace=1" ;;
				3) intfilter=",phase=b,tinterlace=2" ;;
				4) intfilter=",phase=u,tinterlace=1" ;;
				5) intfilter=",phase=u,tinterlace=2" ;;
				6) intfilter=",phase=a,tinterlace=1" ;;
				7) intfilter=",phase=a,tinterlace=2" ;;
				8) intfilter=",tinterlace=4" ;;
				9) interlacing=":nointerlacing" ;;
				*)
				error "-> Unknown interlace option: '$intmeth'"
				rmconf
				;;
			esac
			case "$intmeth" in
				[0-8]|"")
				quiet="2>/dev/null"
				source_fps_func interlace
				case "$SOURCEFPS" in
					50.000|50.00)
					intfps="50"
					intofps="25"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Double)"
					calc_fps_func
					;;
					100.000|100.00)
					intfps="100"
					intofps="50"
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Quad)"
					calc_fps_func
					;;
					59.940|59.94)
					intfps="60000/1001"
					intofps="30000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					;;
					60.000|60.00)
					intfps="60"
					intofps="30"
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					;;
					119.880|119.88)
					intfps="120000/1001"
					intofps="60000/1001"
					green "-> Detected $SOURCEFPS FPS (NTSC Quad)"
					calc_fps_func
					;;
					"")
					error "-> Could not detect the source FPS value!"
					echo ""
					rmconf
					;;
					*)
					error "-> The detected source FPS ($SOURCEFPS) is not supported!"
					error "-> Supported frame rates are: 50/100/59.940/60/119.880 FPS"
					echo ""
					rmconf
					;;
				esac
				;;
			esac
		elif [ "$intenc" = "n" -o "$intenc" = "N" -o -z "$intenc" ]; then
			intfilter=
			intfps=
			intofps=
		fi
	else
		intfilter=
		intfps=
		intofps=
	fi
}

# Postprocessing
video_deblock_func() {
	printf "Would you like to Deblock/Dering the $source? [y/n]: "
	read db
	if [ "$db" = "y" -o "$db" = "Y" ]; then
		echo ""
		brown "Postprocessing Deblock/Dering Filters"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "The filters below have tunable parameters."
		echo "Higher values will filter the content more"
		echo "but can also introduce too much blurring"
		echo "and/or smear it. Note to only use deblocking"
		echo "filters if your $source shows blocking artifacts"
		echo ""
		echo "0 -> spp:  Simple postprocessing filter"
		echo "1 -> uspp: Ultra simple/slow postprocessing filter"
		echo "2 -> fspp: Fast simple postprocessing filter"
		echo "3 -> pp7:  Variant of spp with 7 points DCT"
		echo "4 -> ha/va/dr: Deblock/dering postprocessing filters"
		echo "5 -> ha/va: Deblock postprocessing filters"
		echo "6 -> dr: Dering postprocessing filter"
		echo "7 -> Skip the postprocessing filters" 
		echo ""
		printf "Select a Deblock/Dering filter [default is 0]: "
		read dbfilter
		case "$dbfilter" in
			0|"")
			printf "Specify the Quality level [0-6 - default is 3]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				dbql="3"
			else
				dbql="$dbqlevel"
			fi
			printf "Specify the Quantization parameter [0-32 - default is 0]: "
			read dbquant
			if [ -z "$dbquant" ]; then
				dbqp="0"
			else
				dbqp="$dbquant"
			fi
			deblockfilter="spp=$dbql:$dbqp,"
			;;
			1)
			printf "Specify the Quality level [0-8 - default is 2]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				dbql="2"
			else
				dbql="$dbqlevel"
			fi
			printf "Specify the Quantization parameter [0-32 - default is 0]: "
			read dbquant
			if [ -z "$dbquant" ]; then
				dbqp="0"
			else
				dbqp="$dbquant"
			fi
			deblockfilter="uspp=$dbql:$dbqp,"
			;;
			2)
			printf "Specify the Quality level [0-6 - default is 3]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				dbql="3"
			else
				dbql="$dbqlevel"
			fi
			printf "Specify the Quantization parameter [0-32 - default is 0]: "
			read dbquant
			if [ -z "$dbquant" ]; then
				dbqp="0"
			else
				dbqp="$dbquant"
			fi
			echo ""
			brown "FSPP Filter Strength"
			brown "~~~~~~~~~~~~~~~~~~~~"
			echo "With the filter strength, one can adjust"
			echo "the deblocking/deringing strength. Lower"
			echo "values mean more details but also more"
			echo "artifacts, while higher values make the"
			echo "image smoother but also blurrier."
			echo ""
			printf "Specify the fspp filter strength [-15-32 - default is 0]: "
			read fsppfs
			if [ -z "$fsppfs" ]; then
				fsppstrength="0"
			else
				fsppstrength="$fsppfs"
			fi
			deblockfilter="fspp=$dbql:$dbqp:$fsppstrength,"
			;;
			4)
			echo ""
			brown "ha/va/dr deblock/dering filters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "The 'ha' and 'va' filters are the old"
			echo "postprocessing deblock filters. Both share"
			echo "two threshold values. The first value is"
			echo "the difference factor where a higher value"
			echo "will do more deblocking. The second value"
			echo "is the flatness threshold where a lower"
			echo "value will do more deblocking. The 'dr'"
			echo "filter is the deringing filter. The format"
			echo "is as follows: difference:flatness"
			echo ""
			printf "Specify the Difference and Flatness values [default is 164:7]: "
			read dfv
			if [ -z "$dfv" ]; then
				dbvalues="164:7"
			else
				dbvalues="$dfv"
			fi
			deblockfilter="pp=ha:$dbvalues:c/va:c/dr:c,"
			;;
			5)
			echo ""
			brown "ha/va deblocking filters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "The 'ha' and 'va' filters are the old"
			echo "postprocessing deblock filters. Both share"
			echo "two threshold values. The first value is"
			echo "the difference factor where a higher value"
			echo "will do more deblocking. The second value"
			echo "is the flatness threshold where a lower"
			echo "value will do more deblocking. The format"
			echo "is as follows: difference:flatness"
			echo ""
			printf "Specify the Difference and Flatness values [default is 164:7]: "
			read dfv
			if [ -z "$dfv" ]; then
				dbvalues="164:7"
			else
				dbvalues="$dfv"
			fi
			deblockfilter="pp=ha:$dbvalues:c/va:c,"
			;;
			6)
			deblockfilter="pp=dr:c,"
			;;
			7) false ;;
			*)
			error "-> Unknown deblock/dering option: '$dbfilter'"
			rmconf
			;;
		esac
	elif [ "$db" = "n" -o "$db" = "N" -o -z "$db" ]; then
		deblockfilter=
	fi
}

# Denoising
video_denoise_func() {
	printf "Would you like to Denoise the $source? [y/n]: "
	read dn
	if [ "$dn" = "y" -o "$dn" = "Y" ]; then
		echo ""
		brown "Available Video Denoise Filters"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "All filters below have tunable parameters."
		echo "The higher the individual values are, the"
		echo "more filtering will be done."
		echo ""
		echo "0 -> 3D Denoise Filter (denoise3d)"
		echo "1 -> High-Quality 3D Denoise Filter (hqdn3d)"
		echo "2 -> Overcomplete Wavelet Denoiser (ow)"
		echo "3 -> Temporal Denoiser (tn)"
		echo "4 -> Skip denoising"
		echo ""
		printf "Select a Denoise filter [default is 1]: "
		read dnfilt
		case "$dnfilt" in
			0)
			echo ""
			brown "3D Denoise Filter"
			brown "~~~~~~~~~~~~~~~~~"
			echo "This filter aims to reduce image noise producing"
			echo "smooth images and making still images really still"
			echo "This also should enhance compressibility. There"
			echo "are 4 values you have to specify here:"
			echo ""
			echo "The Spatial Luma Strength"
			echo "The Spatial Chroma Strength"
			echo "The Temporal Luma Strength"
			echo "The Temporal Chroma Strength"
			echo ""
			echo "The higher the values are, the more filtering will"
			echo "be done."
			echo ""
			echo "Tip: with this filter, one can do only Spatial,"
			echo "only Temporal or Spatial and Temporal filtering."
			echo "For only Spatial filtering, just set the last two"
			echo "values to 0 (eg, 3:2:0:0). For only Temporal filtering"
			echo "set the first two values to 0 (eg, 0:0:3:2). For"
			echo "Spatial and Temporal filtering, use all values."
			echo ""
			printf "Specify the Denoise Filter Parameters [default is 2:1:2:1]: "
			read dfp
			if [ -z "$dfp" ]; then
				denoisefilter="denoise3d=2:1:2:1,"
			else
				denoisefilter="denoise3d=$dfp,"
			fi
			;;
			1|"")
			echo ""
			brown "High-Quality 3D Denoise Filter"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "This filter aims to reduce image noise producing"
			echo "smooth images and making still images really still"
			echo "This also should enhance compressibility. There"
			echo "are 4 values you have to specify here:"
			echo ""
			echo "The Spatial Luma Strength"
			echo "The Spatial Chroma Strength"
			echo "The Temporal Luma Strength"
			echo "The Temporal Chroma Strength"
			echo ""
			echo "The higher the values are, the more filtering will"
			echo "be done."
			echo ""
			echo "Tip: with this filter, one can do only Spatial,"
			echo "only Temporal or Spatial and Temporal filtering."
			echo "For only Spatial filtering, just set the last two"
			echo "values to 0 (eg, 3:2:0:0). For only Temporal filtering"
			echo "set the first two values to 0 (eg, 0:0:3:2). For"
			echo "Spatial and Temporal filtering, use all values."
			echo ""
			printf "Specify the Denoise Filter Parameters [default is 2:1:2:1]: "
			read dfp
			if [ -z "$dfp" ]; then
				denoisefilter="hqdn3d=2:1:2:1,"
			else
				denoisefilter="hqdn3d=$dfp,"
			fi
			;;
			2)
			echo ""
			brown "Overcomplete Wavelet Denoiser"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "This filter belongs to the new generation of"
			echo "denoisers which use wavelets to denoise the"
			echo "video content. The filter has three parameters"
			echo ""
			echo "Depth (integer)"
			echo "Luma Strength (integer/float)"
			echo "Chroma Strength (integer/float)"
			echo ""
			echo "Larger depth values will denoise lower frequency"
			echo "components more, but will slow down filtering."
			echo "The format is as follows: depth:luma:chroma"
			echo ""
			printf "Specify the Denoise Filter Parameters [default is 3:1.0:1.0]: "
			read dfp
			if [ -z "$dfp" ]; then
				denoisefilter="ow=3:1.0:1.0,"
			else
				denoisefilter="ow=$dfp,"
			fi
			;;
			3)
			echo ""
			brown "Temporal Denoiser"
			brown "~~~~~~~~~~~~~~~~~"
			echo "This is a temporal denoiser (without motion"
			echo "compensation) which aims to reduce image"
			echo "noise in the video content. It has three"
			echo "thresholds. The higher the values, the more"
			echo "filtering will be done. The format is as"
			echo "follows: threshold1:threshold2:threshold3"
			echo ""
			echo "Note that the second value should be lesser"
			echo "than or equal to the first one, and the"
			echo "third value should be lesser than or equal"
			echo "to the second value."
			echo ""
			printf "Specify the Denoise Filter Parameters [default is 64:128:256]: "
			read dfp
			if [ -z "$dfp" ]; then
				denoisefilter="pp=tn:64:128:256:c,"
			else
				denoisefilter="pp=tn:$dfp:c,"
			fi
			;;
			4) false ;;
			*)
			error "-> Unknown denoise option: '$dnfilt'"
			rmconf
			;;
		esac
	elif [ "$dn" = "n" -o "$dn" = "N" -o -z "$dn" ]; then
		denoisefilter=
	fi
}

# Video noise function.
# Mutually exclusive with
# the denoise function.
video_noise_func() {
	if [ -z "$dn" -o "$dn" = "n" -o "$dn" = "N" ]; then
		printf "Would you like to add Noise to the $source? [y/n]: "
		read addnoise
		if [ "$addnoise" = "y" -o "$addnoise" = "Y" ]; then
			echo ""
			brown "Video Noise Filter"
			brown "~~~~~~~~~~~~~~~~~~"
			echo "With the 'noise' filter one can add noise"
			echo "to the video content in case the content"
			echo "looks too unnatural or has been denoised"
			echo "too strong. The 'noise' filter can operate"
			echo "only on the Luma (light) components, only"
			echo "on the Chroma (color) components, or on"
			echo "both at the same time. The filter also uses"
			echo "different types of noise patterns. It is"
			echo "recommended to use small values or the"
			echo "image will become too noisy."
			echo ""
			echo "0 --> Luma + Uniform noise pattern"
			echo "1 --> Luma + Temporal noise pattern"
			echo "2 --> Luma + Averaged temporal noise pattern"
			echo "3 --> Luma + High-quality noise pattern"
			echo "4 --> Luma + Random noise pattern"
			echo "5 --> Chroma + Uniform noise pattern"
			echo "6 --> Chroma + Temporal noise pattern"
			echo "7 --> Chroma + Averaged temporal noise pattern"
			echo "8 --> Chroma + High-quality noise pattern"
			echo "9 --> Chroma + Random noise pattern"
			echo "10 -> Luma & Chroma + Uniform noise pattern"
			echo "11 -> Luma & Chroma + Temporal noise pattern"
			echo "12 -> Luma & Chroma + Averaged temporal noise pattern"
			echo "13 -> Luma & Chroma + High-quality noise pattern"
			echo "14 -> Luma & Chroma + Random noise pattern"
			echo "15 -> Skip adding noise"
			echo ""
			printf "Select the Noise filter mode and pattern [default is 1]: "
			read nfmp
			case "$nfmp" in
				[0-4]|"")
				printf "Specify the amount of Luma noise to add [0-100 - default is 0]: "
				read lnoise
				if [ -z "$lnoise" ]; then
					lumanoise="0"
				else
					lumanoise="$lnoise"
				fi
				case "$nfmp" in
					0) noisefilter=",noise=${lumanoise}u:0u" ;;
					1|"") noisefilter=",noise=${lumanoise}t:0t" ;;
					2) noisefilter=",noise=${lumanoise}a:0a" ;;
					3) noisefilter=",noise=${lumanoise}h:0h" ;;
					4) noisefilter=",noise=${lumanoise}p:0p" ;;
				esac
				;;
				[5-9])
				printf "Specify the amount of Chroma noise to add [0-100 - default is 0]: "
				read cnoise
				if [ -z "$cnoise" ]; then
					chromanoise="0"
				else
					chromanoise="$cnoise"
				fi
				case "$nfmp" in
					5) noisefilter=",noise=0u:${chromanoise}u" ;;
					6) noisefilter=",noise=0t:${chromanoise}t" ;;
					7) noisefilter=",noise=0a:${chromanoise}a" ;;
					8) noisefilter=",noise=0h:${chromanoise}h" ;;
					9) noisefilter=",noise=0p:${chromanoise}p" ;;
				esac
				;;
				1[0-4])
				printf "Specify the amount of Luma noise to add [0-100 - default is 0]: "
				read lnoise
				if [ -z "$lnoise" ]; then
					lumanoise="0"
				else
					lumanoise="$lnoise"
				fi
				printf "Specify the amount of Chroma noise to add [0-100 - default is 0]: "
				read cnoise
				if [ -z "$cnoise" ]; then
					chromanoise="0"
				else
					chromanoise="$cnoise"
				fi
				case "$nfmp" in
					10) noisefilter=",noise=${lumanoise}u:${chromanoise}u" ;;
					11) noisefilter=",noise=${lumanoise}t:${chromanoise}t" ;;
					12) noisefilter=",noise=${lumanoise}a:${chromanoise}a" ;;
					13) noisefilter=",noise=${lumanoise}h:${chromanoise}h" ;;
					14) noisefilter=",noise=${lumanoise}p:${chromanoise}p" ;;
				esac
				;;
				15) false ;;
				*)
				error "-> Unknown noise filter mode and noise pattern: '$nfmp'"
				rmconf
				;;
			esac
		elif [ "$addnoise" = "n" -o "$addnoise" = "N" -o -z "$addnoise" ]; then
			noisefilter=
		fi
	else
		noisefilter=
	fi
}

# (Un)sharp mask/gaussian blur
# video filter
video_unsharp_func() {
	printf "Would you like to Sharpen or Blur the $source? [y/n]: "
	read sharpblur
	if [ "$sharpblur" = "y" -o "$sharpblur" = "Y" ]; then
		echo ""
		brown "(Un)sharp Mask/Gaussian Blur Video Filter"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "With the '(un)sharp mask / gaussian blur' filter"
		echo "one can sharpen or blur the content. The filter"
		echo "can operate only on the Luma (light) components,"
		echo "only on the Chroma (color) components or on both"
		echo "at the same time. It is recommended to use very"
		echo "small values or the content will become too sharp"
		echo "or too blurry. The sane range for the amount of blur"
		echo "or sharpness to add to the image is between -1.50 and"
		echo "1.50. Negative values will blur the image, positive"
		echo "values will sharpen the image. A value of 0.00 (or 0"
		echo "or 0.0) will disable filtering. The filter also uses"
		echo "an odd-sized matrix which defines its operating area"
		echo "in width and height. Below are the recommended"
		echo "matrices one can choose from. Small matrix sizes"
		echo "are usually better, but this depends on the source."
		echo ""
		echo "0 -> Luma 3x3 matrix     6 --> Chroma 3x3 matrix"
		echo "1 -> Luma 5x5 matrix     7 --> Chroma 5x5 matrix"
		echo "2 -> Luma 7x7 matrix     8 --> Chroma 7x7 matrix"
		echo "3 -> Luma 9x9 matrix     9 --> Chroma 9x9 matrix"
		echo "4 -> Luma 11x11 matrix   10 -> Chroma 11x11 matrix"
		echo "5 -> Luma 13x11 matrix   11 -> Chroma 13x11 matrix"
		echo ""
		echo "         12 -> Luma & Chroma 3x3 matrix"
		echo "         13 -> Luma & Chroma 5x5 matrix"
		echo "         14 -> Luma & Chroma 7x7 matrix"
		echo "         15 -> Luma & Chroma 9x9 matrix"
		echo "         16 -> Luma & Chroma 11x11 matrix"
		echo "         17 -> Luma & Chroma 13x11 matrix"
		echo "         18 -> Skip sharpen/blur"
		echo ""
		printf "Select the Filtering Mode and Matrix Size [default is 12]: "
		read fmms
		case "$fmms" in
			[0-5])
			printf "Specify the amount of Luma filtering [default is 0.00]: "
			read lumafilt
			if [ -z "$lumafilt" ]; then
				lumavalue="0.00"
			else
				lumavalue="$lumafilt"
			fi
			case "$fmms" in
				0) unsharpfilter=",unsharp=l3x3:$lumavalue" ;;
				1) unsharpfilter=",unsharp=l5x5:$lumavalue" ;;
				2) unsharpfilter=",unsharp=l7x7:$lumavalue" ;;
				3) unsharpfilter=",unsharp=l9x9:$lumavalue" ;;
				4) unsharpfilter=",unsharp=l11x11:$lumavalue" ;;
				5) unsharpfilter=",unsharp=l13x11:$lumavalue" ;;
			esac
			;;
			[6-9]|1[0-1])
			printf "Specify the amount of Chroma filtering [default is 0.00]: "
			read chromafilt
			if [ -z "$chromafilt" ]; then
				chromavalue="0.00"
			else
				chromavalue="$chromafilt"
			fi
			case "$fmms" in
				6) unsharpfilter=",unsharp=c3x3:$chromavalue" ;;
				7) unsharpfilter=",unsharp=c5x5:$chromavalue" ;;
				8) unsharpfilter=",unsharp=c7x7:$chromavalue" ;;
				9) unsharpfilter=",unsharp=c9x9:$chromavalue" ;;
				10) unsharpfilter=",unsharp=c11x11:$chromavalue" ;;
				11) unsharpfilter=",unsharp=c13x11:$chromavalue" ;;
			esac
			;;
			1[2-7]|"")
			printf "Specify the amount of Luma filtering [default is 0.00]: "
			read lumafilt
			if [ -z "$lumafilt" ]; then
				lumavalue="0.00"
			else
				lumavalue="$lumafilt"
			fi
			printf "Specify the amount of Chroma filtering [default is 0.00]: "
			read chromafilt
			if [ -z "$chromafilt" ]; then
				chromavalue="0.00"
			else
				chromavalue="$chromafilt"
			fi
			case "$fmms" in
				12|"") unsharpfilter=",unsharp=l3x3:$lumavalue:c3x3:$chromavalue" ;;
				13) unsharpfilter=",unsharp=l5x5:$lumavalue:c5x5:$chromavalue" ;;
				14) unsharpfilter=",unsharp=l7x7:$lumavalue:c7x7:$chromavalue" ;;
				15) unsharpfilter=",unsharp=l9x9:$lumavalue:c9x9:$chromavalue" ;;
				16) unsharpfilter=",unsharp=l11x11:$lumavalue:c11x11:$chromavalue" ;;
				17) unsharpfilter=",unsharp=l13x11:$lumavalue:c13x11:$chromavalue" ;;
			esac
			;;
			18) false ;;
			*)
			error "-> Unknown filtering mode and matrix option: '$fmms'"
			rmconf
			;;
		esac
	elif [ "$sharpblur" = "n" -o "$sharpblur" = "N" -o -z "$sharpblur" ]; then
		unsharpfilter=
	fi
}

# Automatic brightness/contrast
# control function
video_brightness_func() {
	printf "Would you like to use Automatic Brightness/Contrast? [y/n]: "
	read abc
	if [ "$abc" = "y" -o "$abc" = "Y" ]; then
		echo ""
		brown "Automatic Brightness/Contrast Control"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Luminance-only control"
		echo "1 -> Chrominance-only control"
		echo "2 -> Luminance & Chrominance control"
		echo "3 -> Skip brightness/contrast control"
		echo ""
		printf "Select the Automatic brightness/contrast control [default is 2]: "
		read abcc
		case "$abcc" in
			0) brightnessfilter="pp=al:y," ;;
			1) brightnessfilter="pp=al:n," ;;
			2|"") brightnessfilter="pp=al:c," ;;
			3) false ;;
			*)
			error "-> Unknown brightness/contrast option: '$abcc'"
			rmconf
			;;
		esac
	elif [ "$abc" = "n" -o "$abc" = "N" -o -z "$abc" ]; then
		brightnessfilter=
	fi
}

# Colorspace conversion. Can only
# be used when the user is scaling
# the content as this filter needs
# the 'scale' filter to do the real
# colorspace conversion. Don't ask
# for colorspace conversion if we
# use a deinterlacer or if
# interlacing progressive content
# as it does not work with these
# filters
video_colorspace_func() {
	if [ -z "$deintfilter" -a -z "$intfilter" ]; then
		printf "Would you like to perform a Colorspace conversion? [y/n]: "
		read csconv
		if [ "$csconv" = "y" -o "$csconv" = "Y" ]; then
			echo ""
			brown "Colorspace Formats"
			brown "~~~~~~~~~~~~~~~~~~"
			echo "0 --> 444P (YUV444P - Planar)"
			echo "1 --> 422P (YUV422P - Planar)"
			echo "2 --> 411P (YUV411P - Planar)"
			echo "3 --> YUY2 (YUYV422 - Packed)"
			echo "4 --> UYVY (UYVY422 - Packed)"
			echo "5 --> YVU9 (YUV410P - Planar)"
			echo "6 --> IF09 (YUV410P - Planar)"
			echo "7 --> YV12 (YUV420P - Planar)"
			echo "8 --> I420 (YUV420P - Planar)"
			echo "9 --> Y800 (Gray - Planar)"
			echo "10 -> Skip colorspace conversion"
			echo ""
			printf "Select a Colorspace format [default is 7]: "
			read csp
			case "$csp" in
				0) colorspacefilter="format=444p," ;;
				1) colorspacefilter="format=422p," ;;
				2) colorspacefilter="format=411p," ;;
				3) colorspacefilter="format=yuy2," ;;
				4) colorspacefilter="format=uyvy," ;;
				5) colorspacefilter="format=yvu9," ;;
				6) colorspacefilter="format=if09," ;;
				7|"") colorspacefilter= ;;
				8) colorspacefilter="format=i420," ;;
				9) colorspacefilter="format=y800," ;;
				10) false ;;
				*)
				error "-> Unknown colorspace option: '$csp'"
				rmconf
				;;
			esac
		elif [ "$csconv" = "n" -o "$csconv" = "N" -o -z "$csconv" ]; then
			colorspacefilter=
		fi
	else
		colorspacefilter=
	fi
}

# Subtitles
video_subtitles_func() {
	printf "Would you like to include/rip a Subtitle? [y/n]: "
	read sub
	if [ "$sub" = "y" -o "$sub" = "Y" ]; then
		echo ""
		green "-> Scanning for subtitles..."
		mplayer "$sourcetype" $device -nosound -vo null -frames 1 -nocache 2>/dev/null > $CONFIGDIR/subs
		SUBS=$(grep "^subtitle" $CONFIGDIR/subs)
		rm -f $CONFIGDIR/subs
		echo ""
		brown "Available Subtitles On Disc"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		if [ ! -z "$SUBS" ]; then
			echo "$SUBS" | sed -e 's/^subtitle //g' -e 's/( sid ):/Subtitle ID:/g' -e 's/language:/- Language:/g'
		else
			green "-> No subtitles available or failed to detect them!"
		fi
		echo ""
		printf "Specify the Subtitle ID number [press 'Enter' to skip]: "
		read subid
		if [ ! -z "$(echo $subid | grep '[a-zA-Z]')" ]; then
			error "-> You have to specify the Subtitle ID number, not the language code!"
			rmconf
		fi
		if [ -z "$subid" ]; then
			sid=
		else
			sid="-sid $subid"
		fi
		if [ ! -z "$sid" ]; then
			echo ""
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "0 -> Hardcode the subtitle into the movie"
			echo "1 -> Dump the subtitle to a file on disk"
			echo ""
			printf "Select the Subtitle Method [default is 1]: "
			read sub_method
			case "$sub_method" in
				0)
				vobsubout=
				echo ""
				brown "Subtitle Anti-Aliasing Modes"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				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
				if [ "$(echo $spuaa | awk '{print $2}')" = "4" ]; then
					printf "Specify the Gaussian Variance [0.0-3.0 - default is 0.7]: "
					read gaussvar
					if [ -z "$gaussvar" ]; then
						spugauss="-spugauss 0.7"
					else
						spugauss="-spugauss $gaussvar"
					fi
				else
					spugauss=
				fi
				echo ""
				brown "Subtitles Alignment"
				brown "~~~~~~~~~~~~~~~~~~~"
				echo "0 -> Original position"
				echo "1 -> Align at top (original behavior)"
				echo "2 -> Align at center"
				echo "3 -> Align at bottom"
				echo "4 -> Skip subtitle alignment"
				echo ""
				printf "Select the Subtitle Alignment [default is 0]: "
				read subalign
				case "$subalign" in
					0|"") spualign="-spualign -1" ;;
					1) spualign="-spualign 0" ;;
					2) spualign="-spualign 1" ;;
					3) spualign="-spualign 2" ;;
					4) false ;;
					*)
					error "-> Unknown subtitle alignment option: '$subalign'"
					rmconf
					;;
				esac
				;;
				1|"")
				# The IDXFILE variable is also used to
				# import the subtitle into the MKV/MP4
				# containers!
				IDXFILE=$(echo "$OUTPUT" | sed 's|\.avi|\.idx|')
				SUBFILE=$(echo "$OUTPUT" | sed 's|\.avi|\.sub|')
				test -e "$IDXFILE" && mv -f "$IDXFILE" "$IDXFILE.old"
				test -e "$SUBFILE" && mv -f "$SUBFILE" "$SUBFILE.old"
				vobsubout="-vobsubout $(echo \"$OUTPUT\" | sed 's|\.avi||') -vobsuboutindex 0"
				spualign=
				spuaa=
				spugauss=
				;;
				*)
				error "-> Unknown subtitle method option: '$sub_method'"
				rmconf
				;;
			esac
		else
			vobsubout=
			spuaa=
			spualign=
			spugauss=
		fi
	elif [ "$sub" = "n" -o "$sub" = "N" -o -z "$sub" ]; then
		sid=
		vobsubout=
		spuaa=
		spualign=
		spugauss=
	fi
}

# Video cropping
video_crop_func() {
	printf "Would you like to Crop the $source? [y/n]: "
	read cropping
	if [ "$cropping" = "y" -o "$cropping" = "Y" ]; then
		echo ""
		green "-> Detecting crop values with 'cropdetect'..."
		mplayer "$sourcetype" $device $vid -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/cropdetect
		VLENGTH=$(grep "^ID_LENGTH" $CONFIGDIR/cropdetect | cut -f '2' -d '=' | cut -f '1' -d '.')
		#GETCROP=$(mplayer "$sourcetype" $device $vid -vf cropdetect -nosound -vo null -frames 30 -sstep $(($VLENGTH/30)) -nocache 2>/dev/null | tr '\r' '\n' | grep "crop=" | tail -1 | awk '{print $9}' | sed 's/crop=//g; s/).//g')
		GETCROP=$(mplayer "$sourcetype" $device $vid -vf cropdetect -nosound -nocache -frames 500 -vo null -ss $(($VLENGTH/2)) 2>/dev/null | tr '\r' '\n' | grep "crop=" | tail -1 | awk '{print $9}' | sed 's/crop=//g; s/).//g')
		rm -f $CONFIGDIR/cropdetect
		if [ ! -z "$GETCROP" ]; then
			green "-> Found crop values: $GETCROP"
		else
			green "-> Failed to get the crop values!"
			green "-> You have to specify them yourself!"
			green "-> 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
			cropfilter=
		else
			if [ -z "$cropvalues" ]; then
				cropfilter="crop=$GETCROP,"
				crop_preview="$GETCROP"
			else
				cropfilter="crop=$cropvalues,"
				crop_preview="$cropvalues"
			fi
			printf "Preview the crop values for 15 seconds? [y/n]: "
			read precrop
			if [ "$precrop" = "y" -o "$precrop" = "Y" ]; then
				printf "Specify the start position in hour:min:sec [default is 0:02:00]: "
				read timepos
				if [ -z "$timepos" ]; then
					startpos="0:02:00"
				else
					startpos="$timepos"
				fi
				mplayer "$sourcetype" $device $vid -vf rectangle=$crop_preview -nocache -nosound -ss $startpos >/dev/null 2>&1 & PID=$!; sleep 15; kill -KILL $PID;
			elif [ "$precrop" = "n" -o "$precrop" = "N" -o -z "$precrop" ]; then
				false
			fi
		fi
	elif [ "$cropping" = "n" -o "$cropping" = "N" -o -z "$cropping" ]; then
		cropfilter=
		GETCROP=
	fi
}

calcbits() {
	echo "scale=3; $1" | bc -l | sed 's@^\.@0\.@'
}

# Bits per pixel calculation
# Not supported by fixed-quant!
#
#
#         $videobitrate * 1000
# $bpp = -----------------------
#        $width * $height * $fps
#
bits_per_pixel_func() {
	if [ "$vres" = "$GETRES" -o -z "$vres" ]; then
		WIDTH=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $2}')
	else
		WIDTH=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $2}')
	fi
	if [ -z "$ofps" ]; then
		VIDFPS="$GETFPS"
	else
		VIDFPS="$(echo $ofps | awk '{print $2}')"
	fi
	if [ "$calcvidbit" = "y" -o "$calcvidbit" = "Y" ]; then
		BPP=$(calcbits "$EST_BITRATE*1000/($WIDTH*$HEIGHT*$VIDFPS)")
	elif [ "$calcvidbit" = "n" -o "$calcvidbit" = "N" -o -z "$calcvidbit" ]; then
		echo ""
		green "-> Bits Per Pixel value: $(calcbits "$(echo $vbitrate | awk -F= '{print $2}')*1000/($WIDTH*$HEIGHT*$VIDFPS)") bpp"
	fi
}

# Bits per block calculation
# Not supported by fixed-quant!
#
# MPEG type compression breaks each
# frame into many smaller 16x16 blocks
# and assigns a quantizer to each one
# of them. The below formula can be
# used to calculate how many bits
# each one of these blocks gets
#
#                      $videobitrate * 1000
# $bpb = ---------------------------------------------------
#        $(($fps * $(($(($width * $height))/$((16 * 16))))))
#
bits_per_block_func() {
	if [ "$vres" = "$GETRES" -o -z "$vres" ]; then
		WIDTH=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $2}')
	else
		WIDTH=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $vres | tr '[:alpha:]' ' ' | awk '{print $2}')
	fi
	if [ -z "$ofps" ]; then
		VIDFPS="$GETFPS"
	else
		VIDFPS="$(echo $ofps | awk '{print $2}')"
	fi
	if [ "$calcvidbit" = "y" -o "$calcvidbit" = "Y" ]; then
		BPB=$(calcbits "$EST_BITRATE*1000/($VIDFPS*($WIDTH*$HEIGHT)/(16*16))")
	elif [ "$calcvidbit" = "n" -o "$calcvidbit" = "N" -o -z "$calcvidbit" ]; then
		green "-> Bits Per Block value: $(calcbits "$(echo $vbitrate | awk -F= '{print $2}')*1000/($VIDFPS*($WIDTH*$HEIGHT)/(16*16))") bpb"
	fi
}

# Custom matrics for quality presets
# and manual codec configuration
custom_matrix_func() {
	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 -e intrafile
		if [ -z "$(echo "$intrafile" | grep '^/')" ]; then
			error "-> You have to provide the full path to the file!"
			rmconf
		fi
		if [ ! -f "$intrafile" ]; then
			error "-> No such file: '$intrafile'"
			rmconf
		fi
		intramatrix=":quant_intra_matrix=$intrafile"
		printf "Provide the Inter Matrix file: "
		read -e interfile
		if [ -z "$(echo "$interfile" | grep '^/')" ]; then
			error "-> You have to provide the full path to the file!"
			rmconf
		fi
		if [ ! -f "$interfile" ]; then
			error "-> No such file: '$interfile'"
			rmconf
		fi
		intermatrix=":quant_inter_matrix=$interfile"
	elif [ "$iim" = "n" -o "$iim" = "N" -o -z "$iim" ]; then
		intramatrix=
		intermatrix=
	fi
}

# Set output filename.
set_output_filename_func() {
	case "$vtype" in
		file|FILE|File)
		printf "Provide a name for the Output File [default is $HOME/Xvid-$$.avi]: "
		read -e outfile
		if [ -z "$outfile" ]; then
			OUTPUT="$HOME/Xvid-$$.avi"
		else
			if [ -z "$(echo "$outfile" | grep '^/')" ]; then
				error "-> You have to specify the full path!"
				rmconf
			fi
			if [ -z "$(echo "$outfile" | grep '\.avi')" ]; then
				error "-> You have to use the '.avi' extension for the output file!"
				rmconf
			fi
			OUTPUT="$outfile"
		fi
		;;
		dvd|DVD|Dvd)
		green "-> Scanning for DVD title name..."
		GET_TITLE=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep '^Disc Title:' | sed 's/Disc Title: //')
		SET_TITLE=$(echo "$GET_TITLE" | sed 's/_/ /g')
		echo ""
		if [ ! -z "$GET_TITLE" ]; then
			printf "Provide a name for the Output File [default is $HOME/$SET_TITLE.avi]: "
			read -e outfile
			if [ -z "$outfile" ]; then
				OUTPUT="$HOME/$SET_TITLE.avi"
			else
				if [ -z "$(echo "$outfile" | grep '^/')" ]; then
					error "-> You have to specify the full path!"
					rmconf
				fi
				if [ -z "$(echo "$outfile" | grep '\.avi')" ]; then
					error "-> You have to use the '.avi' extension for the output file!"
					rmconf
				fi
				OUTPUT="$outfile"
			fi
		else
			printf "Provide a name for the Output File [default is $HOME/Xvid-$$.avi]: "
			read -e outfile
			if [ -z "$outfile" ]; then
				OUTPUT="$HOME/Xvid-$$.avi"
			else
				if [ -z "$(echo "$outfile" | grep '^/')" ]; then
					error "-> You have to specify the full path!"
					rmconf
				fi
				if [ -z "$(echo "$outfile" | grep '\.avi')" ]; then
					error "-> You have to use the '.avi' extension for the output file!"
					rmconf
				fi
				OUTPUT="$outfile"
			fi
		fi
		;;
	esac
	test -e "$OUTPUT" && mv -f "$OUTPUT" "$OUTPUT.old"
	if [ ! -d "$(dirname "$OUTPUT")" ]; then
		mkdir -p "$(dirname "$OUTPUT")" 2>/dev/null
		if [ $? != 0 ]; then
			error "-> Failed to create the destination directory!"
			error "-> Maybe a permissions problem?"
			rmconf
		fi
	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
# or MP4, just play it safe and check
# if it's < 4 GB
# Do the same for the $CONFIGDIR directory
# since it will be used to store temporary
# files when converting from AVI -> MP4

check_diskspace_func() {
	HDOUT="$(df -m "$(dirname "$OUTPUT")" | tail -1 | sed -r 's/^.*\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+[0-9]+%.*/\1/')"
	HDCONF="$(df -m $CONFIGDIR | tail -1 | sed -r 's/^.*\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+[0-9]+%.*/\1/')"
	if [ $HDOUT -le 4096 -o $HDCONF -le 4096 ]; then
		echo ""
		echo "Note that you are running out of disk space in"
		echo "the destination output directory and/or in the"
		echo "configuration directory of xvidenc!"
		echo ""
		echo "This could be a problem if you want to convert"
		echo "the final encode to Matroska, OGM or to the MP4"
		echo "container. It is recommended to free up some disk"
		echo "space or provide a different destination output"
		echo "directory before continuing with the encoding"
		echo "process if you intend to do some of the above"
		echo "tasks!"
		echo ""
		error "Space left over in '$(dirname "$OUTPUT")': $HDOUT MB"
		error "Space left over in '$CONFIGDIR': $HDCONF MB"
		echo ""
		printf "#### Press 'Enter' to continue, CTRL+C to exit ####"
		read continue_encoding
		case "$vtype" in
			file|FILE|File) echo "" ;;
		esac
	fi
}

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

clear
echo ""
brown "+==================================================================+"
brown "|<<<<<<<<<< xvidenc - the interactive shell script ripper >>>>>>>>>|"
brown "|------------------------------------------------------------------|"
brown "|<<<<<<<< version: $version - (C) 2006-2008 Grozdan Nikolov >>>>>>>>>>|"
brown "+==================================================================+"
echo ""
echo ""


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"
	chapters=
	dvdangle=
	printf "Provide the Input Video File: "
	read -e infile
	if [ -z "$(echo "$infile" | grep '^/')" ]; then
		error "-> You have to provide the full path to the input video file!"
		rmconf
	fi
	if [ ! -f "$infile" ]; then
		error "-> No such file: '$infile'"
		rmconf
	fi
	set_output_filename_func
	check_diskspace_func
	sourcetype="$infile"
	if [ "$sourcetype" = "$OUTPUT" ]; then
		error "-> You cannot use the same name for the input and output file!"
		rmconf
	fi
	# Scan to see if input file has
	# more than one video stream
	printf "Scan for multiple video streams? [y/n]: "
	read mvs
	if [ "$mvs" = "y" -o "$mvs" = "Y" ]; then
		echo ""
		green "-> Scanning for video streams..."
		mplayer "$sourcetype" -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/videostreams
		if [ $(grep '^ID_VIDEO_ID' $CONFIGDIR/videostreams | wc -l) -lt 2 ]; then
			vid=
			green "-> Found only one video stream"
			green "-> Skipping stream selection"
			echo ""
		else
			echo ""
			for i in $(grep '^ID_VIDEO_ID' $CONFIGDIR/videostreams); do
				echo "$(echo "Video stream: $(echo $i | awk -F= '{print $2}')")"
			done
			echo ""
			VIDSTREAM=$(grep '^ID_VIDEO_ID' $CONFIGDIR/videostreams | awk -F= '{print $2}')
			printf "Specify the video stream number for encoding [default is $(echo $VIDSTREAM | awk '{print $1}')]: "
			read vidstream
			if [ -z "$vidstream" ]; then
				vid="-vid 0"
			else
				vid="-vid $vidstream"
			fi
		fi
		rm -f $CONFIGDIR/videostreams
	elif [ "$mvs" = "n" -o "$mvs" = "N" -o -z "$mvs" ]; then
		vid=
	fi
	printf "Would you like to use Pre/Postprocessing video filters? [y/n]: "
	read vfilters
	if [ "$vfilters" = "y" -o "$vfilters" = "Y" ]; then
		echo ""
		brown "+==================================+"
		brown "| Pre/Postprocessing Video Filters |"
		brown "+==================================+"
		echo ""
		video_deinterlace_func
		video_interlace_func
		video_deblock_func
		video_denoise_func
		video_noise_func
		video_unsharp_func
		video_brightness_func
	elif [ "$vfilters" = "n" -o "$vfilters" = "n" -o -z "$vfilters" ]; then
		interlacing=":nointerlacing"
	fi
	video_crop_func
	video_subtitles_func
	;;
	dvd|DVD|Dvd)
	source=DVD
	vid=
	if [ ! -x "$(which lsdvd 2>/dev/null)" ]; then
		error "-> Checking for lsdvd... FAILED!"
		rmconf
	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
				green "-> Found device: /dev/$i"
			done
		fi
	fi
	if [ -L /dev/dvd ]; then
		green "-> 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 -e dev
	if [ -z "$dev" ]; then
		device="-dvd-device /dev/dvd"
	else
		if [ -z "$(echo "$dev" | grep '^/')" ]; then
			error "-> You have to provide the full path to the DVD device!"
			rmconf
		fi
		device="-dvd-device $dev"
	fi
	if [ ! -e "$(echo $device | awk '{print $2}')" ]; then
		error "-> No such device: '$(echo $device | awk '{print $2}')'"
		rmconf
	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 ""
	green "-> Unlocking the DVD disc..."
	mplayer dvd://1 $device -nosound -vo null -frames 1 -nocache >/dev/null 2>&1
	set_output_filename_func
	check_diskspace_func
	echo ""
	green "-> Scanning for DVD titles..."
	lsdvd $(echo $device | awk '{print $2}') 2>/dev/null > $CONFIGDIR/dvdtitles
	ALLTITLES=$(grep '^Title' $CONFIGDIR/dvdtitles | awk '{print $1,$2,$3,$4}' | sed 's/,/ -/g' | cut -f '1' -d '.')
	DVDTITLE=$(grep 'Longest' $CONFIGDIR/dvdtitles | awk '{print $3}' | sed 's/^0//')
	TOTAL_TITLES=$(grep '^Title' $CONFIGDIR/dvdtitles | sed 's/,//g' | awk 'END{print $2}' | 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 '.')
	rm -f $CONFIGDIR/dvdtitles
	echo ""
	if [ -z "$DVDTITLE" ]; then
		brown "Disc Title: $GET_TITLE"
		echo "$ALLTITLES"
		echo ""
		green "-> Titles On Disc: $TOTAL_TITLES"
		green "-> Failed to detect longest DVD title!"
		green "-> You have to specify it yourself!"
		DVDTITLE="???"
	else
		brown "Disc Title: $GET_TITLE"
		echo "$ALLTITLES"
		echo ""
		green "-> Titles On Disc: $TOTAL_TITLES"
		green "-> 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
		error "-> You have to specify the DVD title for encoding!"
		rmconf
	fi
	if [ -z "$title" ]; then
		sourcetype=dvd://$DVDTITLE
	else
		sourcetype=dvd://$title
	fi
	printf "Would you like to encode from a different DVD angle? [y/n]: "
	read angle
	if [ "$angle" = "y" -o "$angle" = "Y" ]; then
		echo ""
		green "-> Scanning for angles in title $(echo $sourcetype | sed 's|dvd://||')..."
		ANGLES=$(mplayer $sourcetype $device -nosound -vo null -frames 1 -nocache 2>/dev/null | grep "angles")
		if [ ! -z "$ANGLES" ]; then
			green "-> $ANGLES"
		else
			green "-> Could not detect any angles in this DVD title!"
		fi
		echo ""
		printf "From which angle to encode the DVD? [default is 1]: "
		read dvd_angle
		if [ -z "$dvd_angle" ]; then
			dvdangle=
		else
			dvdangle="-dvdangle $dvd_angle"
		fi
	elif [ "$angle" = "n" -o "$angle" = "N" -o -z "$angle" ]; then
		dvdangle=
	fi
	printf "Would you like to encode only Specific Chapters? [y/n]: "
	read chap
	if [ "$chap" = "y" -o "$chap" = "Y" ]; then
		echo ""
		green "-> Scanning for chapters in title $(echo $sourcetype | sed 's|dvd://||')..."
		mplayer $sourcetype $device -nosound -vo null -frames 1 -identify -nocache 2>/dev/null > $CONFIGDIR/chapters
		if [ ! -z "$(grep '^CHAPTERS' $CONFIGDIR/chapters)" ]; then
			echo ""
			grep '^CHAPTERS' $CONFIGDIR/chapters | sed -e 's/CHAPTERS: //' -e 's/,/ /g' > $CONFIGDIR/getchaps
			for i in $(cat $CONFIGDIR/getchaps); do
				echo "Chapter: $i - Start position: " >> $CONFIGDIR/lschaps
			done
			nl $CONFIGDIR/lschaps | awk '{print $2,$1,$4,$5,$6,$3}'
		else
			green "-> Could not detect any chapters in this DVD title!"
		fi
		rm -f $CONFIGDIR/*
		echo ""
		printf "Which chapter(s) to encode from this DVD title? [example: 1-3]: "
		read chapenc
		if [ -z "$chapenc" ]; then
			chapters=
		else
			chapters="-chapter $chapenc"
		fi
		# Overwirte output name and
		# append chapter info to it
		if [ ! -z "$chapters" ]; then
			OUTPUT="$(echo "$OUTPUT" | sed 's/\.avi//')_chapter$(echo $chapters | awk '{print $2}').avi"
			test -e "$OUTPUT" && mv -f "$OUTPUT" "$OUTPUT.old"
		fi
	elif [ "$chap" = "n" -o "$chap" = "N" -o -z "$chap" ]; then
		chapters=
	fi
	# Export chapters information to a file.
	# This can be used to import chapters
	# info when muxing into MKV. It requires
	# ogmtools' dvdxchap.
	if [ -x "$(which dvdxchap 2>/dev/null)" ]; then
		printf "Export DVD chapters information to a file on disk? [y/n]: "
		read chapexp
		if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
			CHAPTERSFILE=$(echo "$OUTPUT" | sed 's|\.avi|\.chaps|')
			test -e "$CHAPTERSFILE" && mv -f "$CHAPTERSFILE" "$CHAPTERSFILE.old"
			dvdxchap -t $(echo $sourcetype | sed 's|dvd://||') $(echo $device | awk '{print $2}') | grep '^CHAPTER' > "$CHAPTERSFILE"
		fi
	fi
	printf "Would you like to use Pre/Postprocessing video filters? [y/n]: "
	read vfilters
	if [ "$vfilters" = "y" -o "$vfilters" = "Y" ]; then
		echo ""
		brown "+==================================+"
		brown "| Pre/Postprocessing Video Filters |"
		brown "+==================================+"
		echo ""
		video_deinterlace_func
		video_interlace_func
		video_deblock_func
		video_denoise_func
		video_noise_func
		video_unsharp_func
		video_brightness_func
	elif [ "$vfilters" = "n" -o "$vfilters" = "N" -o -z "$vfilters" ]; then
		interlacing=":nointerlacing"
	fi
	video_crop_func
	video_subtitles_func
	;;
	*)
	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.
# Skip frame rate selection if interlacing progressive
# content or deinterlacing interlaced content with a
# deinterlacing filter which doubles the output frame
# rate. Both actions are mutually exclusive with the
# option below.

if [ -z "$intfilter" -a -z "$deintfps" ]; then
	echo ""
	green "-> Detecting source FPS value..."
	mplayer "$sourcetype" $device $vid -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/fps
	GETFPS=$(grep '^ID_VIDEO_FPS' $CONFIGDIR/fps | tail -1 | awk -F= '{print $2}')
	rm -f $CONFIGDIR/fps
	case "$GETFPS" in
		# VFR (variable frame rate) Anime is not
		# officially supported by xvidenc. Heck
		# even MEncoder doesn't support VFR. We
		# just display here the FPS if we detect
		# such content.
		5.000|5.00)
		green "-> Detected $GETFPS FPS (VFR Anime)"
		;;
		10.000|10.00)
		green "-> Detected $GETFPS FPS (VFR Anime)"
		;;
		12.000|12.00)
		green "-> Detected $GETFPS FPS (VFR Anime)"
		;;
		15.000|15.00)
		green "-> Detected $GETFPS FPS (VFR Anime)"
		;;
		15.98[4-5]|15.98)
		green "-> Detected $GETFPS FPS (Silent Film)"
		;;
		17.982|17.98)
		green "-> Detected $GETFPS FPS (Silent Film)"
		;;
		24.000|24.00)
		green "-> Detected $GETFPS FPS (Film)"
		;;
		25.000|25.00)
		green "-> Detected $GETFPS FPS (PAL/SECAM Film/Video)"
		;;
		50.000|50.00)
		green "-> Detected $GETFPS FPS (PAL/SECAM Double)"
		;;
		100.000|100.00)
		green "-> Detected $GETFPS FPS (PAL/SECAM Quad)"
		;;
		23.976|23.97)
		green "-> Detected $GETFPS FPS (NTSC Film)"
		green "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		29.970|29.97|30.000|30.00)
		green "-> Detected $GETFPS FPS (NTSC Video)"
		green "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		59.940|59.94|60.000|60.00)
		green "-> Detected $GETFPS FPS (NTSC Double)"
		green "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		119.880|119.88)
		green "-> Detected $GETFPS FPS (NTSC Quad)"
		green "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		"")
		green "-> Failed to detect source FPS value!"
		;;
		*)
		green "-> Detected $GETFPS FPS (???)"
		;;
	esac
	echo ""
	printf "Would you like to set/force the Output Frame Rate (FPS)? [y/n]: "
	read outfps
	if [ "$outfps" = "y" -o "$outfps" = "Y" ]; then
		echo ""
		brown "Frame Rate Selection"
		brown "~~~~~~~~~~~~~~~~~~~~"
		echo "0 --> Silent Film (15.984 fps)"
		echo "1 --> Silent Film (17.982 fps)"
		echo "2 --> Film (24 fps)"
		echo "3 --> PAL/SECAM Film/Video (25 fps)"
		echo "4 --> PAL/SECAM Double (50 fps)"
		echo "5 --> PAL/SECAM Quad (100 fps)"
		echo "6 --> NTSC Film (23.976 fps)"
		echo "7 --> NTSC Video (29.970 fps)"
		echo "8 --> NTSC Video (30 fps)"
		echo "9 --> NTSC Double (59.940 fps)"
		echo "10 -> NTSC Double (60 fps)"
		echo "11 -> NTSC Quad (119.880 fps)"
		echo "12 -> User Defined"
		echo "13 -> Skip setting the frame rate"
		echo ""
		printf "Select a Frame Rate format [default is 3]: "
		read frf
		case "$frf" in
			0) ofps="-ofps 16000/1001" ;;
			1) ofps="-ofps 18000/1001" ;;
			2) ofps="-ofps 24" ;;
			3|"") ofps="-ofps 25" ;;
			4) ofps="-ofps 50" ;;
			5) ofps="-ofps 100" ;;
			6) ofps="-ofps 24000/1001" ;;
			7) ofps="-ofps 30000/1001" ;;
			8) ofps="-ofps 30" ;;
			9) ofps="-ofps 60000/1001" ;;
			10) ofps="-ofps 60" ;;
			11) ofps="-ofps 120000/1001" ;;
			12)
			printf "Specify the Frame Rate value [default is 25]: "
			read frame_rate
			if [ ! -z "$(echo $frame_rate | grep '\.')" ]; then
				error "-> Float is not allowed. Use fractions instead!"
				error "-> Example: 30000/1001"
				rmconf
			fi
			if [ -z "$frame_rate" ]; then
				ofps="-ofps 25"
			else
				if [ "$(echo $frame_rate | awk -F/ '{print $2}')" != "1001" ]; then
					error "-> You have to use 1001 as last value of the fraction!"
					error "-> Example: 30000/1001"
					rmconf
				fi
				ofps="-ofps $frame_rate"
			fi
			;;
			13) false ;;
			*)
			error "-> Unknown frame rate option: '$frf'"
			rmconf
			;;
		esac
	elif [ "$outfps" = "n" -o "$outfps" = "N" -o -z "$outfps" ]; then
		ofps=
		frf=
	fi
else
	GETFPS="25"
fi

# Frame rate conversion. Mutually
# exclusive with frame doubling
# deinterlacers and interlacing
# filters

case "$GETFPS" in
	25.000|25.00|29.970|29.97|50.000|50.00|100.000|100.00|59.940|59.94|60.000|60.00|119.880|119.88|"")
	if [ -z "$deintfps" -a -z "$intfps" -a "$interlacing" = ":nointerlacing" ]; then
		printf "Would you like to do Frame Rate Conversion? [y/n]: "
		read fpsconv
		if [ "$fpsconv" = "y" -o "$fpsconv" = "Y" ]; then
			quiet="2>/dev/null"
			echo ""
			brown "Frame Rate Conversion"
			brown "~~~~~~~~~~~~~~~~~~~~~"
			echo "0 -> 50 fps ------> 25 fps (PAL/SECAM Double -> PAL/SECAM)"
			echo "1 -> 100 fps -----> 50 fps (PAL/SECAM Quad -> PAL/SECAM Double)"
			echo "2 -> 29.970 fps --> 23.976 fps (NTSC Video -> NTSC Film)"
			echo "3 -> 59.940 fps --> 23.976 fps (NTSC Double -> NTSC Film)"
			echo "4 -> 59.940 fps --> 29.970 fps (NTSC Double -> NTSC Video)"
			echo "5 -> 60 fps ------> 30 fps (NTSC Double -> NTSC Video)"
			echo "6 -> 119.880 fps -> 59.940 fps (NTSC Quad -> NTSC Double)"
			echo "7 -> 25 fps ------> 50 fps (PAL/SECAM -> PAL/SECAM Double)"
			echo "8 -> 29.970 ------> 59.940 fps (NTSC Video -> NTSC Double)"
			echo "9 -> Skip frame rate conversion"
			echo ""
			printf "Select the frame rate conversion [no default!]: "
			read frc
			frc_func() {
				echo ""
				green "-> Setting input/output frame rate to $(echo "scale=3; $(echo $fps | awk '{print $2}')" | bc -l)/$(echo "scale=3; $(echo $ofps | awk '{print $2}')" | bc -l) FPS"
				green "-> Using '$(echo $fpsfilter | sed 's/,$//')' video filter(s)"
			}
			case "$frc" in
				0|1)
				echo ""
				brown "FPS Conversion Filters"
				brown "~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 -> Framestep"
				echo "1 -> Filmdint"
				echo ""
				printf "Which filter to use? [default is 1]: "
				read fpscf
				case "$frc" in
					0)
					case "$fpscf" in
						0) fpsfilter="framestep=2," ;;
						1|"") fpsfilter="filmdint=fast=0/io=50:25/dint_thres=256," ;;
						*) error "-> Unknown filters option: '$fpscf'"; rmconf ;;
					esac
					fps="-fps 50"
					ofps="-ofps 25"
					frc_func
					;;
					1)
					case "$fpscf" in
						0) fpsfilter="framestep=2," ;;
						1|"") fpsfilter="filmdint=fast=0/io=100:50/dint_thres=256," ;;
						*) error "-> Unknown filters option: '$fpscf'"; rmconf ;;
					esac
					fps="-fps 100"
					ofps="-ofps 50"
					frc_func
					;;
				esac
				;;
				2)
				fpsfilter="filmdint=fast=0/io=30:24/dint_thres=256,"
				fps="-fps 30000/1001"
				ofps="-ofps 24000/1001"
				frc_func
				;;
				3)
				echo ""
				brown "FPS Conversion Filters"
				brown "~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 -> Framestep & Filmdint"
				echo "1 -> Filmdint"
				echo ""
				printf "Which filter(s) to use? [default is 1]: "
				read fpscf
				case "$fpscf" in
					0) fpsfilter="framestep=2,filmdint=fast=0/io=30:24/dint_thres=256," ;;
					1|"") fpsfilter="filmdint=fast=0/io=60:24/dint_thres=256," ;;
					*) error "-> Unknown filters option: '$fpscf'"; rmconf ;;
				esac
				fps="-fps 60000/1001"
				ofps="-ofps 24000/1001"
				frc_func
				;;
				4|5|6)
				echo ""
				brown "FPS Conversion Filters"
				brown "~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 -> Framestep"
				echo "1 -> Filmdint"
				echo ""
				printf "Which filter to use? [default is 1]: "
				read fpscf
				case "$frc" in
					4)
					case "$fpscf" in
						0) fpsfilter="framestep=2," ;;
						1|"") fpsfilter="filmdint=fast=0/io=60:30/dint_thres=256," ;;
						*) error "-> Unknown filters option: '$fpscf'"; rmconf ;;
					esac
					fps="-fps 60000/1001"
					ofps="-ofps 30000/1001"
					frc_func
					;;
					5)
					case "$fpscf" in
						0) fpsfilter="framestep=2," ;;
						1|"") fpsfilter="filmdint=fast=0/io=60:30/dint_thres=256," ;;
						*) error "-> Unknown filters option: '$fpscf'"; rmconf ;;
					esac
					fps="-fps 60"
					ofps="-ofps 30"
					frc_func
					;;
					6)
					case "$fpscf" in
						0) fpsfilter="framestep=2," ;;
						1|"") fpsfilter="filmdint=fast=0/io=120:60/dint_thres=256," ;;
						*) error "-> Unknown filters option: '$fpscf'"; rmconf ;;
					esac
					fps="-fps 120000/1001"
					ofps="-ofps 60000/1001"
					frc_func
					;;
				esac
				;;
				7)
				fps="-fps 25"
				ofps="-ofps 50"
				echo ""
				green "-> Setting input/output frame rate to 25/50 FPS"
				;;
				8)
				fps="-fps 30000/1001"
				ofps="-ofps 60000/1001"
				echo ""
				green "-> Setting input/output frame rate to 29.970/59.940 FPS"
				;;
				9) false ;;
				*|"") error "-> Unknown option or frame rate conversion not selected!"; rmconf ;;
			esac
		elif [ "$fpsconv" = "n" -o "$fpsconv" = "N" -o -z "$fpsconv" ]; then
			fpsfilter=
		fi
	else
		fpsfilter=
	fi
	;;
	*) fpsfilter=
	;;
esac

# Pulldown reversal/inverse telecine/telecine
# 3:2 pulldown filters.
# Only ask for telecine stuff if user doesn't
# use interlaced encoding and content is not
# PAL/SECAM and if user isn't using a deinterlace
# filter.

case "$GETFPS" in
	23.976|29.970|23.97|29.97|30.000|30.00|"")
	if [ "$interlacing" = ":nointerlacing" -a -z "$deintfilter" -a -z "$fpsfilter" ]; then
		printf "Apply a Telecine/3:2 Pulldown/IVTC/Pullup process (NTSC only!)? [y/n]: "
		read tpp
		if [ "$tpp" = "y" -o "$tpp" = "Y" ]; then
			echo ""
			brown "Telecine/3:2 Pulldown/IVTC/Pullup"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "0 -> Apply Inverse Telecine/Pullup on the input"
			echo "     source to make it progressive and bring back"
			echo "     its frame rate from 29.97 to 23.976 fps. Use"
			echo "     this process on soft/hard telecined content."
			echo ""
			echo "1 -> Apply Hard Telecine/3:2 Pulldown to the"
			echo "     encoded content and speed up its frame"
			echo "     rate from 23.976 to 29.97 fps. Use this"
			echo "     process on progressive content."
			echo ""
			echo "2 -> Skip Telecine/Pullup"
			echo ""
			printf "Which process to use? [default is 0]: "
			read telproc
			case "$telproc" in
				0|"")
				echo ""
				brown "Available IVTC Filters"
				brown "~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 -> Pullup (4th generation IVTC filter)"
				echo "1 -> Filmdint (3rd generation IVTC filter)"
				echo "2 -> IVTC (2nd generation IVTC filter)"
				echo "3 -> DETC (1st generation IVTC filter)"
				echo ""
				printf "Which Inverse Telecine/Pullup filter to use? [default is 0]: "
				read ivtc
				case "$ivtc" in
					0|"") ivtcfilter="pullup," ;;
					1) ivtcfilter="filmdint=fast=0," ;;
					2) ivtcfilter="ivtc=1," ;;
					3)
					echo ""
					brown "DETC Frame Dropping Modes"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~"
					echo "0 -> Always drop a frame if there has been"
					echo "     no drops or telecine merges in past"
					echo "     5 frames. (detc=dr=1)"
					echo ""
					echo "1 -> Always maintain exact 5:4 input to"
					echo "     output frame ratio. (detc=dr=2)"
					echo ""
					printf "Select a DETC frame dropping mode [default is 0]: "
					read detcmode
					case "$detcmode" in
						0|""|*) ivtcfilter="detc=dr=1," ;;
						1) ivtcfilter="detc=dr=2," ;;
					esac
					;;
					*)
					error "-> Unknown IVTC option: '$ivtc'"
					rmconf
					;;
				esac
				echo ""
				green "-> Setting input/output frame rate to 29.970/23.976 FPS"
				green "-> Using '$(echo $ivtcfilter | sed 's/,$//')' video filter(s)"
				fps="-fps 30000/1001"
				ofps="-ofps 24000/1001"
				quiet="2>/dev/null"
				;;
				1)
				# Both fps and ofps *must* be
				# 30000/1001 or we will loose
				# A/V sync due to limitations
				# in the filter layer of MEncoder !!
				fps="-fps 30000/1001"
				ofps="-ofps 30000/1001"
				telecinefilter=",telecine"
				interlacing=":interlacing"
				ivtcfilter=
				quiet="2>/dev/null"
				echo ""
				green "-> Setting input/output frame rate to 29.970 FPS"
				green "-> Using '$(echo $telecinefilter | sed 's/^,//')' video filter(s)"
				;;
				2) false ;;
				*)
				error "-> Unknown IVTC/Pulldown option: '$telproc'"
				rmconf
				;;
			esac
		elif [ "$tpp" = "n" -o "$tpp" = "N" -o -z "$tpp" ]; then
			ivtcfilter=
			telecinefilter=
		fi
	else
		ivtcfilter=
		telecinefilter=
	fi
	;;
	*)
	ivtcfilter=
	telecinefilter=
	;;
esac

# Overwrite input/output frame rate if the
# user has chosen to interlace his progressive
# content during the encoding process or if
# the user is deinterlacing it with a deinterlace
# filter which doubles the output frame rate.

if [ ! -z "$intfilter" ]; then
	fps="-fps $intfps"
	ofps="-ofps $intofps"
fi

if [ ! -z "$deintfps" ]; then
	fps="-fps $deintfps"
	ofps="-ofps $deintofps"
fi


profile_res_func() {
	case "$1" in
		hwsdpal) green "-> Maximum allowed profile resolution: 720x576" ;;
		hwsdntsc) green "-> Maximum allowed profile resolution: 720x480" ;;
		hwhdpal|hwhdntsc) green "-> Maximum allowed profile resolution: 1280x720" ;;
	esac
}
	

# 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 "$cropfilter" ]; then
	green "-> Detecting cropped resolution..."
	GETRES=$(echo $cropfilter | sed -e 's/crop=//' -e 's/,//' | tr ':' ' ' | awk '{print $1,$2}' | sed 's/ /x/')
	if [ ! -z "$GETRES" ]; then
		green "-> Resolution after cropping is: $GETRES"
		profile_res_func $3
	else
		echo ""
		green "-> Failed to detect cropped resolution!"
		green "-> You have to provide it yourself!"
		profile_res_func $3
		GETRES="???"
	fi
else
	green "-> Detecting original resolution..."
	mplayer "$sourcetype" $device $vid -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/resolution
	GETRES=$(grep "^VIDEO:" $CONFIGDIR/resolution | tail -1 | awk '{print $3}')
	if [ ! -z "$GETRES" ]; then
		green "-> Original resolution is: $GETRES"
		profile_res_func $3
	else
		echo ""
		green "-> Failed to detect original resolution!"
		green "-> You have to provide it yourself!"
		profile_res_func $3
		GETRES="???"
	fi
	rm -f $CONFIGDIR/resolution
fi
echo ""
printf "Specify the desired Resolution [default is $GETRES]: "
read vres
if [ -z "$vres" -a "$GETRES" = "???" ]; then
	error "-> 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 "$vres" in
	$GETRES|"")
	scale=
	sws=
	isws=
	swsparam=
	;;
	*)
	scale="scale=$(echo $vres | tr '[:alpha:]' ':')"
	# Interlacing parameters for the scale filter.
	# The first conditional sets the SWS parameters
	# to progressive if the user is interlacing
	# progressive content with the 'tinterlace' filter
	# and if the 'telecine' filter is not being used.
	# As this filter comes *after* the 'scale' filter,
	# there is no need to enable interlaced mode in
	# the SWS scaler during the resizing process.
	# The second conditional sets the SWS to interlaced
	# mode if the user is not using the 'tinterlace'
	# filter but does want to preserve the interlacing
	# of his content and if the 'telecine' filter is not
	# used. The third conditional sets the SWS parameters
	# to progressive if the user is not interlacing the
	# content with 'tinterlace' but is using the 'telecine'
	# filter. As is the case with the first conditional,
	# the 'telecine' filter also comes after the scaler
	# so again there's no need to enable interlaced
	# mode in the scaler. The last conditional sets the
	# SWS parameters to progressive mode if the content
	# is not interlaced or if it is, but the user is
	# deinterlacing it with one of the filters.
	
	if [ "$interlacing" = ":interlacing" -a ! -z "$intfilter" -a -z "$telecinefilter" ]; then
		isws=":0:0"
	elif [ "$interlacing" = ":interlacing" -a -z "$intfilter" -a -z "$telecinefilter" ]; then
		isws=":1:0"
	elif [ "$interlacing" = ":interlacing" -a -z "$intfilter" -a ! -z "$telecinefilter" ]; then
		isws=":0:0"
	elif [ "$interlacing" = ":nointerlacing" ]; then
		isws=":0:0"
	fi
	echo ""
	brown "Available Software Scalers"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
	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 ""
	# Check if width & height are divisible
	# by 16 and if not display a warning
	WMOD16=$(echo "scale=3; $(echo $scale | sed 's/scale=//' | awk -F: '{print $1}')/16" | bc -l | awk -F. '{print $2}')
	HMOD16=$(echo "scale=3; $(echo $scale | sed 's/scale=//' | awk -F: '{print $2}')/16" | bc -l | awk -F. '{print $2}')
	if [ "$WMOD16" != "000" -o "$HMOD16" != "000" ]; then
		green "-> Warning: width and/or height not divisible by 16!"
		green "-> Compression will suffer!"
		echo ""
	fi
	printf "Select a Software Scaler [default is 10]: "
	read ss
	if [ -z "$ss" ]; then
		sws="-sws 10"
	else
		sws="-sws $ss"
	fi
	# software scaler tuning, only supported
	# by bicubic, bicubic spline, gaussian
	# and lanczos scalers
	case $(echo "$sws" | 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 ""
			brown "Software Scaler Parameters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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 "Below are some frequently used settings"
			echo "Format is as follows: blurring:ringing"
			echo ""
			echo "0 -> 0.00:0.60 -> Default"
			echo "1 -> 0.00:0.75 -> VirtualDub's \"Precise Bicubic\""
			echo "2 -> 0.00:0.50 -> Catmull-Rom Spline"
			echo "3 -> 0.33:0.33 -> Mitchell-Netravali Spline"
			echo "4 -> 1.00:0.00 -> Cubic B-Spline"
			echo "5 -> User defined"
			echo "6 -> Skip the scaler parameters"
			echo ""
			printf "Specify the Software Scaler Parameters [default is 0.00:0.60]: "
			read ssparam
			case "$ssparam" in
				0|"") swsparam=":0.00:0.60" ;;
				1) swsparam=":0.00:0.75" ;;
				2) swsparam=":0.00:0.50" ;;
				3) swsparam=":0.33:0.33" ;;
				4) swsparam=":1.00:0.00" ;;
				5)
				printf "Specify the Software Scaler Parameters [default is 0.00:0.60]: "
				read ssp
				if [ -z "$ssp" ]; then
					swsparam=":0.00:0.60"
				else
					swsparam=":$ssp"
				fi
				;;
				6) false ;;
				*)
				error "-> Unknown software scaler parameters option: '$ssparam'"
				rmconf
				;;
			esac
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			swsparam=
		fi
		;;
		7)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			brown "Software Scaler Parameters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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
				swsparam=
			else
				swsparam=":$ssparam"
			fi
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			swsparam=
		fi
		;;
		9)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			brown "Software Scaler Parameters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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
				swsparam=
			else
				swsparam=":$ssparam"
			fi
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			swsparam=
		fi
		;;
		*)
		swsparam=
		;;
	esac
	;;
esac

# Do a colorspace conversion?
if [ ! -z "$scale" ]; then
	if [ -z "$fpsfilter" -a -z "$intfilter" -a -z "$telecinefilter" -a "$interlacing" = ":nointerlacing" ]; then
		video_colorspace_func
	else
		colorspacefilter=
	fi
else
	colorspacefilter=
fi

# Aspect ratio
printf "Would you like to set/force the input Video Aspect Ratio? [y/n]: "
read aratio
if [ "$aratio" = "y" -o "$aratio" = "Y" ]; then
	echo ""
	green "-> Detecting video aspect..."
	mplayer "$sourcetype" $device $vid -identify -nosound -vo null -nocache -frames 1 2>/dev/null > $CONFIGDIR/aspect
	GET_ASPECT=$(grep '^ID_VIDEO_ASPECT' $CONFIGDIR/aspect | tail -1 | awk -F= '{print $2}')
	rm -f $CONFIGDIR/aspect
	if [ ! -z "$GET_ASPECT" ]; then
		green "-> Detected: $GET_ASPECT"
		V_ASPECT="$GET_ASPECT"
	else
		green "-> Could not detect the video aspect!"
		V_ASPECT="16:9"
	fi
	echo ""
	printf "Specify the Aspect Ratio [4:3/16:9/1.3333/1.777... - default is $V_ASPECT]: "
	read asra
	if [ -z "$asra" ]; then
		aspect="-aspect $V_ASPECT"
	else
		aspect="-aspect $asra"
	fi
elif [ "$aratio" = "n" -o "$aratio" = "N" -o -z "$aratio" ]; then
	aspect=
fi

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


echo ""
brown "+==================================+"
brown "| Xvid 1.1.x Encoder Configuration |"
brown "+==================================+"
echo ""

# Skip bitrate/quant settings if user
# chooses the NLQ preset
if [ "$3" = "nlq" ]; then
	true
else
	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 in kbps [default is 1200]: "
		read vb
		if [ -z "$vb" ]; then
			vbitrate="bitrate=1200"
		else
			vbitrate="bitrate=$vb"
		fi
		bits_per_pixel_func
		bits_per_block_func
		;;
		-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
		echo ""
		;;
	esac
fi

#####################################################
################### Presets #########################
#####################################################

if [ -r /proc/cpuinfo ]; then
	THREADS=$(sed -n -e '/^processor/p' /proc/cpuinfo | wc -l)
	if [ ! -z "$THREADS" ]; then
		threads=":threads=$THREADS"
	else
		threads=
	fi
else
	threads=
fi

display_quality_preset_func $3
case "$3" in
	ulq)
	# Ultra Low Quality
	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"
	;;
	elq)
	# Extreme Low Quality
	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"
	;;
	vlq)
	# Very Low Quality
	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"
	;;
	lq)
	# Low Quality
	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"
	;;
	mq)
	# Medium Quality
	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"
	;;
	nq)
	# Normal Quality
	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"
	;;
	hq)
	# High Quality
	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"
	;;
	vhq)
	# Very High Quality
	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"
	;;
	ehq|hwsdpal|hwsdntsc|hwhdpal|hwhdntsc)
	# Extreme High Quality/HW compatible
	me_quality=":me_quality=6"
	vhq=":vhq=4"
	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"
	case "$3" in
		hwsdpal)
		profile=":profile=dxnhtpal"
		ffourcc="-ffourcc DX50"
		noodml="-noodml"
		;;
		hwsdntsc)
		profile=":profile=dxnhtntsc"
		ffourcc="-ffourcc DX50"
		noodml="-noodml"
		;;
		hwhdpal|hwhdntsc)
		profile=":profile=dxnhdtv"
		ffourcc="-ffourcc DX50"
		noodml="-noodml"
		;;
	esac
	;;
	uhq)
	# Ultra High Quality
	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"
	;;
	nlq)
	# Near Lossless Quality
	vbitrate="fixed_quant=2"
	me_quality=":me_quality=6"
	vhq=":vhq=0"
	max_bframes=":max_bframes=0"
	bvhq=":bvhq=0"
	packed=":nopacked"
	quant_type=":quant_type=mpeg"
	qpel=":noqpel"
	gmc=":nogmc"
	trellis=":trellis"
	chroma_me=":chroma_me"
	chroma_opt=":chroma_opt"
	hq_ac=":hq_ac"
	lumi_mask=":nolumi_mask"
	turbo=
	;;
esac
echo ""
case "$3" in
	hwsdpal|hwsdntsc|hwhdpal|hwhdntsc) false ;;
	*) custom_matrix_func ;;
esac
advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100$intramatrix$intermatrix"

# 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 ""
	brown "Encoder Priority Level"
	brown "~~~~~~~~~~~~~~~~~~~~~~"
	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 on 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=
			;;
			*|"")
			priority_level=
			;;
		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=
			;;
		esac
	fi
elif [ "$priolevel" = "n" -o "$priolevel" = "N" -o -z "$priolevel" ]; then
	priority_level=
fi

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

# Check availability of the
# selected audio codec in
# MEncoder
check_audio_codec_func() {
	case "$audiocodec" in
		mp2|MP2|ac3|AC3|adpcm|ADPCM|wma|WMA|flac|FLAC|sonic|SONIC|sonicls|SONICLS)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc')" ]; then
			error "-> MEncoder does not support the libavcodecs audio collection!"
			error "-> Download the official MPlayer package or use a different"
			error "   audio codec."
			rmconf
		fi
		;;
		mp3|MP3|"")
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" ]; then
			error "-> MEncoder does not support MP3 audio encoding!"
			error "-> Download LAME and recompile MPlayer or use"
			error "   a different audio codec"
			rmconf
		fi
		;;
		aac|AAC)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" ]; then
			error "-> MEncoder does not support AAC audio encoding!"
			error "-> Download 'faac' and recompile MPlayer or use"
			error "   a different audio codec"
			rmconf
		fi
		;;
		aac+|AAC+)
		if [ ! -x "$(which neroAacEnc 2>/dev/null)" ]; then
			error "-> 'neroAacEnc' is missing from your system!"
			error "-> Please select a different audio codec!"
			rmconf
		fi
		;;
		vorbis|VORBIS)
		if [ ! -x "$(which oggenc 2>/dev/null)" ]; then
			error "-> 'oggenc' is missing from your system!"
			error "-> Please select a different audio codec!"
			rmconf
		fi
		;;
		pcm|PCM)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" ]; then
			error "-> MEncoder does not support PCM audio encoding!"
			error "-> Download the official MPlayer package or use"
			error "   a different audio codec"
			rmconf
		fi
		;;
		copy|COPY)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'copy')" ]; then
			error "-> MEncoder does not support audio stream copy!"
			error "-> Download the official MPlayer package or use"
			error "   a different audio codec"
			rmconf
		fi
		;;
	esac
}

# Resample function
audio_resample_func() {
	printf "Would you like to Resample the Audio? [y/n]: "
	read rsmp
	if [ "$rsmp" = "y" -o "$rsmp" = "Y" ]; then
		echo ""
		brown "Available Resample Frequencies"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		case "$audiocodec" in
			MP[2-3]|mp[2-3]|PCM|pcm|vorbis|VORBIS|ADPCM|adpcm|WMA|wma|FLAC|flac|SONIC|sonic|SONICLS|sonicls|"")
			echo "0 -> 8000 Hz (8 kHz)"
			echo "1 -> 11025 Hz (11 kHz)"
			echo "2 -> 12000 Hz (12 kHz)"
			echo "3 -> 16000 Hz (16 kHz)"
			echo "4 -> 22050 Hz (22 kHz)"
			echo "5 -> 24000 Hz (24 kHz)"
			echo "6 -> 32000 Hz (32 kHz)"
			echo "7 -> 44100 Hz (44.1 kHz)"
			echo "8 -> 48000 Hz (48 kHz)"
			echo ""
			printf "Select a Resample frequency [default is 7]: "
			read freq
			case "$freq" in
				0) herz="8000" ;;
				1) herz="11025" ;;
				2) herz="12000" ;;
				3) herz="16000" ;;
				4) herz="22050" ;;
				5) herz="24000" ;;
				6) herz="32000" ;;
				7|"") herz="44100" ;;
				8) herz="48000" ;;
				*) error "-> Unknown resample frequency option: '$freq'"; rmconf ;;
			esac
			;;
			AAC|aac|AAC+|aac+)
			echo "0 --> 8000 Hz (8 kHz)"
			echo "1 --> 11025 Hz (11 kHz)"
			echo "2 --> 12000 Hz (12 kHz)"
			echo "3 --> 16000 Hz (16 kHz)"
			echo "4 --> 22050 Hz (22 kHz)"
			echo "5 --> 24000 Hz (24 kHz)"
			echo "6 --> 32000 Hz (32 kHz)"
			echo "7 --> 44100 Hz (44.1 kHz)"
			echo "8 --> 48000 Hz (48 kHz)"
			echo "9 --> 64000 Hz (64 kHz)"
			echo "10 -> 88200 Hz (88.2 kHz)"
			echo "11 -> 96000 Hz (96 kHz)"
			echo ""
			printf "Select a Resample frequency [default is 7]: "
			read freq
			case "$freq" in
				0) herz="8000" ;;
				1) herz="11025" ;;
				2) herz="12000" ;;
				3) herz="16000" ;;
				4) herz="22050" ;;
				5) herz="24000" ;;
				6) herz="32000" ;;
				7|"") herz="44100" ;;
				8) herz="48000" ;;
				9) herz="64000" ;;
				10) herz="88200" ;;
				11) herz="96000" ;;
				*) error "-> Unknown resample frequency option: '$freq'"; rmconf ;;
			esac
			;;
			AC3|ac3)
			echo "0 -> 32000 Hz (32 kHz)"
			echo "1 -> 44100 Hz (44.1 kHz)"
			echo "2 -> 48000 Hz (48 kHz)"
			echo ""
			printf "Select a Resample frequency [default is 1]: "
			read freq
			case "$freq" in
				0) herz="32000" ;;
				1|"") herz="44100" ;;
				2) herz="48000" ;;
				*) error "-> Unknown resample frequency option: '$freq'"; rmconf ;;
			esac
			;;
		esac
		echo ""
		brown "Audio Resample Filters And Modes"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Resample: standard mode, linear interpolation"
		echo "1 -> Resample: HQ mode, linear interpolation"
		echo "2 -> Resample: standard mode, polyphase filterbank & integer processing"
		echo "3 -> Resample: HQ mode, polyphase filterbank & integer processing"
		echo "4 -> Resample: standard mode, polyphase filterbank & floating point processing"
		echo "5 -> Resample: HQ mode, polyphase filterbank & floating point processing"
		echo "6 -> Lavcresample: standard mode"
		echo "7 -> Lavcresample: linear interpolated polyphase filterbank"
		echo "8 -> Skip resampling"
		echo ""
		printf "Select a Resample filter [default is 5]: "
		read rsmpfilter
		case "$rsmpfilter" in
			0) resample="resample=$herz:1:0 -srate $herz" ;;
			1) resample="resample=$herz:0:0 -srate $herz" ;;
			2) resample="resample=$herz:1:1 -srate $herz" ;;
			3) resample="resample=$herz:0:1 -srate $herz" ;;
			4) resample="resample=$herz:1:2 -srate $herz" ;;
			5|"") resample="resample=$herz:0:2 -srate $herz" ;;
			6) resample="lavcresample=$herz:16:0 -srate $herz" ;;
			7) resample="lavcresample=$herz:16:1 -srate $herz" ;;
			8) false ;;
			*) error "-> Unknown resample filter option: '$rsmpfilter'"; rmconf ;;
		esac
	elif [ "$rsmp" = "n" -o "$rsmp" = "N" -o -z "$rsmp" ]; then
		resample=
	fi
}

# Volume normalizing function.
# Must be called after the
# audio resample function
audio_volnorm_func() {
	printf "Would you like to Normalize the Audio volume? [y/n]: "
	read norm
	if [ "$norm" = "y" -o "$norm" = "Y" ]; then
		volnorm="volnorm=2,"
	elif [ "$norm" = "n" -o "$norm" = "N" -o -z "$norm" ]; then
		volnorm=
	fi
}

# Audio volume gain
# Mutual exclusive with
# the volnorm filter
audio_volume_func() {
	if [ -z "$volnorm" ]; then
		printf "Would you like to set the Audio volume? [y/n]: "
		read avolume
		if [ "$avolume" = "y" -o "$avolume" = "Y" ]; then
			printf "Specify the Audio volume gain in dB [-200-60 - default is 5]: "
			read dbgain
			if [ -z "$dbgain" ]; then
				volume="volume=5:0,"
			else
				volume="volume=$dbgain:0,"
			fi
		elif [ "$avolume" = "n" -o "$avolume" = "N" -o -z "$avolume" ]; then
			volume=
		fi
	else
		volume=
	fi
}

# Channels function for AC3,
# AAC, PCM, FLAC and COPY
audio_channels_func() {
	case "$audiocodec" in
		AC3|ac3|AAC|aac|AAC+|aac+|VORBIS|vorbis|FLAC|flac|PCM|pcm)
		printf "Would you like to use/have more than 2 Audio Channels? [y/n]: "
		read chan
		if [ "$chan" = "y" -o "$chan" = "Y" ]; then
			case "$audiocodec" in
				AC3|ac3)
				echo ""
				brown "AC3 Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> Dolby AC3 Stereo  (2 front)"
				echo "4 -> Dolby AC3 Quadro  (2 front + 2 rear)"
				echo "5 -> Dolby AC3 5.0     (2 front + 2 rear + 1 center)"
				echo "6 -> Dolby AC3 Digital (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				AAC|aac|AAC+|aac+)
				echo ""
				brown "AAC(+) Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> AAC(+) Stereo (2 front)"
				echo "4 -> AAC(+) Quadro (2 front + 2 rear)"
				echo "5 -> AAC(+) 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> AAC(+) 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				VORBIS|vorbis)
				echo ""
				brown "Vorbis Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> Vorbis Stereo (2 front)"
				echo "4 -> Vorbis Quadro (2 front + 2 rear)"
				echo "5 -> Vorbis 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> Vorbis 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				FLAC|flac)
				echo ""
				brown "FLAC Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> FLAC Stereo (2 front)"
				echo "4 -> FLAC Quadro (2 front + 2 rear)"
				echo "5 -> FLAC 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> FLAC 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				PCM|pcm)
				echo ""
				brown "PCM Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> PCM Stereo (2 front)"
				echo "4 -> PCM Quadro (2 front + 2 rear)"
				echo "5 -> PCM 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> PCM 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
			esac
			printf "How many channels to use/add? [default is 2]: "
			read chanuse
			if [ -z "$chanuse" ]; then
				channels=
			else
				channels="-channels $chanuse"
			fi
		elif [ "$chan" = "n" -o "$chan" = "N" -o -z "$chan" ]; then
			channels=
		fi
		;;
		COPY|copy)
		case "$vtype" in
			file|FILE|File)
			printf "How many channels to copy? [2/4/5/6 - default is 2]: "
			read chancopy
			if [ -z "$chancopy" ]; then
				channels="-channels 2"
			else
				channels="-channels $chancopy"
			fi
			;;
			dvd|DVD|Dvd)
			printf "How many channels to copy? [2/4/5/6 - default is 6]: "
			read chancopy
			if [ -z "$chancopy" ]; then
				channels="-channels 6"
			else
				channels="-channels $chancopy"
			fi
			;;
		esac
		;;
	esac
}

echo ""
brown "+=====================+"
brown "| Audio Configuration |"
brown "+=====================+"
echo ""
case "$vtype" in
	dvd|DVD|Dvd)
	green "-> Scanning for audio streams..."
	mplayer $sourcetype $device -nosound -vo null -frames 1 -nocache 2>/dev/null > $CONFIGDIR/audiostreams
	STREAMS=$(grep "^audio stream" $CONFIGDIR/audiostreams)
	rm -f $CONFIGDIR/audiostreams
	echo ""
	if [ ! -z "$STREAMS" ]; then
		echo "$STREAMS" | sed -e 's/^audio/Audio/g' -e 's/format:/Format:/g' -e 's/language:/Language:/g' \
		-e 's/aid:/ID:/g' -e 's/ac3/AC3/g' -e 's/eac3/E-AC3/g' -e 's/dts/DTS/g' -e 's/lpcm/LPCM/g' -e 's/pcm/PCM/g'
	else
		green "-> Could not detect any audio streams!"
	fi
	echo ""
	printf "Specify the DVD Audio Stream ID [default is 128]: "
	read dac
	if [ ! -z "$(echo $dac | grep '[a-zA-Z]')" ]; then
		error "-> You have to specify the 'ID' number, not the language code!"
		rmconf
	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
	printf "Scan for multiple audio streams? [y/n]: "
	read multiaudio
	if [ "$multiaudio" = "y" -o "$multiaudio" = "Y" ]; then
		echo ""
		green "-> Scanning for audio streams..."
		mplayer "$sourcetype" -nosound -vo null -identify -frames 1 -nocache 2>/dev/null > $CONFIGDIR/audiostreams
		if [ $(grep "^ID_AUDIO_ID" $CONFIGDIR/audiostreams | wc -l) -le 1 ]; then
			aid=
			green "-> Zero or one audio stream found"
			green "-> Skipping stream selection"
			echo ""
		else
			echo ""
			for i in $(grep "^ID_AUDIO_ID" $CONFIGDIR/audiostreams); do
				echo "$(echo "Audio stream: $(echo $i | awk -F= '{print $2}')")"
			done
			echo ""
			AID=$(grep "^ID_AUDIO_ID" $CONFIGDIR/audiostreams | awk -F= '{print $2}')
			printf "Specify the Audio Stream 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/audiostreams
	elif [ "$multiaudio" = "n" -o "$multiaudio" = "N" -o -z "$multiaudio" ]; then
		aid=
	fi
	;;
esac

########################################################
############# Audio Codecs Functions ###################
########################################################

mp2_audio_func() {
	echo ""
	brown "MP2 Audio Bitrates"
	brown "~~~~~~~~~~~~~~~~~~"
	echo "0 -> 32 kbps   7 --> 112 kbps"
	echo "1 -> 40 kbps   8 --> 128 kbps"
	echo "2 -> 48 kbps   9 --> 160 kbps"
	echo "3 -> 56 kbps   10 -> 192 kbps"
	echo "4 -> 64 kbps   11 -> 224 kbps"
	echo "5 -> 80 kbps   12 -> 256 kbps"
	echo "6 -> 96 kbps   13 -> 320 kbps"
	echo ""
	printf "Select the MP2 Audio Bitrate [default is 8]: "
	read ab
	case "$ab" in
		0) abitrate="32" ;;
		1) abitrate="40" ;;
		2) abitrate="48" ;;
		3) abitrate="56" ;;
		4) abitrate="64" ;;
		5) abitrate="80" ;;
		6) abitrate="96" ;;
		7) abitrate="112" ;;
		8|"") abitrate="128" ;;
		9) abitrate="160" ;;
		10) abitrate="192" ;;
		11) abitrate="224" ;;
		12) abitrate="256" ;;
		13) abitrate="320" ;;
		*) error "-> Unknown option: '$ab'"; rmconf ;;
	esac
	acodec="-oac lavc -lavcopts acodec=mp2:abitrate=$abitrate"
	channels=
	ac3drc=
}

mp3_audio_func() {
	printf "Specify the MP3 Audio Encoding Mode [ABR/CBR/VBR - default is ABR]: "
	read mp3mode
	case "$mp3mode" in
		a*|A*|"")
		printf "Specify the MP3 Average Audio Bitrate [default is 140]: "
		read ab
		if [ -z "$ab" ]; then
			abitrate="abr:br=140"
		else
			abitrate="abr:br=$ab"
		fi
		;;
		c*|C*)
		echo ""
		brown "MP3 Audio Bitrates"
		brown "~~~~~~~~~~~~~~~~~~"
		echo "0 -> 32 kbps   7 --> 112 kbps"
		echo "1 -> 40 kbps   8 --> 128 kbps"
		echo "2 -> 48 kbps   9 --> 160 kbps"
		echo "3 -> 56 kbps   10 -> 192 kbps"
		echo "4 -> 64 kbps   11 -> 224 kbps"
		echo "5 -> 80 kbps   12 -> 256 kbps"
		echo "6 -> 96 kbps   13 -> 320 kbps"
		echo ""
		printf "Select the MP3 Audio Bitrate [default is 8]: "
		read ab
		case "$ab" in
			0) abitrate="cbr:br=32" ;;
			1) abitrate="cbr:br=40" ;;
			2) abitrate="cbr:br=48" ;;
			3) abitrate="cbr:br=56" ;;
			4) abitrate="cbr:br=64" ;;
			5) abitrate="cbr:br=80" ;;
			6) abitrate="cbr:br=96" ;;
			7) abitrate="cbr:br=112" ;;
			8|"") abitrate="cbr:br=128" ;;
			9) abitrate="cbr:br=160" ;;
			10) abitrate="cbr:br=192" ;;
			11) abitrate="cbr:br=224" ;;
			12) abitrate="cbr:br=256" ;;
			13) abitrate="cbr:br=320" ;;
			*) error "-> Unknown option: '$ab'"; rmconf ;;
		esac
		;;
		v*|V*)
		printf "Specify the desired MP3 Quality [0-9 - default is 3]: "
		read ab
		if [ -z "$ab" ]; then
			abitrate="q=3"
		else
			abitrate="q=$ab"
		fi
		;;
		*)
		error "-> Unknown MP3 encoding mode: '$mp3mode'"
		rmconf
		;;
	esac
	printf "Specify the MP3 Algorithmic Quality [0-9 - default is 4]: "
	read aq
	if [ -z "$aq" ]; then
		aquality=":aq=4"
	else
		aquality=":aq=$aq"
	fi
	printf "Specify the MP3 Audio Input Gain [0.0-10.0 - default is 2.2]: "
	read aig
	if [ -z "$aig" ]; then
		again=":vol=2.2"
	else
		again=":vol=$aig"
	fi
	echo ""
	brown "MP3 Channel Modes"
	brown "~~~~~~~~~~~~~~~~~"
	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" ;;
		*)
		error "-> Unknown MP3 channel option: '$mp3chan'"
		rmconf
		;;
	esac
	acodec="-oac mp3lame -lameopts $abitrate$aquality$again$mp3channel"
	channels=
	ac3drc=
}

ac3_audio_func() {
	echo ""
	brown "AC3 Audio Bitrates"
	brown "~~~~~~~~~~~~~~~~~~"
	echo "0 -> 32 kbps    9 --> 160 kbps"
	echo "1 -> 40 kbps    10 -> 192 kbps"
	echo "2 -> 48 kbps    11 -> 224 kbps"
	echo "3 -> 56 kbps    12 -> 256 kbps"
	echo "4 -> 64 kbps    13 -> 320 kbps"
	echo "5 -> 80 kbps    14 -> 448 kbps"
	echo "6 -> 96 kbps    15 -> 512 kbps"
	echo "7 -> 112 kbps   16 -> 576 kbps"
	echo "8 -> 128 kbps   17 -> 640 kbps"
	echo ""
	printf "Select the AC3 Audio Bitrate [default is 10]: "
	read ab
	case "$ab" in
		0) abitrate="32" ;;
		1) abitrate="40" ;;
		2) abitrate="48" ;;
		3) abitrate="56" ;;
		4) abitrate="64" ;;
		5) abitrate="80" ;;
		6) abitrate="96" ;;
		7) abitrate="112" ;;
		8) abitrate="128" ;;
		9) abitrate="160" ;;
		10|"") abitrate="192" ;;
		11) abitrate="224" ;;
		12) abitrate="256" ;;
		13) abitrate="320" ;;
		14) abitrate="448" ;;
		15) abitrate="512" ;;
		16) abitrate="576" ;;
		17) abitrate="640" ;;
		*) error "-> Unknown option: '$ab'"; rmconf ;;
	esac
	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
	acodec="-oac lavc -lavcopts acodec=ac3:abitrate=$abitrate"
}

aac_audio_func() {
	printf "Which MPEG version to use for AAC audio? [2/4 - default is 4]: "
	read mpeg_ver
	case "$mpeg_ver" in
		2) mpeg_version="mpeg=2" ;;
		4|""|*) mpeg_version="mpeg=4" ;;
	esac
	printf "Specify the AAC Audio Encoding Mode [ABR/VBR - default is ABR]: "
	read aacmode
	case "$aacmode" in
		ABR|abr|A*|a*|"")
		printf "Specify the AAC Average Audio Bitrate [default is 110]: "
		read abitrate
		if [ -z "$abitrate" ]; then
			br=":br=110"
		else
			br=":br=$abitrate"
		fi
		;;
		VBR|vbr|V*|v*)
		printf "Specify the AAC Audio Quality [1-1000 - default is 100]: "
		read abitrate
		if [ -z "$abitrate" ]; then
			br=":quality=100"
		else
			br=":quality=$abitrate"
		fi
		;;
		*)
		error "-> Unknown AAC audio encoding mode: '$aacmode'"
		rmconf
		;;
	esac
	# Main --> 1
	# LC ----> 2
	# SRS ---> 3
	# LTP ---> 4
	echo ""
	brown "AAC Object Type Complexity Profiles"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> Main"
	echo "1 -> Low Complexity (LC-AAC)"
	echo "2 -> Long Term Prediction (LTP-AAC)"
	echo ""
	printf "Select a AAC Object Type Complexity Profile [default is 1]: "
	read objtype
	case "$objtype" in
		0) object=":object=1" ;;
		1|"") object=":object=2" ;;
		2) object=":object=4" ;;
		*) error "-> Unknown AAC profile: '$objtype'"; rmconf ;;
	esac
	printf "Enable AAC 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
	acodec="-oac faac -faacopts $mpeg_version$br$object$tns"
}

aacplus_audio_func() {
	printf "Specify the AAC+ Encoding Mode [ABR/CBR/VBR - default is ABR]: "
	read aacmode
	case "$aacmode" in
		a*|A*|"")
		printf "Specify the AAC+ Average Audio Bitrate in kbps [default is 100]: "
		read ab
		if [ -z "$ab" ]; then
			aacplusbr="-br 100000 -he"
		else
			aacplusbr="-br ${ab}000 -he"
		fi
		;;
		c*|C*)
		echo ""
		brown "AAC+ Audio Bitrates"
		brown "~~~~~~~~~~~~~~~~~~~"
		echo "0 -> 32 kbps   7 --> 112 kbps"
		echo "1 -> 40 kbps   8 --> 128 kbps"
		echo "2 -> 48 kbps   9 --> 160 kbps"
		echo "3 -> 56 kbps   10 -> 192 kbps"
		echo "4 -> 64 kbps   11 -> 224 kbps"
		echo "5 -> 80 kbps   12 -> 256 kbps"
		echo "6 -> 96 kbps   13 -> 320 kbps"
		echo ""
		printf "Select the AAC+ Audio Bitrate [default is 6]: "
		read ab
		case "$ab" in
			0) aacplusbr="-cbr 32000 -he" ;;
			1) aacplusbr="-cbr 40000 -he" ;;
			2) aacplusbr="-cbr 48000 -he" ;;
			3) aacplusbr="-cbr 56000 -he" ;;
			4) aacplusbr="-cbr 64000 -he" ;;
			5) aacplusbr="-cbr 80000 -he" ;;
			6|"") aacplusbr="-cbr 96000 -he" ;;
			7) aacplusbr="-cbr 112000 -he" ;;
			8) aacplusbr="-cbr 128000 -he" ;;
			9) aacplusbr="-cbr 160000 -he" ;;
			10) aacplusbr="-cbr 192000 -he" ;;
			11) aacplusbr="-cbr 224000 -he" ;;
			12) aacplusbr="-cbr 256000 -he" ;;
			13) aacplusbr="-cbr 320000 -he" ;;
			*) error "-> Unknown option: '$ab'"; rmconf ;;
		esac
		;;
		v*|V*)
		printf "Specify the AAC+ Audio Quality [0.00-1.00 - default is 0.35]: "
		read ab
		if [ -z "$ab" ]; then
			aacplusbr="-q 0.35 -he"
		else
			aacplusbr="-q $ab -he"
		fi
		;;
		*) error "-> Unknown option: '$aacmode'"; rmconf ;;
	esac
}

vorbis_audio_func() {
	printf "Specify the Vorbis Audio Quality [-1-10 - default is 3]: "
	read ab
	if [ ! -z "$(echo $ab | grep '\.')" ]; then
		error "-> Floating point values are not supported at the moment!"
		rmconf
	fi
	if [ -z "$ab" ]; then
		vorbq="-q 3"
	else
		vorbq="-q $ab"
	fi
}

wma_audio_func() {
	printf "Which WMA version to use? [v1/v2 - default is v2]: "
	read wma_ver
	case "$wma_ver" in
		v1) wma_version=wmav1 ;;
		v2|"") wma_version=wmav2 ;;
		*)
		error "-> '$wma_ver' is not a valid WMA version!"
		rmconf
		;;
	esac
	echo ""
	brown "WMA Audio Bitrates"
	brown "~~~~~~~~~~~~~~~~~~"
	echo "0 -> 32 kbps   7 --> 112 kbps"
	echo "1 -> 40 kbps   8 --> 128 kbps"
	echo "2 -> 48 kbps   9 --> 160 kbps"
	echo "3 -> 56 kbps   10 -> 192 kbps"
	echo "4 -> 64 kbps   11 -> 224 kbps"
	echo "5 -> 80 kbps   12 -> 256 kbps"
	echo "6 -> 96 kbps   13 -> 320 kbps"
	echo ""
	printf "Select the WMA Audio Bitrate [default is 8]: "
	read ab
	case "$ab" in
		0) abitrate="32" ;;
		1) abitrate="40" ;;
		2) abitrate="48" ;;
		3) abitrate="56" ;;
		4) abitrate="64" ;;
		5) abitrate="80" ;;
		6) abitrate="96" ;;
		7) abitrate="112" ;;
		8|"") abitrate="128" ;;
		9) abitrate="160" ;;
		10) abitrate="192" ;;
		11) abitrate="224" ;;
		12) abitrate="256" ;;
		13) abitrate="320" ;;
		*) error "-> Unknown option: '$ab'"; rmconf ;;
	esac
	acodec="-oac lavc -lavcopts acodec=$wma_version:abitrate=$abitrate"
	channels=
	ac3drc=
}

sonic_audio_func() {
	printf "Specify the Sonic Audio Bitrate [default is 128]: "
	read ab
	if [ -z "$ab" ]; then
		abitrate=128
	else
		abitrate=$ab
	fi
	acodec="-oac lavc -lavcopts acodec=sonic:abitrate=$abitrate"
	channels=
	ac3drc=
}

echo ""
brown "Available Audio Codecs"
brown "~~~~~~~~~~~~~~~~~~~~~~"
echo "MP2 -----> Container support: AVI/MP4"
echo "MP3 -----> Container support: AVI/MKV/MP4/OGM"
echo "AC3 -----> Container support: AVI/MKV/OGM"
echo "AAC -----> Container support: AVI/MKV/MP4"
echo "AAC+ ----> Container support: MP4"
echo "VORBIS --> Container support: MP4"
echo "WMA -----> Container support: AVI"
echo "SONIC ---> Container support: AVI"
echo "SONICLS -> Container support: AVI"
echo "FLAC ----> Container support: AVI"
echo "PCM -----> Container support: AVI/MKV/OGM"
echo "ADPCM ---> Container support: AVI"
echo "COPY ----> Container support: Depends on audio codec"
echo "NOSOUND -> Container support: AVI/MKV/MP4/OGM"
echo ""
printf "Select the Audio Codec [default is MP3]: "
read audiocodec
case "$audiocodec" in
	MP2|mp2)
	check_audio_codec_func
	mp2_audio_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume$resample"
	;;
	MP3|mp3|"")
	check_audio_codec_func
	mp3_audio_func
	audio_resample_func
	afilters="$resample"
	;;
	AC3|ac3)
	check_audio_codec_func
	ac3_audio_func
	audio_channels_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume$resample"
	;;
	AAC|aac)
	check_audio_codec_func
	aac_audio_func
	audio_channels_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume$resample"
	ac3drc=
	;;
	AAC+|aac+)
	check_audio_codec_func
	aacplus_audio_func
	#audio_channels_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume$resample"
	# Encode to PCM. We'll encode
	# it to AAC+ later on
	acodec="-oac pcm"
	;;
	VORBIS|vorbis)
	check_audio_codec_func
	vorbis_audio_func
	audio_channels_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume$resample"
	# Encode to PCM. We'll encode
	# it to Vorbis later on
	acodec="-oac pcm"
	;;
	WMA|wma)
	check_audio_codec_func
	wma_audio_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume$resample"
	;;
	SONIC|sonic)
	check_audio_codec_func
	sonic_audio_func
	#audio_resample_func
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume$resample"
	channels=
	ac3drc=
	;;
	SONICLS|sonicls)
	check_audio_codec_func
	#audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac lavc -lavcopts acodec=sonicls"
	afilters="$volnorm$volume$resample"
	;;
	FLAC|flac)
	check_audio_codec_func
	audio_channels_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac lavc -lavcopts acodec=flac"
	afilters="$volnorm$volume$resample"
	ac3drc=
	;;
	PCM|pcm)
	check_audio_codec_func
	audio_channels_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac pcm"
	afilters="$volnorm$volume$resample"
	ac3drc=
	;;
	ADPCM|adpcm)
	check_audio_codec_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac lavc -lavcopts acodec=adpcm_ima_wav"
	afilters="$volnorm$volume$resample"
	channels=
	ac3drc=
	;;
	COPY|copy)
	check_audio_codec_func
	audio_channels_func
	acodec="-oac copy"
	afilters=
	ac3drc=
	;;
	NOSOUND|nosound)
	acodec="-nosound"
	aid=
	afilters=
	channels=
	ac3drc=
	;;
	*)
	error "-> Unknown audio codec: '$audiocodec'"
	rmconf
	;;
esac

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

# 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|AAC+|aac+|VORBIS|vorbis|WMA|wma|PCM|pcm|SONIC|sonic|COPY|copy|NOSOUND|nosound|"")
		printf "Would you like to set a target file size? [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
			case "$aacmode" in
				v*|V*)
				echo ""
				green "-> You have chosen to use quality based audio mode (VBR)."
				green "-> Currently xvidenc does not support video bitrate"
				green "   calculation with VBR AAC(+) audio!"
				echo ""
				;;
				*|"")
				echo ""
				brown "Video Bitrate Calculation/Target File Size"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				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|AC3|ac3|WMA|wma|SONIC|sonic)
					AUDIO_BITRATE=$abitrate
					;;
					MP3|mp3|"")
					case "$mp3mode" in
						CBR|cbr|C*|c*|ABR|abr|A*|a*|"")
						AUDIO_BITRATE=$(echo $abitrate | awk -F= '{print $2}')
						;;
						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
					;;
					AAC|aac)
					APPRO="~"
					AUDIO_BITRATE=$(echo $br | awk -F= '{print $2}')
					;;
					AAC+|aac+)
					APPRO="~"
					AUDIO_BITRATE=$(($(echo $aacplusbr | awk '{print $2}')/1000))
					;;
					VORBIS|vorbis)
					APPRO="~"
					case "$(echo $vorbq | awk '{print $2}')" in
						-1) AUDIO_BITRATE=45 ;;
						0) AUDIO_BITRATE=64 ;;
						1) AUDIO_BITRATE=80 ;;
						2) AUDIO_BITRATE=96 ;;
						3) AUDIO_BITRATE=112 ;;
						4) AUDIO_BITRATE=128 ;;
						5) AUDIO_BITRATE=160 ;;
						6) AUDIO_BITRATE=192 ;;
						7) AUDIO_BITRATE=224 ;;
						8) AUDIO_BITRATE=256 ;;
						9) AUDIO_BITRATE=320 ;;
						10) AUDIO_BITRATE=500 ;;
					esac
					;;
					PCM|pcm)
					# Get channels info. Resampling is not
					# taken into account so we assume 48 kHz
					case "$(echo $channels | awk '{print $2}')" in
						2|""|*) AUDIO_BITRATE=1536 ;;
						4) AUDIO_BITRATE=3072 ;;
						5) AUDIO_BITRATE=3840 ;;
						6) AUDIO_BITRATE=4608 ;;
					esac
					;;
					COPY|copy)
					# Lets hope this works
					# for most sources
					mplayer "$sourcetype" $device $aid -identify -vo null -frames 1 -nocache 2>/dev/null > $CONFIGDIR/audio_copy
					AUDIO_BITRATE=$(echo $(($(grep '^ID_AUDIO_BITRATE' $CONFIGDIR/audio_copy | tail -1 | awk -F= '{print $2}')/1000)) | awk -F. '{print $1}')
					rm -f $CONFIGDIR/audio_copy
					;;
				esac
				# Get video length and calculate the video bitrate
				# based on the length, audio bitrate and target file
				# size.
				echo ""
				green "-> Detecting video length..."
				mplayer "$sourcetype" $device $vid -identify -vo null -frames 1 -nosound -nocache 2>/dev/null > $CONFIGDIR/video_length
				VIDEO_LENGTH=$(grep "^ID_LENGTH" $CONFIGDIR/video_length | cut -f '2' -d '=' | cut -f '1' -d '.')
				rm -f $CONFIGDIR/video_length
				if [ -z "$VIDEO_LENGTH" ]; then
					echo ""
					green "-> Could not detect video length!"
					green "-> Will skip video bitrate calculation!"
					echo ""
				else
					case "$audiocodec" in
						nosound|NOSOUND) EST_BITRATE=$(($TARGET_SIZE*8192/$VIDEO_LENGTH)) ;;
						*|"") EST_BITRATE=$(($(($TARGET_SIZE*8192/$VIDEO_LENGTH))-$AUDIO_BITRATE)) ;;
					esac
					bits_per_pixel_func
					bits_per_block_func
					green "-> Video length is $(($VIDEO_LENGTH/60)) minutes or $VIDEO_LENGTH seconds"
					case "$audiocodec" in
						nosound|NOSOUND) false ;;
						*|"") green "-> Chosen/detected audio bitrate is $APPRO$AUDIO_BITRATE kbps" ;;
					esac
					echo ""
					green "-> Estimated video bitrate for $TARGET_SIZE MB is: $EST_BITRATE kbps"
					green "-> Bits Per Pixel value: $BPP bpp"
					green "-> Bits Per Block value: $BPB bpb"
					echo ""
					printf "Specify the new video bitrate in kbps [default is $EST_BITRATE]: "
					read new_bitrate
					if [ -z "$new_bitrate" ]; then
						vbitrate="bitrate=$EST_BITRATE"
					else
						vbitrate="bitrate=$new_bitrate"
					fi
				fi
				;;
			esac
		fi
		;;
	esac
	;;
esac

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

# Audio/video filters variables for all
# passes. Since all filters are the same in
# each pass, we put them in a single
# variable to reduce code duplication and
# filter maintenance.
#
# The softskip filter should come after filters
# which need to see duplicate or skipped frames
# in order to operate correct. This includes any
# filter that does temporal processing, like the
# temporal denoiser, hqdn3d/denoise3d and all the
# inverse telecine filters. The softskip filter
# should also come before scaling so that the scale
# filter will be skipped if a frame is going to be
# dropped. Deinterlacing or pullup should be done
# before cropping. The harddup filter should be placed
# before the telecine one so that duplicate frames will
# never get telecined, we don't want that. The interlace
# filters should be placed after the softskip and scale
# filters and after the harddup filter. The (un)sharp /
# gaussian blur filter should come after the scale filter.
# The 'tfields' filter should come after the crop filter
# as it alters the resolution and MEncoder will error out
# with a "crop area outside of the original" message!
#
# Log file for 2-pass
PASSLOG="$CONFIGDIR/xvid.log"

if [ ! -z "$(echo $deintfilter | grep '^tfields')" ]; then
	videofilters="-vf $(echo $ivtcfilter$cropfilter$deintfilter$fpsfilter$ild$deblockfilter$denoisefilter$ili$brightnessfilter$colorspacefilter,softskip,$scale$isws$swsparam$unsharpfilter$noisefilter,harddup$intfilter$telecinefilter | sed -e 's/^,//' -e 's/,,/,/g' -e 's/,$//')"
else
	videofilters="-vf $(echo $ivtcfilter$deintfilter$cropfilter$fpsfilter$ild$deblockfilter$denoisefilter$ili$brightnessfilter$colorspacefilter,softskip,$scale$isws$swsparam$unsharpfilter$noisefilter,harddup$intfilter$telecinefilter | sed -e 's/^,//' -e 's/,,/,/g' -e 's/,$//')"
fi

if [ ! -z "$afilters" ]; then
	audiofilters="-af $(echo $afilters | sed -e 's/^,//' -e 's/,,/,/g' -e 's/,$//')"
else
	audiofilters=
fi

mencoder_opts() {
	case "$1" in
		-1p|-fq)
		echo "$priority_level mencoder \"$sourcetype\" -o \"$OUTPUT\" $chapters $device $dvdangle $vid $ffourcc $fps $ofps $videofilters $field_dominance $sws $aspect $sid $spuaa $vobsubout $spualign $spugauss $noodml $aid $audiofilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts $vbitrate$me_quality$vhq$threads$max_bframes$bvhq$packed$quant_type$qpel$gmc$trellis$interlacing$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$stats$advopts:closed_gop:autoaspect $quiet"
		;;
		-2p)
		# Pass one
		# do not use subs for the first pass
		echo "$priority_level mencoder \"$sourcetype\" -o /dev/null $chapters $device $dvdangle $vid $ffourcc $fps $ofps $videofilters $field_dominance $sws $aspect $noodml $aid $audiofilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts pass=1:turbo$me_quality$vhq$threads$max_bframes$bvhq$packed$quant_type$qpel$gmc$trellis$interlacing$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$advopts:closed_gop:autoaspect -passlogfile $PASSLOG $quiet"
		echo ""
		# Pass two
		echo "$priority_level mencoder \"$sourcetype\" -o \"$OUTPUT\" $chapters $device $dvdangle $vid $ffourcc $fps $ofps $videofilters $field_dominance $sws $aspect $sid $spuaa $vobsubout $spualign $spugauss $noodml $aid $audiofilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts pass=2:$vbitrate$me_quality$vhq$threads$max_bframes$bvhq$packed$quant_type$qpel$gmc$trellis$interlacing$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$stats$advopts:closed_gop:autoaspect -passlogfile $PASSLOG $quiet"
		;;
	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 ""
	brown "+===========================+"
	brown "| MEncoder encoding options |"
	brown "+===========================+"
	echo ""
	case "$1" in
		-1p|-fq)
		echo $(cat $XVID1PFQ)
		;;
		-2p)
		brown "First pass options"
		brown "~~~~~~~~~~~~~~~~~~"
		echo $(cat $XVID2P1)
		echo ""
		brown "Second pass options"
		brown "~~~~~~~~~~~~~~~~~~~"
		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 MEncoder options to a file? [y/n]: "
read saveopts
if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
	printf "Where to store the options? [default is $HOME/batchfile]: "
	read -e storeopts
	OPTSFILE="$HOME/batchfile"
	CMDSTART="################### START OF COMMANDS ###################"
	DIRTEST="test -d \"$(dirname "$OUTPUT")\" || mkdir -p \"$(dirname "$OUTPUT")\""
	CONFTEST="test -d $CONFIGDIR || mkdir -p $CONFIGDIR"
	FILETEST="test -e \"$OUTPUT\" && mv -f \"$OUTPUT\" \"$OUTPUT.old\""
	case "$1" in
		-1p|-fq)
		if [ -z "$storeopts" ]; then
			echo "$CMDSTART" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$DIRTEST" >> "$OPTSFILE"
			echo "$CONFTEST" >> "$OPTSFILE"
			echo "$FILETEST" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo $(cat $XVID1PFQ) >> "$OPTSFILE"
			echo "sleep 3" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
		else
			if [ -z "$(echo $storeopts | grep '^/')" ]; then
				error "-> You have to provide the full path!"
				rmconf
			else
				test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
				echo "$CMDSTART" >> "$storeopts"
				echo "" >> "$storeopts"
				echo "$DIRTEST" >> "$storeopts"
				echo "$CONFTEST" >> "$storeopts"
				echo "$FILETEST" >> "$storeopts"
				echo "" >> "$storeopts"
				echo $(cat $XVID1PFQ) >> "$storeopts"
				echo "sleep 3" >> "$storeopts"
				echo "" >> "$storeopts"
			fi
		fi
		;;
		-2p)
		if [ -z "$storeopts" ]; then
			echo "$CMDSTART" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$DIRTEST" >> "$OPTSFILE"
			echo "$CONFTEST" >> "$OPTSFILE"
			echo "$FILETEST" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo $(cat $XVID2P1) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo $(cat $XVID2P2) >> "$OPTSFILE"
			echo "sleep 3" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
		else
			if [ -z "$(echo $storeopts | grep '^/')" ]; then
				error "-> You have to provide the full path!"
				rmconf
			else
				test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
				echo "$CMDSTART" >> "$storeopts"
				echo "" >> "$storeopts"
				echo "$DIRTEST" >> "$storeopts"
				echo "$CONFTEST" >> "$storeopts"
				echo "$FILETEST" >> "$storeopts"
				echo "" >> "$storeopts"
				echo $(cat $XVID2P1) >> "$storeopts"
				echo "" >> "$storeopts"
				echo $(cat $XVID2P2) >> "$storeopts"
				echo "sleep 3" >> "$storeopts"
				echo "" >> "$storeopts"
			fi
		fi
		;;
	esac
fi

# For AAC+ and Vorbis audio
if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
	MENC="mencoder \"$OUTPUT\" -nosound -ovc copy -of rawvideo -o $CONFIGDIR/video.cmp"
	MPL="mplayer \"$OUTPUT\" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1"
	FIFO="mkfifo $CONFIGDIR/audio.wav"
	NERO="neroAacEnc -ignorelength $aacplusbr -if $CONFIGDIR/audio.wav -of $CONFIGDIR/audio.aac &"
	OGG="oggenc $vorbq $CONFIGDIR/audio.wav -o $CONFIGDIR/audio.ogg &"
	case "$audiocodec" in
		aac+|AAC+|vorbis|VORBIS)
		if [ -z "$storeopts" ]; then
			echo "$MENC" >> "$OPTSFILE"
			echo "sleep 3" >> "$OPTSFILE"
			echo "$FIFO" >> "$OPTSFILE"
			case "$audiocodec" in
				aac+|AAC+)
				echo "$NERO" >> "$OPTSFILE"
				echo "$MPL" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				;;
				vorbis|VORBIS)
				echo "$OGG" >> "$OPTSFILE"
				echo "$MPL" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				;;
			esac
		else
			echo "$MENC" >> "$storeopts"
			echo "sleep 3" >> "$storeopts"
			echo "$FIFO" >> "$storeopts"
			case "$audiocodec" in
				aac+|AAC+)
				echo "$NERO" >> "$storeopts"
				echo "$MPL" >> "$storeopts"
				echo "" >> "$storeopts"
				;;
				vorbis|VORBIS)
				echo "$OGG" >> "$storeopts"
				echo "$MPL" >> "$storeopts"
				echo "" >> "$storeopts"
				;;
			esac
		fi
		;;
	esac
fi

# Ask user if he wants to convert
# from AVI to Matroska container
case "$audiocodec" in
	mp[2-3]|MP[2-3]|aac|AAC|ac3|AC3|pcm|PCM|copy|COPY|nosound|NOSOUND|"")
	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
			MKVCHAPS=
			MKVSUB=
			echo ""
			green "-> Utility 'mkvmerge' is missing!"
			green "-> Will skip AVI to Matroska conversion!"
			echo ""
		else
			avi_to_mkv=yes
			if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
				printf "Import chapters information into the Matroska file? [y/n]: "
				read impchap
				if [ "$impchap" = "y" -o "$impchap" = "Y" ]; then
					MKVCHAPS="$CHAPTERSFILE"
				else
					MKVCHAPS=
				fi
			else
				MKVCHAPS=
			fi
			if [ ! -z "$vobsubout" ]; then
				printf "Import the ripped subtitle into the Matroska container? [y/n]: "
				read mkv_impsub
				if [ "$mkv_impsub" = "y" -o "$mkv_impsub" = "Y" ]; then
					MKVSUB="$IDXFILE"
				else
					MKVSUB=
				fi
			else
				MKVSUB=
			fi
			# Export muxing commands
			# to the options file
			if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
				MKVOUT=$(echo "$OUTPUT" | sed 's|\.avi|\.mkv|')
				MKVTEST="test -e \"$MKVOUT\" && mv -f \"$MKVOUT\" \"$MKVOUT.old\""
				if [ -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MKVTEST" >> "$storeopts"
						echo "mkvmerge \"$OUTPUT\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MKVTEST" >> "$OPTSFILE"
						echo "mkvmerge \"$OUTPUT\" -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ ! -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MKVTEST" >> "$storeopts"
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MKVTEST" >> "$OPTSFILE"
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MKVTEST" >> "$storeopts"
						echo "mkvmerge \"$OUTPUT\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MKVTEST" >> "$OPTSFILE"
						echo "mkvmerge \"$OUTPUT\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ ! -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MKVTEST" >> "$storeopts"
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MKVTEST" >> "$OPTSFILE"
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				fi
			fi
		fi
	elif [ "$avi_mkv" = "n" -o "$avi_mkv" = "N" -o -z "$avi_mkv" ]; then
		avi_to_mkv=no
		MKVCHAPS=
		MKVSUB=
	fi
	;;
	*|"")
	avi_to_mkv=no
	MKVCHAPS=
	MKVSUB=
	;;
esac

# Ask for AVI -> MP4 conversion
# This only works with MP2/MP3/AAC audio
# or NOSOUND as MP4Box doesn't support
# the other codecs
case "$audiocodec" in
	mp[2-3]|MP[2-3]|aac|AAC|aac+|AAC+|vorbis|VORBIS|nosound|NOSOUND|"")
	printf "Would you like to convert the final encode from AVI to MP4? [y/n]: "
	read avi_mp4
	if [ "$avi_mp4" = "y" -o "$avi_mp4" = "Y" ]; then
		if [ ! -x "$(which MP4Box 2>/dev/null)" ]; then
			avi_to_mp4=no
			MP4CHAPS=
			MP4SUB=
			echo ""
			green "-> MP4Box (from gpac) is missing!"
			green "-> Skipping AVI to MP4 conversion!"
			echo ""
		else
			avi_to_mp4=yes
			if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
				printf "Import chapters information into the MP4 file? [y/n]: "
				read impchap
				if [ "$impchap" = "y" -o "$impchap" = "Y" ]; then
					MP4CHAPS="$CHAPTERSFILE"
				else
					MP4CHAPS=
				fi
			else
				MP4CHAPS=
			fi
			if [ ! -z "$vobsubout" ]; then
				printf "Import the ripped subtitle into the MP4 container? [y/n]: "
				read mp4_impsub
				if [ "$mp4_impsub" = "y" -o "$mp4_impsub" = "Y" ]; then
					MP4SUB="$IDXFILE"
				else
					MP4SUB=
				fi
			else
				MP4SUB=
			fi
			# Export muxing commands
			# to the options file
			if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
				case "$audiocodec" in
					mp2|MP2)
					MVRAW="mv -f $CONFIGDIR/*.raw $CONFIGDIR/audio.m2a"
					AUDIOFILE="m2a.raw"
					AUDIOINPUT="-add $CONFIGDIR/*.m2a"
					;;
					mp3|MP3|"")
					MVRAW=
					AUDIOFILE="mp3.mp3"
					AUDIOINPUT="-add $CONFIGDIR/*.mp3"
					;;
					aac|AAC)
					MVRAW="mv -f $CONFIGDIR/*.raw $CONFIGDIR/audio.aac"
					AUDIOFILE="aac.raw"
					AUDIOINPUT="-add $CONFIGDIR/*.aac"
					;;
					aac+|AAC+)
					MVRAW=
					AUDIOFILE=
					AUDIOINPUT="-add $CONFIGDIR/*.aac -sbr"
					;;
					vorbis|VORBIS)
					MVRAW=
					AUDIOFILE=
					AUDIOINPUT="-add $CONFIGDIR/*.ogg"
					;;
					nosound|NOSOUND)
					MVRAW=
					AUDIOFILE=
					AUDIOINPUT=
					;;
				esac
				MP4OUT=$(echo "$OUTPUT" | sed 's|\.avi|\.mp4|')
				MP4FPS="-fps `echo $`(mplayer \"$OUTPUT\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print `echo $`2}')"
				MP4TEST="test -e \"$MP4OUT\" && mv -f \"$MP4OUT\" \"$MP4OUT.old\""
				VIDEOINPUT="-add $CONFIGDIR/*.cmp"
				case "$audiocodec" in
					aac+|AAC+|vorbis|VORBIS)
					MP4VID=
					MP4AUD=
					;;
					nosound|NOSOUND)
					MP4VID="MP4Box -aviraw video \"$OUTPUT\" -out $CONFIGDIR/xvid.cmp"
					MP4AUD=
					;;
					mp[2-3]|MP[2-3]|aac|AAC|"")
					MP4VID="MP4Box -aviraw video \"$OUTPUT\" -out $CONFIGDIR/xvid.cmp"
					MP4AUD="MP4Box -aviraw audio \"$OUTPUT\" -out $CONFIGDIR/$AUDIOFILE"
					;;
				esac
				if [ -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MP4VID" >> "$storeopts"
						echo "$MP4AUD" >> "$storeopts"
						echo "$MVRAW" >> "$storeopts"
						echo "$MP4TEST" >> "$storeopts"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT \"$MP4OUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4TEST" >> "$OPTSFILE"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT \"$MP4OUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ ! -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MP4VID" >> "$storeopts"
						echo "$MP4AUD" >> "$storeopts"
						echo "$MVRAW" >> "$storeopts"
						echo "$MP4TEST" >> "$storeopts"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT -chap \"$MP4CHAPS\" \"$MP4OUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4TEST" >> "$OPTSFILE"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT -chap \"$MP4CHAPS\" \"$MP4OUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MP4VID" >> "$storeopts"
						echo "$MP4AUD" >> "$storeopts"
						echo "$MVRAW" >> "$storeopts"
						echo "$MP4TEST" >> "$storeopts"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT -add \"$MP4SUB\" \"$MP4OUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4TEST" >> "$OPTSFILE"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT -add \"$MP4SUB\" \"$MP4OUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ ! -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MP4VID" >> "$storeopts"
						echo "$MP4AUD" >> "$storeopts"
						echo "$MVRAW" >> "$storeopts"
						echo "$MP4TEST" >> "$storeopts"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT -chap \"$MP4CHAPS\" -add \"$MP4SUB\" \"$MP4OUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4TEST" >> "$OPTSFILE"
						echo "MP4Box $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT -chap \"$MP4CHAPS\" -add \"$MP4SUB\" \"$MP4OUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				fi
			fi
		fi
	elif [ "$avi_mp4" = "n" -o "$avi_mp4" = "N" -o -z "$avi_mp4" ]; then
		avi_to_mp4=no
		MP4CHAPS=
		MP4SUB=
	fi
	;;
	*)
	avi_to_mp4=no
	MP4CHAPS=
	MP4SUB=
	;;
esac

# Ask for AVI -> OGM
case "$audiocodec" in
	mp3|MP3|ac3|AC3|pcm|PCM|copy|COPY|nosound|NOSOUND|"")
	printf "Would you like to convert the final encode from AVI to OGM? [y/n]: "
	read avi_ogm
	if [ "$avi_ogm" = "y" -o "$avi_ogm" = "Y" ]; then
		# Check for ogmmerge
		if [ ! -x "$(which ogmmerge 2>/dev/null)" ]; then
			avi_to_ogm=no
			OGMCHAPS=
			echo ""
			green "-> Utility 'ogmmerge' is missing!"
			green "-> Skipping AVI to OGM conversion!"
		else
			avi_to_ogm=yes
			if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
				printf "Import chapters information into the OGM container? [y/n]: "
				read ogm_impchap
				if [ "$ogm_impchap" = "y" -o "$ogm_impchap" = "Y" ]; then
					OGMCHAPS="$CHAPTERSFILE"
				else
					OGMCHAPS=
				fi
			else
				OGMCHAPS=
			fi
			# Export muxing commands
			# to the options file
			if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
				OGMOUT=$(echo "$OUTPUT" | sed 's|\.avi|\.ogm|')
				OGMTEST="test -e \"$OGMOUT\" && mv -f \"$OGMOUT\" \"$OGMOUT.old\""
				if [ -z "$OGMCHAPS" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$OGMTEST" >> "$storeopts"
						echo "ogmmerge \"$OUTPUT\" -o \"$OGMOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$OGMTEST" >> "$OPTSFILE"
						echo "ogmmerge \"$OUTPUT\" -o \"$OGMOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ ! -z "$OGMCHAPS" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$OGMTEST" >> "$storeopts"
						echo "ogmmerge \"$OUTPUT\" -c \"$OGMCHAPS\" -o \"$OGMOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$OGMTEST" >> "$OPTSFILE"
						echo "ogmmerge \"$OUTPUT\" -c \"$OGMCHAPS\" -o \"$OGMOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				fi
			fi
		fi
	elif [ "$avi_ogm" = "n" -o "$avi_ogm" = "N" -o -z "$avi_ogm" ]; then
		avi_to_ogm=no
		OGMCHAPS=
	fi
	;;
	*|"")
	avi_to_ogm=no
	OGMCHAPS=
	;;
esac

if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
	if [ -z "$storeopts" ]; then
		echo "rm -rf $CONFIGDIR" >> "$OPTSFILE"
		echo "" >> "$OPTSFILE"
		echo "#################### END OF COMMANDS ####################" >> "$OPTSFILE"
		echo "" >> "$OPTSFILE"
	else
		echo "rm -rf $CONFIGDIR" >> "$storeopts"
		echo "" >> "$storeopts"
		echo "#################### END OF COMMANDS ####################" >> "$storeopts"
		echo "" >> "$storeopts"
	fi
fi

echo ""
case "$1" in
	-1p)
	green "-> Starting to encode the $source in 1-pass mode"
	display_quality_preset_func $3
	green "-> Will use '$OUTPUT' as output file"
	;;
	-fq)
	green "-> Starting to encode the $source in fixed-quant mode"
	display_quality_preset_func $3
	green "-> Will use '$OUTPUT' as output file"
	;;
	-2p)
	green "-> Starting to encode the $source in 2-pass mode"
	display_quality_preset_func $3
	green "-> Will use '/dev/null' as output for the first pass"
	green "-> 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 :)
counter() {
	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
}

mencoder_exit() {
	if [ $? != 0 ]; then
		rm -rf $CONFIGDIR
		error "-> MEncoder exited with a non-zero status!"
		exit 1
	fi
}

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


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

rm -f $CONFIGDIR/*

# Extract audio and video and then
# encode audio to AAC+ or Vorbis.
if [ "$avi_to_mp4" = "yes" ]; then
	case "$audiocodec" in
		aac+|AAC+|vorbis|VORBIS)
		echo ""
		green "-> Extracting video from the AVI file, please wait..."
		sleep 2
		mencoder "$OUTPUT" -nosound -ovc copy -of rawvideo -o $CONFIGDIR/video.cmp >/dev/null 2>&1
		mkfifo $CONFIGDIR/audio.wav
		case "$audiocodec" in
			aac+|AAC+)
			green "-> Encoding audio with 'neroAacEnc' to AAC+, please wait..."
			sleep 2
			echo ""
			neroAacEnc -ignorelength $aacplusbr -if $CONFIGDIR/audio.wav -of $CONFIGDIR/audio.aac &
			mplayer "$OUTPUT" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1
			;;
			vorbis|VORBIS)
			green "-> Encoding audio with 'oggenc' to Vorbis, please wait..."
			sleep 2
			echo ""
			oggenc $vorbq $CONFIGDIR/audio.wav -o $CONFIGDIR/audio.ogg &
			mplayer "$OUTPUT" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1
			;;
		esac
		rm -f $CONFIGDIR/audio.wav
		;;
	esac
fi

#######################################################
########### Container conversion (MKV/MP4) ############
#######################################################

# AVI -> MKV conversion

if [ "$avi_to_mkv" = "yes" ]; then
	OUTPUT_MKV="$(echo "$OUTPUT" | sed 's|\.avi|\.mkv|')"
	test -e "$OUTPUT_MKV" && mv -f "$OUTPUT_MKV" "$OUTPUT_MKV.old"
	echo ""
	green "-> Will now convert the AVI file to Matroska..."
	sleep 3
	green "-> Converting AVI to the Matroska container, please wait..."
	if [ -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
		mkvmerge "$OUTPUT" -o "$OUTPUT_MKV" >/dev/null 2>&1
	elif [ ! -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
		mkvmerge "$OUTPUT" --chapters "$MKVCHAPS" -o "$OUTPUT_MKV" >/dev/null 2>&1
	elif [ -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
		mkvmerge "$OUTPUT" "$MKVSUB" -o "$OUTPUT_MKV" >/dev/null 2>&1
	elif [ ! -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
		mkvmerge "$OUTPUT" --chapters "$MKVCHAPS" "$MKVSUB" -o "$OUTPUT_MKV" >/dev/null 2>&1
	fi
	if [ -e "$OUTPUT_MKV" ]; then
		green "-> Done"
	else
		error "-> Failed!"
	fi
fi

# AVI -> OGM

if [ "$avi_to_ogm" = "yes" ]; then
	OUTPUT_OGM="$(echo "$OUTPUT" | sed 's|\.avi|\.ogm|')"
	test -e "$OUTPUT_OGM" && mv -f "$OUTPUT_OGM" "$OUTPUT_OGM.old"
	echo ""
	green "-> Will now convert the AVI file to OGM..."
	sleep 3
	green "-> Converting AVI to the OGM container, please wait..."
	if [ -z "$OGMCHAPS" ]; then
		ogmmerge -o "$OUTPUT_OGM" "$OUTPUT" >/dev/null 2>&1
	elif [ ! -z "$OGMCHAPS" ]; then
		ogmmerge -o "$OUTPUT_OGM" -c "$OGMCHAPS" "$OUTPUT" >/dev/null 2>&1
	fi
	if [ -e "$OUTPUT_OGM" ]; then
		green "-> Done"
	else
		error "-> Failed!"
	fi
fi

# AVI -> MP4 conversion
#
# MP4Box does not detect the video FPS value
# and falls back to 25 FPS. We need to pass
# the correct FPS value to MP4Box if the input
# source has a different FPS, like in NTSC or
# Progressive NTSC content. Failing to provide the
# correct value will result in A/V desync!

mp4_fps_func() {
	mplayer "$OUTPUT" -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/mp4fps
	MP4FPS="$(grep '^ID_VIDEO_FPS' $CONFIGDIR/mp4fps | tail -1 | awk -F= '{print $2}')"
	rm -f $CONFIGDIR/mp4fps
	
}

if [ "$avi_to_mp4" = "yes" ]; then
	OUTPUT_MP4="$(echo "$OUTPUT" | sed 's|\.avi|\.mp4|')"
	test -e "$OUTPUT_MP4" && mv -f "$OUTPUT_MP4" "$OUTPUT_MP4.old"
	echo ""
	case "$audiocodec" in
		mp2|MP2)
		green "-> Will now convert the AVI file to MP4..."
		sleep 3
		green "-> Extracting video from the AVI file, please wait..."
		MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/xvid.cmp >/dev/null 2>&1
		green "-> Extracting audio from the AVI file, please wait..."
		MP4Box -aviraw audio "$OUTPUT" -out $CONFIGDIR/mp2.raw >/dev/null 2>&1
		mv -f $CONFIGDIR/*.raw $CONFIGDIR/audio.m2a
		VIDEOFILE="-add $CONFIGDIR/*.cmp"
		AUDIOFILE="-add $CONFIGDIR/*.m2a"
		;;
		mp3|MP3|"")
		green "-> Will now convert the AVI file to MP4..."
		sleep 3
		green "-> Extracting video from the AVI file, please wait..."
		MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/xvid.cmp >/dev/null 2>&1
		green "-> Extracting audio from the AVI file, please wait..."
		MP4Box -aviraw audio "$OUTPUT" -out $CONFIGDIR/mp3.mp3 >/dev/null 2>&1
		VIDEOFILE="-add $CONFIGDIR/*.cmp"
		AUDIOFILE="-add $CONFIGDIR/*.mp3"
		;;
		aac|AAC)
		green "-> Will now convert the AVI file to MP4..."
		sleep 3
		green "-> Extracting video from the AVI file, please wait..."
		MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/xvid.cmp >/dev/null 2>&1
		green "-> Extracting audio from the AVI file, please wait..."
		MP4Box -aviraw audio "$OUTPUT" -out $CONFIGDIR/aac.raw >/dev/null 2>&1
		mv -f $CONFIGDIR/*.raw $CONFIGDIR/audio.aac
		VIDEOFILE="-add $CONFIGDIR/*.cmp"
		AUDIOFILE="-add $CONFIGDIR/*.aac"
		;;
		aac+|AAC+)
		# Video and audio are already extracted
		VIDEOFILE="-add $CONFIGDIR/*.cmp"
		AUDIOFILE="-add $CONFIGDIR/*.aac -sbr"
		;;
		vorbis|VORBIS)
		# Video and audio are already extracted
		VIDEOFILE="-add $CONFIGDIR/*.cmp"
		AUDIOFILE="-add $CONFIGDIR/*.ogg"
		;;
		nosound|NOSOUND)
		green "-> Extracting video from the AVI file, please wait..."
		MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/h264.h264 >/dev/null 2>&1
		VIDEOFILE="-add $CONFIGDIR/*.cmp"
		AUDIOFILE=
		;;
	esac
	mp4_fps_func
	green "-> Muxing audio and video into the MP4 container, please wait..."
	if [ -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
		MP4Box -fps $MP4FPS -tmp $CONFIGDIR $VIDEOFILE $AUDIOFILE "$OUTPUT_MP4" >/dev/null 2>&1
	elif [ ! -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
		MP4Box -fps $MP4FPS -tmp $CONFIGDIR $VIDEOFILE $AUDIOFILE -chap "$MP4CHAPS" "$OUTPUT_MP4" >/dev/null 2>&1
	elif [ -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
		MP4Box -fps $MP4FPS -tmp $CONFIGDIR $VIDEOFILE $AUDIOFILE -add "$MP4SUB" "$OUTPUT_MP4" >/dev/null 2>&1
	elif [ ! -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
		MP4Box -fps $MP4FPS -tmp $CONFIGDIR $VIDEOFILE $AUDIOFILE -chap "$MP4CHAPS" -add "$MP4SUB" "$OUTPUT_MP4" >/dev/null 2>&1
	fi
	if [ -e "$OUTPUT_MP4" ]; then
		green "-> Done"
	else
		error "-> Failed!"
	fi
fi

rm -rf $CONFIGDIR

# Report final file size
FSIZE_AVI=$(echo "scale=3; $(stat -c %s "$OUTPUT" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
echo ""
green "-> AVI file size is: $FSIZE_AVI MB"
if [ "$avi_to_mkv" = "yes" ]; then
	if [ -e "$OUTPUT_MKV" ]; then
		FSIZE_MKV=$(echo "scale=3; $(stat -c %s "$OUTPUT_MKV" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
		green "-> MKV file size is: $FSIZE_MKV MB"
	fi
fi
if [ "$avi_to_mp4" = "yes" ]; then
	if [ -e "$OUTPUT_MP4" ]; then
		FSIZE_MP4=$(echo "scale=3; $(stat -c %s "$OUTPUT_MP4" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
		green "-> MP4 file size is: $FSIZE_MP4 MB"
	fi
fi
if [ "$avi_to_ogm" = "yes" ]; then
	if [ -e "$OUTPUT_OGM" ]; then
		FSIZE_OGM=$(echo "scale=3; $(stat -c %s "$OUTPUT_OGM" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
		green "-> OGM file size is: $FSIZE_OGM MB"
	fi
fi

if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" -o "$avi_to_ogm" = "yes" ]; then
	echo ""
	printf "Delete the original AVI file? [y/n]: "
	read delavi
	if [ "$delavi" = "y" -o "$delavi" = "Y" ]; then
		rm -f "$OUTPUT"
	fi
fi
echo ""
brown "-> Have a nice day ^_^"
echo ""

exit 0
