#!/bin/bash
# $Id: xvidenc, v 7.6.3, 2008/02/06, 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/local/bin
version=7.6.3

case "$1" in
	"")
	echo "Usage: $(basename $0) [-1p|-2p|-fq|-o|-sc|-scan|-bpp|-bpb|-p help|-v] [-p <preset>]"
	echo "       For more info use the --help option"
	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.0rc1 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 " -o <path/to/file/optionsfile>"
	echo ""
	echo "             Load a options file generated by *this* script from"
	echo "             a previous encoding. This will skip *all* internal"
	echo "             options of the script and will directly execute"
	echo "             MEncoder with the options from the given file."
	echo "             NOTE: this is not recommended and is only meant for"
	echo "                   debugging purposes! The options file is only"
	echo "                   useful if you want to encode the *exact* same"
	echo "                   DVD or video file one more time, or if you have"
	echo "                   found a bug in this script and want to inspect"
	echo "                   where it went wrong in collecting and passing the"
	echo "                   options to MEncoder"
	echo ""
	echo " -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 " -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 " -p help     Display quick help on available quality presets and how"
	echo "             to use them."
	echo ""
	echo " <passmode> -p <preset>"
	echo ""
	echo "             Use a predefined Xvid quality preset, where <passmode> is the"
	echo "             desired encoding mode (-1p or -2p or -fq) and <preset> is the"
	echo "             desired quality preset to use (see below). Presets are supported"
	echo "             by all encoding modes with the exception of the Near Lossless"
	echo "             Quality (NLQ) preset which is supported only in Fixed-Quant (-fq)"
	echo "             mode, and do not work if you use the -o option."
	echo "             You can choose from 11 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 ""
	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 " -v          Display version of this script and exit"
	echo ""
	echo " --help      Display this help screen and exit"
	echo ""
	echo "For bug reporting, suggestions, comments, questions or if this script"
	echo "was useful to you, send me an e-mail at <neutrino8@gmail.com>"
	echo ""
	exit 0
	;;
	-p)
	# If user needs quick help/info on quality
	# presets, display it and exit
	case "$2" in
		help)
		echo ""
		echo "Available Quality Presets"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "ulq -> Ultra Low Quality (ULQ)"
		echo "elq -> Extreme Low Quality (ELQ)"
		echo "vlq -> Very Low Quality (VLQ)"
		echo "lq --> Low Quality (LQ)"
		echo "mq --> Medium Quality (MQ)"
		echo "nq --> Normal Quality (NQ)"
		echo "hq --> High Quality (HQ)"
		echo "vhq -> Very High Quality (VHQ) (recommended)"
		echo "ehq -> Extreme High Quality (EHQ) (recommended)"
		echo "uhq -> Ultra High Quality (UHQ) (recommended)"
		echo "nlq -> Near Lossless Quality (NLQ) (only in '-fq' mode)"
		echo ""
		echo "Example of preset usage: xvidenc -2p -p hq"
		echo ""
		echo "Above example will encode the DVD or video file"
		echo "in 2-pass mode using the High Quality (HQ) preset"
		echo ""
		echo "Need more info? Use: xvidenc --help"
		echo "or 'man xvidenc'"
		echo ""
		exit 0
		;;
		"")
		echo "-> Option '-p' requires a parameter!"
		echo "-> Use '`basename $0` --help' for more info"
		exit 1
		;;
		*)
		echo "-> Unknown parameter ($2) for option '-p'"
		echo "-> Use '`basename $0` --help' for more info"
		exit 1
		;;
	esac
	;;
	-bpp|-bpb)
	# Bits per pixel/block calculation
	if [ ! -x "$(which bc 2>/dev/null)" ]; then
		echo "-> Utility 'bc' is missing!"
		exit 1
	fi
	case "$1" in
		-bpp)
		echo ""
		echo "+============================+"
		echo "| Bits Per Pixel Calculation |"
		echo "+============================+"
		echo ""
		;;
		-bpb)
		echo ""
		echo "+============================+"
		echo "| Bits Per Block Calculation |"
		echo "+============================+"
		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
		echo "-> 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
		echo "-> 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 ""
	echo "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: ${WID}x$HEI -- BPP: $BPP -- Bitrate based on BPP: $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: ${WID}x$HEI -- BPB: $BPB"
		done
		;;
	esac
	echo ""
	exit 0
	;;
	-o)
	if [ -z "$2" ]; then
		echo "-> Option '-o' requires an input file!"
		echo "-> Use $(basename $0) --help"
		exit 1
	fi
	if [ ! -f "$2" ]; then
		echo "-> No such file: '$2'"
		exit 1
	fi
	. "$2"
	exit $?
	;;
	-sc)
	echo ""
	if [ -x "$(which mplayer 2>/dev/null)" ]; then
		echo "-> Checking for MPlayer.................... OK"
	else
		echo "-> Checking for MPlayer.................... FAILED!"
	fi
	if [ -x "$(which mencoder 2>/dev/null)" ]; then
		echo "-> Checking for MEncoder................... OK"
		if [ -z "$(mencoder -ovc help 2>/dev/null | awk '{print $1}' | grep 'xvid')" ]; then
			echo "-> Xvid video support in MEncoder.......... NO"
		else
			echo "-> Xvid video support in MEncoder.......... YES"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" ]; then
			echo "-> AAC (FAAC) audio support in MEncoder.... NO"
		else
			echo "-> AAC (FAAC) audio support in MEncoder.... YES"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" ]; then
			echo "-> MP3 (LAME) audio support in MEncoder.... NO"
		else
			echo "-> MP3 (LAME) audio support in MEncoder.... YES"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc')" ]; then
			echo "-> MP2 (lavc) audio support in MEncoder.... NO"
			echo "-> AC3 (lavc) audio support in MEncoder.... NO"
			echo "-> WMA (lavc) audio support in MEncoder.... NO"
			echo "-> Sonic (lavc) audio support in MEncoder.. NO"
			echo "-> FLAC (lavc) audio support in MEncoder... NO"
			echo "-> ADPCM (lavc) audio support in MEncoder.. NO"
		else
			echo "-> MP2 (lavc) audio support in MEncoder.... YES"
			echo "-> AC3 (lavc) audio support in MEncoder.... YES"
			echo "-> WMA (lavc) audio support in MEncoder.... YES"
			echo "-> Sonic (lavc) audio support in MEncoder.. YES"
			echo "-> FLAC (lavc) audio support in MEncoder... YES"
			echo "-> ADPCM (lavc) audio support in MEncoder.. YES"
		fi
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" ]; then
			echo "-> PCM audio support in MEncoder........... NO"
		else
			echo "-> PCM audio support in MEncoder........... YES"
		fi
	else
		echo "-> Checking for MEncoder................... FAILED!"
	fi
	echo ""
	if [ -x "$(which bc 2>/dev/null)" ]; then
		echo "-> Checking for bc......................... OK"
	else
		echo "-> Checking for bc......................... FAILED!"
	fi
	if [ -x "$(which less 2>/dev/null)" ]; then
		echo "-> Checking for less....................... OK"
	else
		echo "-> Checking for less....................... FAILED!"
	fi
	if [ -x "$(which lsdvd 2>/dev/null)" ]; then
		echo "-> Checking for lsdvd...................... OK"
	else
		echo "-> Checking for lsdvd...................... FAILED! [no support for DVD title scans]"
	fi
	if [ -x "$(which dvdxchap 2>/dev/null)" ]; then
		echo "-> Checking for dvdxchap................... OK"
	else
		echo "-> Checking for dvdxchap................... FAILED! [no support for DVD chapters export]"
	fi
	if [ -x "$(which mkvmerge 2>/dev/null)" ]; then
		echo "-> Checking for mkvmerge................... OK"
	else
		echo "-> Checking for mkvmerge................... FAILED! [no support for the Matroska container]"
	fi
	if [ -x "$(which MP4Box 2>/dev/null)" ]; then
		echo "-> Checking for MP4Box..................... OK"
	else
		echo "-> Checking for MP4Box..................... FAILED! [no support for the MP4 container]"
	fi
	if [ -x "$(which mp4creator 2>/dev/null)" ]; then
		echo "-> Checking for mp4creator................. OK"
	else
		echo "-> Checking for mp4creator................. FAILED! [no support for MP4 layout optimization]"
	fi
	if [ -x "$(which avisplit 2>/dev/null)" ]; then
		echo "-> Checking for avisplit................... OK"
	else
		echo "-> Checking for avisplit................... FAILED! [no support for AVI file splitting]"
	fi
	echo ""
	exit 0
	;;
	-scan)
	# 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
			echo "-> Checking for '$i'... FAILED!"
			exit 1
		fi
	done
	echo ""
	printf "Specify the DVD device [default is /dev/dvd]: "
	read dvd_dev
	if [ -z "$dvd_dev" ]; then
		device="/dev/dvd"
	else
		if [ -z "$(echo $dvd_dev | grep '^/')" ]; then
			echo "-> You have to provide the full path to the DVD device!"
			exit 1
		fi
		if [ ! -e "$dvd_dev" ]; then
			echo "-> No such device: '$dvd_dev'"
			exit 1
		fi
		device="$dvd_dev"
	fi
	echo ""
	echo "-> 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}')"
	echo "-> $GET_TITLES"
	echo "-> $(lsdvd $device 2>/dev/null | grep 'Longest' | sed 's/track:/title:/')"
	echo ""
	echo "DVD Information Menu"
	echo "~~~~~~~~~~~~~~~~~~~~"
	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 ;;
		""|*)
		echo "-> 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" ;;
			""|*)
			echo "-> 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" ;;
			""|*)
			echo "-> Format unknown 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
	;;
	-[1-2]p|-fq)
	true
	;;
	*)
	echo "-> Unknown option: '$1'"
	echo "-> Use $(basename $0) --help for more info"
	exit 1
	;;
esac

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

# 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
		echo "-> The Near Lossless Quality (NLQ) preset is supported only in Fixed-Quant mode!"
		echo "-> Use: $(basename $0) -fq -p nlq"
		exit 1
	fi
fi

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

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

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

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

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

# Make config dir
CONFIGDIR=$HOME/.xvidenc
if [ ! -d $CONFIGDIR ]; then
	mkdir -p $CONFIGDIR 2>/dev/null
	if [ $? != 0 ]; then
		echo "-> Could not create .xvidenc config directory!"
		exit 1
	fi
fi
rm -f $CONFIGDIR/*

# User interrupt
user_interrupt_func() {
	echo ""
	echo "-> Exiting..."
	sleep 1
	rm -f $CONFIGDIR/*
	exit 1
}

trap 'user_interrupt_func' SIGHUP SIGTSTP SIGINT SIGQUIT SIGKILL SIGABRT SIGFPE SIGSEGV SIGTERM

###############################################################
#### 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).
#

deint_custom_fps_func() {
	printf "Specify the original frame rate of the content [no default!]: "
	read ofrc
	if [ -z "$ofrc" ]; then
		echo "-> You have to specify the frame rate!"
		exit 1
	fi
	if [ ! -z "$(echo $ofrc | grep '\.')" ]; then
		echo "-> Float is not allowed. Use fractions instead!"
		echo "-> Example: 30000/1001"
		exit 1
	fi
	if [ ! -z "$(echo $ofrc | grep '/')" ]; then
		DFPS=$(echo $ofrc | awk -F/ '{print $1}')
		LFPS=$(echo $ofrc | awk -F/ '{print $2}')
		if [ "$LFPS" != "1001" ]; then
			echo "-> You have to use 1001 as last value of the fraction!"
			echo "-> Example: 30000/1001"
			exit 1
		fi
		deintfps="$(($DFPS*2))/$LFPS"
		deintofps="$(($DFPS*2))/$LFPS"
	else
		deintfps="$(($ofrc*2))"
		deintofps="$(($ofrc*2))"
	fi
}

# 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
			deintfilter=
			deintfps=
			deintofps=
			interlacing=":interlacing"
		elif [ "$preint" = "n" -o "$preint" = "N" -o -z "$preint" ]; then
			interlacing=":nointerlacing"
			echo ""
			echo "Available Deinterlacing Filters"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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 --> Yadif Deinterlacer"
			echo "7 --> Yadif Deinterlacer (no spatial check)"
			echo "8 --> Yadif=1 & Mcdeint (top fields)"
			echo "9 --> Yadif=1 & Mcdeint (bottom fields)"
			echo "10 -> Yadif=3 & Mcdeint (top fields)"
			echo "11 -> Yadif=3 & Mcdeint (bottom fields)"
			echo "12 -> Yadif=1 & Fast Mcdeint (top fields)"
			echo "13 -> Yadif=1 & Fast Mcdeint (bottom fields)"
			echo "14 -> Yadif=3 & Fast Mcdeint (top fields)"
			echo "15 -> Yadif=3 & Fast Mcdeint (bottom fields)"
			echo "16 -> Yadif @ double frame rate"
			echo "17 -> Yadif @ double frame rate (no spatial check)"
			echo "18 -> Yadif=1 & Mcdeint @ double frame rate (top fields)"
			echo "19 -> Yadif=1 & Mcdeint @ double frame rate (bottom fileds)"
			echo "20 -> Yadif=3 & Mcdeint @ double frame rate (top fields)"
			echo "21 -> Yadif=3 & Mcdeint @ double frame rate (bottom fields)"
			echo "22 -> Yadif=1 & Fast Mcdeint @ double frame rate (top fields)"
			echo "23 -> Yadif=1 & Fast Mcdeint @ double frame rate (bottom fields)"
			echo "24 -> Yadif=3 & Fast Mcdeint @ double frame rate (top fields)"
			echo "25 -> Yadif=3 & Fast Mcdeint @ double frame rate (bottom fields)"
			echo "26 -> Tfields @ double frame rate"
			echo "27 -> Tfields & Mcdeint @ double frame rate (top fields)"
			echo "28 -> Tfields & Mcdeint @ double frame rate (bottom fields)"
			echo "29 -> Tfields & Fast Mcdeint @ double frame rate (top fields)"
			echo "30 -> Tfields & Fast Mcdeint @ double frame rate (bottom fields)"
			echo "31 -> Donald Graft's Adaptive Kernel Deinterlacer"
			echo ""
			printf "Select a Deinterlacing Filter [default is 6]: "
			read df
			case "$df" 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|"") deintfilter="yadif=0," ;;
				7) deintfilter="yadif=2," ;;
				8) deintfilter="yadif=1,mcdeint=1:0:10,framestep=2," ;;
				9) deintfilter="yadif=1,mcdeint=1:1:10,framestep=2," ;;
				10) deintfilter="yadif=3,mcdeint=1:0:10,framestep=2," ;;
				11) deintfilter="yadif=3,mcdeint=1:1:10,framestep=2," ;;
				12) deintfilter="yadif=1,mcdeint=0:0:10,framestep=2," ;;
				13) deintfilter="yadif=1,mcdeint=0:1:10,framestep=2," ;;
				14) deintfilter="yadif=3,mcdeint=0:0:10,framestep=2," ;;
				15) deintfilter="yadif=3,mcdeint=0:1:10,framestep=2," ;;
				1[6-9]|2[0-9]|30)
				echo ""
				echo "-> 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 | sed 's/ID_VIDEO_FPS=//')
				rm -f $CONFIGDIR/sourcefps
				case "$SOURCEFPS" in
					24.000|24.00)
					echo "-> Detected $SOURCEFPS FPS (Film)"
					echo "-> Setting input/output frame rate to 48 FPS"
					echo ""
					deintfps="48"
					deintofps="48"
					;;
					25.000|25.00)
					echo "-> Detected $SOURCEFPS FPS (PAL/SECAM Film/Video)"
					echo "-> Setting input/output frame rate to 50 FPS"
					echo ""
					deintfps="50"
					deintofps="50"
					;;
					50.000|50.00)
					echo "-> Detected $SOURCEFPS FPS (PAL/SECAM Double)"
					echo "-> Setting input/output frame rate to 100 FPS"
					echo ""
					deintfps="100"
					deintofps="100"
					;;
					100.000|100.00)
					echo "-> Detected $SOURCEFPS FPS (PAL/SECAM Quad)"
					echo "-> Setting input/output frame rate to 200 FPS"
					echo ""
					deintfps="200"
					deintofps="200"
					;;
					23.976|23.97)
					set_manual=yes
					echo "-> Detected $SOURCEFPS FPS (NTSC Film)"
					echo "-> Setting input/output frame rate to 47.952 FPS"
					echo "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="48000/1001"
					deintofps="48000/1001"
					;;
					29.970|29.97)
					set_manual=yes
					echo "-> Detected $SOURCEFPS FPS (NTSC Video)"
					echo "-> Setting input/output frame rate to 59.940 FPS"
					echo "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="60000/1001"
					deintofps="60000/1001"
					;;
					30.000|30.00)
					set_manual=yes
					echo "-> Detected $SOURCEFPS FPS (NTSC Video)"
					echo "-> Setting input/output frame rate to 60 FPS"
					echo "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="60"
					deintofps="60"
					;;
					59.940|59.94)
					set_manual=yes
					echo "-> Detected $SOURCEFPS FPS (NTSC Double)"
					echo "-> Setting input/output frame rate to 119.880 FPS"
					echo "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="120000/1001"
					deintofps="120000/1001"
					;;
					119.880|119.88)
					set_manual=yes
					echo "-> Detected $SOURCEFPS FPS (NTSC Quad)"
					echo "-> Setting input/output frame rate to 239.760 FPS"
					echo "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="240000/1001"
					deintofps="240000/1001"
					;;
					""|*)
					echo "-> Could not detect a supported frame rate!"
					echo "-> You have to set it manually!"
					echo "-> Note: the provided FPS will be multiplied by 2"
					echo ""
					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)
						echo ""
						echo "-> Note: the provided FPS will be multiplied by 2"
						echo ""
						deint_custom_fps_func
						;;
						""|*)
						echo "-> Option unknow or not specified!"
						exit 1
						;;
					esac
				fi
				case "$df" in
					16) deintfilter="yadif=1," ;;
					17) deintfilter="yadif=3," ;;
					18) deintfilter="yadif=1,mcdeint=1:0:10," ;;
					19) deintfilter="yadif=1,mcdeint=1:1:10," ;;
					20) deintfilter="yadif=3,mcdeint=1:0:10," ;;
					21) deintfilter="yadif=3,mcdeint=1:1:10," ;;
					22) deintfilter="yadif=1,mcdeint=0:0:10," ;;
					23) deintfilter="yadif=1,mcdeint=0:1:10," ;;
					24) deintfilter="yadif=3,mcdeint=0:0:10," ;;
					25) deintfilter="yadif=3,mcdeint=0:1:10," ;;
					26) deintfilter="tfields=4," ;;
					27) deintfilter="tfields=4,mcdeint=1:0:10," ;;
					28) deintfilter="tfields=4,mcdeint=1:1:10," ;;
					29) deintfilter="tfields=4,mcdeint=0:0:10," ;;
					30) deintfilter="tfields=4,mcdeint=0:1:10," ;;
				esac
				quiet="2>/dev/null"
				;;
				31)
				printf "Specify the deinterlacing threshold [0-255 - default is 5]: "
				read kerntres
				if [ -z "$kerntres" ]; then
					deintfilter="kerndeint=5,"
				else
					deintfilter="kerndeint=$kerntres,"
				fi
				;;
				*)
				echo "-> Unknown deinterlacing option: '$df'"
				exit 1
				;;
			esac
		fi
	elif [ "$int" = "n" -o "$int" = "N" -o -z "$int" ]; then
		interlacing=":nointerlacing"
		deintfilter=
		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 ""
			echo "Interlace Field And Frame Orders"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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-first field order + odd frames output"
			echo "1 -> Top-first field order + even frames output"
			echo "2 -> Bottom-first field order + odd frames output"
			echo "3 -> Bottom-first field 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 ""
			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" ;;
				*)
				echo "-> Unknown interlace option: '$intmeth'"
				exit 1
				;;
			esac
			echo ""
			echo "Input Frame Rate Selection"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "0 -> Progressive PAL (50 fps)"
			echo "1 -> Progressive PAL (100 fps)"
			echo "2 -> Progressive NTSC (59.94 fps)"
			echo "3 -> Progressive NTSC (119.88 fps)"
			echo ""
			printf "Select the original frame rate of the content [no default!]: "
			read origfps
			case "$origfps" in
				0)
				intfps="50"
				intofps="25"
				;;
				1)
				intfps="100"
				intofps="50"
				;;
				2)
				intfps="60000/1001"
				intofps="30000/1001"
				;;
				3)
				intfps="120000/1001"
				intofps="60000/1001"
				;;
				"")
				echo "-> You have to specify the frame rate of the content!"
				exit 1
				;;
				*)
				echo "-> Unknown frame rate option: '$origfps'"
				exit 1
				;;
			esac
			quiet="2>/dev/null"
		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 ""
		echo "Postprocessing Deblock/Dering Filters"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		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."
		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 ""
		printf "Select a Deblock/Dering filter [default is 0]: "
		read dbfilter
		case "$dbfilter" in
			0|"")
			printf "Specify the Quality level [0-6 - default is 2]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="spp=2:0:0,"
			else
				deblockfilter="spp=$dbqlevel:0:0,"
			fi
			;;
			1)
			printf "Specify the Quality level [0-8 - default is 2]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="uspp=2:0,"
			else
				deblockfilter="uspp=$dbqlevel:0,"
			fi
			;;
			2)
			printf "Specify the Quality level [0-6 - default is 2]: "
			read dbqlevel
			echo ""
			echo "FSPP Filter Strength"
			echo "~~~~~~~~~~~~~~~~~~~~"
			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
			if [ -z "$dbqlevel" ]; then
				deblockfilter="fspp=2:0:$fsppstrength,"
			else
				deblockfilter="fspp=$dbqlevel:0:$fsppstrength,"
			fi
			;;
			3)
			printf "Specify the Quality Quantization parameter [0-31 - default is 0]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="pp7=0:2,"
			else
				deblockfilter="pp7=$dbqlevel:2,"
			fi
			;;
			4)
			echo "ha/va/dr deblock/dering filters"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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 "ha/va deblock filters"
			echo "~~~~~~~~~~~~~~~~~~~~~"
			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,"
			;;
			*)
			echo "-> Unknown deblock/dering option: '$dbfilter'"
			exit 1
			;;
		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 ""
		echo "Available Video Denoise Filters"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		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 ""
		printf "Select a Denoise filter [default is 1]: "
		read dnfilt
		case "$dnfilt" in
			0)
			echo ""
			echo "3D Denoise Filter"
			echo "~~~~~~~~~~~~~~~~~"
			echo "This filter aims to reduce image noise producing"
			echo "smooth images and making still images really still"
			echo "This also should enhance compressibility. 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 ""
			echo "High-Quality 3D Denoise Filter"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "This filter aims to reduce image noise producing"
			echo "smooth images and making still images really still"
			echo "This also should enhance compressibility. 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 ""
			echo "Overcomplete Wavelet Denoiser"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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 ""
			echo "Temporal Denoiser"
			echo "~~~~~~~~~~~~~~~~~"
			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
			;;
			*)
			echo "-> Unknown denoise option: '$dnfilt'"
			exit 1
			;;
		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 $type? [y/n]: "
		read addnoise
		if [ "$addnoise" = "y" -o "$addnoise" = "Y" ]; then
			echo ""
			echo "Video Noise Filter"
			echo "~~~~~~~~~~~~~~~~~~"
			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"
			echo "2 --> Luma + Averaged temporal noise"
			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"
			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"
			echo "12 -> Luma & Chroma + Averaged temporal noise"
			echo "13 -> Luma & Chroma + High-quality noise pattern"
			echo "14 -> Luma & Chroma + Random noise pattern"
			echo ""
			printf "Select the Noise filter mode and pattern [default is 11]: "
			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
				;;
				*)
				echo "-> Unknown noise filter mode and noise pattern: '$nfmp'"
				exit 1
				;;
			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 ""
		echo "(Un)sharp Mask/Gaussian Blur Video Filter"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		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 advisable 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 ""
		printf "Select the Filtering Mode and Matrix Size [default is 14]: "
		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
			;;
			*)
			echo "-> Unknown filtering mode and matrix option: '$fmms'"
			exit 1
			;;
		esac
	elif [ "$sharpblur" = "n" -o "$sharpblur" = "N" -o -z "$sharpblur" ]; then
		unsharpfilter=
	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 ""
			echo "Colorspace Formats"
			echo "~~~~~~~~~~~~~~~~~~"
			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 ""
			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," ;;
				*)
				echo "-> Unknown colorspace option: '$csp'"
				exit 1
				;;
			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 ""
		echo "-> Scanning for subtitles..."
		case "$vtype" in
			file|FILE|File) device= ;;
		esac
		mplayer "$sourcetype" $device -nosound -vo null -frames 1 -nocache 2>/dev/null > $CONFIGDIR/xvidenc_subs
		SUBS=$(grep "^subtitle" $CONFIGDIR/xvidenc_subs)
		rm -f $CONFIGDIR/xvidenc_subs
		echo ""
		echo "Available Subtitles On Disc"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		if [ ! -z "$SUBS" ]; then
			echo "$SUBS" | sed -e 's/^subtitle //g' -e 's/( sid ):/Subtitle ID:/g' -e 's/language:/- Language:/g'
		else
			echo "-> No subtitles available or failed to detect them!"
		fi
		echo ""
		printf "Specify the Subtitle ID number [press 'Enter' to skip]: "
		read sn
		if [ ! -z "$(echo $sn | grep '[a-zA-Z]')" ]; then
			echo "-> You have to specify the Subtitle ID number, not the language code!"
			exit 1
		fi
		if [ -z "$sn" ]; then
			sid=
		else
			sid="-sid $sn"
		fi
		if [ ! -z "$sid" ]; then
			echo ""
			echo "Subtitle Methods"
			echo "~~~~~~~~~~~~~~~~"
			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
			if [ -z "$sub_method" -o "$sub_method" = "1" ]; then
				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"
				spuaa=
			elif [ "$sub_method" = "0" ]; then
				vobsubout=
				echo ""
				echo "Subtitle Anti-Aliasing Modes"
				echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 -> None (fastest, very ugly)"
				echo "1 -> Approximate (broken?)"
				echo "2 -> Full (slow)"
				echo "3 -> Bilinear (fast and not too bad)"
				echo "4 -> Gaussian Blur (looks very good)"
				echo ""
				printf "Select the Subtitle Anti-Aliasing Mode [default is 4]: "
				read saam
				if [ -z "$saam" ]; then
					spuaa="-spuaa 4"
				else
					spuaa="-spuaa $saam"
				fi
			fi
		else
			vobsubout=
			spuaa=
		fi
	elif [ "$sub" = "n" -o "$sub" = "N" -o -z "$sub" ]; then
		sid=
		vobsubout=
		spuaa=
	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 ""
		echo "-> Detecting crop values with 'cropdetect'..."
		mplayer "$sourcetype" $device $vid -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/xvidenc_cropdetect
		VLENGTH=$(grep "^ID_LENGTH" $CONFIGDIR/xvidenc_cropdetect | cut -f '2' -d '=' | cut -f '1' -d '.')
		GETCROP=$(mplayer "$sourcetype" $device $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')
		rm -f $CONFIGDIR/xvidenc_cropdetect
		if [ ! -z "$GETCROP" ]; then
			echo "-> Found crop values: $GETCROP"
			echo ""
			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 crop=$GETCROP -nocache -nosound -ss $startpos >/dev/null 2>&1 & PID=$!; sleep 15; kill -9 $PID;
			elif [ "$precrop" = "n" -o "$precrop" = "N" -o -z "$precrop" ]; then
				false
			fi
		else
			echo ""
			echo "-> Failed to get the crop values!"
			echo "-> You have to specify them yourself!"
			echo "-> The format is as follows: width:height:x:y"
			echo ""
			GETCROP="???"
		fi
		printf "Specify the crop values [default is $GETCROP]: "
		read cropvalues
		if [ -z "$cropvalues" -a "$GETCROP" = "???" ]; then
			echo "-> You have to specify the crop values!"
			exit 1
		fi
		if [ -z "$cropvalues" ]; then
			cropfilter="crop=$GETCROP,"
		else
			cropfilter="crop=$cropvalues,"
		fi
	elif [ "$cropping" = "n" -o "$cropping" = "N" -o -z "$cropping" ]; then
		cropfilter=
		GETCROP=
	fi
}

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

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 [ "$res" = "$GETRES" -o -z "$res" ]; then
		WIDTH=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $2}')
	else
		WIDTH=$(echo $res | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $res | tr '[:alpha:]' ' ' | awk '{print $2}')
	fi
	if [ -z "$ofps" ]; then
		VIDFPS=25
	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 ""
		echo "-> Bits Per Pixel value: $(calcbits "$(echo $vbitrate | sed 's/bitrate=//')*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 [ "$res" = "$GETRES" -o -z "$res" ]; then
		WIDTH=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $GETRES | tr '[:alpha:]' ' ' | awk '{print $2}')
	else
		WIDTH=$(echo $res | tr '[:alpha:]' ' ' | awk '{print $1}')
		HEIGHT=$(echo $res | tr '[:alpha:]' ' ' | awk '{print $2}')
	fi
	if [ -z "$ofps" ]; then
		VIDFPS=25
	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
		echo "-> Bits Per Block value: $(calcbits "$(echo $vbitrate | sed 's/bitrate=//')*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 intrafile
		if [ -z "$(echo "$intrafile" | grep '^/')" ]; then
			echo "-> You have to provide the full path to the file!"
			exit 1
		fi
		if [ ! -f "$intrafile" ]; then
			echo "-> No such file: '$intrafile'"
			exit 1
		fi
		intramatrix=":quant_intra_matrix=$intrafile"
		printf "Provide the Inter Matrix file: "
		read interfile
		if [ -z "$(echo "$interfile" | grep '^/')" ]; then
			echo "-> You have to provide the full path to the file!"
			exit 1
		fi
		if [ ! -f "$interfile" ]; then
			echo "-> No such file: '$interfile'"
			exit 1
		fi
		intermatrix=":quant_inter_matrix=$interfile"
	elif [ "$iim" = "n" -o "$iim" = "N" -o -z "$iim" ]; then
		intramatrix=
		intermatrix=
	fi
}

# 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 outfile
		if [ -z "$outfile" ]; then
			OUTPUT="$HOME/Xvid.avi"
			test -e $OUTPUT && mv -f $OUTPUT $OUTPUT.old
		else
			if [ -z "$(echo "$outfile" | grep '^/')" ]; then
				echo "-> You have to specify the full path!"
				exit 1
			fi
			if [ -z "$(echo "$outfile" | grep '\.avi')" ]; then
				echo "-> You have to use the '.avi' extension for the output file!"
				exit 1
			fi
			OUTPUT="$outfile"
		fi
		;;
		dvd|DVD|Dvd)
		GET_TITLE=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep '^Disc Title:' | sed 's/Disc Title: //')
		if [ ! -z "$GET_TITLE" ]; then
			printf "Provide a name for the Output File [default is $HOME/$GET_TITLE.avi]: "
			read outfile
			if [ -z "$outfile" ]; then
				OUTPUT="$HOME/$GET_TITLE.avi"
			else
				if [ -z "$(echo "$outfile" | grep '^/')" ]; then
					echo "-> You have to specify the full path!"
					exit 1
				fi
				if [ -z "$(echo "$outfile" | grep '\.avi')" ]; then
					echo "-> You have to use the '.avi' extension for the output file!"
					exit 1
				fi
				OUTPUT="$outfile"
			fi
		else
			printf "Provide a name for the Output File [default is $HOME/Xvid.avi]: "
			read outfile
			if [ -z "$outfile" ]; then
				OUTPUT="$HOME/Xvid.avi"
			else
				if [ -z "$(echo "$outfile" | grep '^/')" ]; then
					echo "-> You have to specify the full path!"
					exit 1
				fi
				if [ -z "$(echo "$outfile" | grep '\.avi')" ]; then
					echo "-> You have to use the '.avi' extension for the output file!"
					exit 1
				fi
				OUTPUT="$outfile"
			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
			echo "-> Failed to create the destination directory!"
			echo "-> Maybe a permissions problem?"
			exit 1
		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() {
	DISKSPACE_OUTPUT="$(df -m "$(dirname "$OUTPUT")" | tail -1 | awk '{print $4}')"
	DISKSPACE_CONFIGDIR=$(df -m $CONFIGDIR | tail -1 | awk '{print $4}')
	if [ $DISKSPACE_OUTPUT -lt 4096 -o $DISKSPACE_CONFIGDIR -lt 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 or to the MP4 container"
		echo "or if you want to split it. It is recommended"
		echo "to free up some disk space or provide a different"
		echo "destination output directory before continuing"
		echo "with the encoding process if you intend to do"
		echo "some of the above tasks!"
		echo ""
		echo "Space left over in '$(dirname "$OUTPUT")': $DISKSPACE_OUTPUT MiB"
		echo "Space left over in '$CONFIGDIR': $DISKSPACE_CONFIGDIR MiB"
		echo ""
		printf "#### Press 'Enter' to continue, CTRL+C to exit ####"
		read continue_encoding
		case "$vtype" in
			file|FILE|File) echo "" ;;
			dvd|DVD|Dvd) false ;;
		esac
	fi
}

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

clear
echo ""
echo "+==================================================================+"
echo "|<<<<<<<<<< xvidenc - the interactive shell script ripper >>>>>>>>>|"
echo "|------------------------------------------------------------------|"
echo "|<<<<<<<< version: $version - (C) 2006-2008 Grozdan Nikolov >>>>>>>>>>|"
echo "+==================================================================+"
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 infile
	if [ -z "$(echo "$infile" | grep '^/')" ]; then
		echo "-> You have to provide the full path to the input video file!"
		exit 1
	fi
	if [ ! -f "$infile" ]; then
		echo "-> No such file: '$infile'"
		exit 1
	fi
	set_output_filename_func
	check_diskspace_func
	sourcetype="$infile"
	if [ "$sourcetype" = "$OUTPUT" ]; then
		echo "-> You cannot use the same name for the input and output file!"
		exit 1
	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 ""
		echo "-> Scanning for video streams..."
		mplayer "$sourcetype" -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/xvidenc_videostreams
		if [ $(grep '^ID_VIDEO_ID' $CONFIGDIR/xvidenc_videostreams | wc -l) -lt 2 ]; then
			vid=
			echo "-> Found only one video stream"
			echo "-> Skipping stream selection"
			echo ""
		else
			echo ""
			for i in $(grep '^ID_VIDEO_ID' $CONFIGDIR/xvidenc_videostreams); do
				echo "Video stream: $(echo $i | sed 's/ID_VIDEO_ID=//g')"
			done
			echo ""
			VIDSTREAM=$(grep '^ID_VIDEO_ID' $CONFIGDIR/xvidenc_videostreams | sed 's/ID_VIDEO_ID=//g')
			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/xvidenc_videostreams
	elif [ "$mvs" = "n" -o "$mvs" = "N" -o -z "$mvs" ]; then
		vid=
	fi
	video_deinterlace_func
	video_interlace_func
	video_deblock_func
	video_denoise_func
	video_noise_func
	video_unsharp_func
	video_crop_func
	video_subtitles_func
	;;
	dvd|DVD|Dvd)
	source=DVD
	vid=
	echo ""
	if [ ! -x "$(which lsdvd 2>/dev/null)" ]; then
		echo "-> Checking for lsdvd... FAILED!"
		exit 1
	else
		echo "-> Checking for lsdvd... OK"
	fi
	echo ""
	# Get available devices and
	# display them. Skip if nothing found
	if [ -r /proc/sys/dev/cdrom/info ]; then
		MEDIA_DEVICES=$(grep "drive name" /proc/sys/dev/cdrom/info | sed 's/drive name://g')
		if [ ! -z "$MEDIA_DEVICES" ]; then
			for i in $MEDIA_DEVICES; do
				echo "-> Found device: /dev/$i"
			done
		fi
	fi
	if [ -L /dev/dvd ]; then
		echo "-> Found symbolic link to DVD device: $(ls -l /dev/dvd | grep -o "/dev.*")"
	fi
	echo ""
	printf "Specify the DVD Device [default is /dev/dvd]: "
	read dev
	if [ -z "$dev" ]; then
		device="-dvd-device /dev/dvd"
	else
		if [ -z "$(echo "$dev" | grep '^/')" ]; then
			echo "-> You have to provide the full path to the DVD device!"
			exit 1
		fi
		device="-dvd-device $dev"
	fi
	if [ ! -e "$(echo $device | awk '{print $2}')" ]; then
		echo "-> DVD device does not exist! [$(echo $device | awk '{print $2}')]"
		exit 1
	fi
	# Before scanning the DVD with 'lsdvd' it has to be
	# unlocked or 'lsdvd' will fail to read it, so we
	# run mplayer here just to unlock it.
	echo ""
	echo "-> Unlocking the DVD disc..."
	mplayer dvd://1 $device -nosound -vo null -frames 1 -nocache >/dev/null 2>&1
	echo ""
	set_output_filename_func
	check_diskspace_func
	echo ""
	echo "-> Scanning for DVD titles..."
	ALLTITLES=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep "^Title" | awk '{print $1,$2,$3,$4}' | sed 's/,/ -/g' | cut -f '1' -d '.')
	DVDTITLE=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep "Longest" | awk '{print $3}' | sed 's/^0//')
	TITLE_LENGTH=$(lsdvd -t $DVDTITLE $(echo $device | awk '{print $2}') 2>/dev/null | grep "Length" | awk '{print $4}' | cut -f '1' -d '.')
	TOTAL_TITLES=$(lsdvd $(echo $device | awk '{print $2}') 2>/dev/null | grep "^Title" | sed 's/,//g' | awk 'END{print $2}' | sed 's/^0//')
	echo ""
	if [ -z "$DVDTITLE" ]; then
		echo "Disc Title: $GET_TITLE"
		echo "$ALLTITLES"
		echo ""
		echo "-> Titles On Disc: $TOTAL_TITLES"
		echo "-> Failed to detect longest DVD title!"
		echo "-> You have to specify it yourself!"
		DVDTITLE="???"
	else
		echo "Disc Title: $GET_TITLE"
		echo "$ALLTITLES"
		echo ""
		echo "-> Titles On Disc: $TOTAL_TITLES"
		echo "-> Longest Title:  $DVDTITLE - Title Length: $TITLE_LENGTH"
		
	fi
	echo ""
	printf "Specify the DVD title for encoding [default/longest is $DVDTITLE]: "
	read title
	if [ -z "$title" -a "$DVDTITLE" = "???" ]; then
		echo "-> You have to specify the DVD title for encoding!"
		exit 1
	fi
	if [ -z "$title" ]; then
		sourcetype=dvd://$DVDTITLE
	else
		sourcetype=dvd://$title
	fi
	printf "Would you like to encode from a different DVD angle? [y/n]: "
	read angle
	if [ "$angle" = "y" -o "$angle" = "Y" ]; then
		echo ""
		echo "-> 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
			echo "-> $ANGLES"
		else
			echo "-> 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 ""
		echo "-> Scanning for chapters in title $(echo $sourcetype | sed 's|dvd://||')..."
		CHAPS=$(mplayer $sourcetype $device -nosound -vo null -frames 1 -nocache 2>/dev/null | grep "chapters")
		#LSCHAPS=$(lsdvd -c -t $(echo $sourcetype | sed 's,dvd://,,') $(echo $device | awk '{print $2}') 2>/dev/null | awk '{print $1,$2,$3,$4}' | grep '^Chapter' | sed -e 's/,/ -/g' -e 's/-$//g')
		mplayer $sourcetype $device -nosound -vo null -frames 1 -identify -nocache 2>/dev/null > $CONFIGDIR/chapters
		if [ ! -z "$CHAPS" ]; then
			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" >> $CONFIGDIR/lschaps
				done
				nl $CONFIGDIR/lschaps | awk '{print $2,$1,$3}'
			fi
		else
			echo "-> Could not detect any chapters in this DVD title!"
		fi
		rm -f $CONFIGDIR/chapters $CONFIGDIR/getchaps $CONFIGDIR/lschaps
		echo ""
		printf "Which chapter(s) to encode from this DVD title? [example: 1-3]: "
		read ct
		if [ -z "$ct" ]; then
			chapters=
		else
			chapters="-chapter $ct"
		fi
	elif [ "$chap" = "n" -o "$chap" = "N" -o -z "$chap" ]; then
		chapters=
	fi
	# 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? [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 | sed 's/-dvd-device //') | grep '^CHAPTER' > "$CHAPTERSFILE"
		fi
	fi
	video_deinterlace_func
	video_interlace_func
	video_deblock_func
	video_denoise_func
	video_noise_func
	video_unsharp_func
	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 ""
	echo "-> 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 | sed 's/ID_VIDEO_FPS=//')
	rm -f $CONFIGDIR/fps
	case "$GETFPS" in
		24.000|24.00)
		echo "-> Detected $GETFPS FPS (Film)"
		;;
		25.000|25.00)
		echo "-> Detected $GETFPS FPS (PAL/SECAM Film/Video)"
		;;
		50.000|50.00)
		echo "-> Detected $GETFPS FPS (PAL/SECAM Double)"
		;;
		100.000|100.00)
		echo "-> Detected $GETFPS FPS (PAL/SECAM Quad)"
		;;
		23.976|23.97)
		echo "-> Detected $GETFPS FPS (NTSC Film)"
		echo "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		29.970|29.97|30.000|30.00)
		echo "-> Detected $GETFPS FPS (NTSC Video)"
		echo "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		59.940|59.94)
		echo "-> Detected $GETFPS FPS (NTSC Double)"
		echo "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		119.880|119.88)
		echo "-> Detected $GETFPS FPS (NTSC Quad)"
		echo "-> Note: NTSC FPS detection is not 100% reliable!"
		;;
		"")
		echo "-> Failed to detect source FPS value!"
		;;
		*)
		echo "-> 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 ""
		echo "Frame Rate Configuration"
		echo "~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Film (24 fps)"
		echo "1 -> PAL/SECAM Film/Video (25 fps)"
		echo "2 -> PAL/SECAM Double (50 fps)"
		echo "3 -> PAL/SECAM Quad (100 fps)"
		echo "4 -> NTSC Film (23.976 fps)"
		echo "5 -> NTSC Video (29.970 fps)"
		echo "6 -> NTSC Video (30 fps)"
		echo "7 -> NTSC Double (59.940 fps)"
		echo "8 -> NTSC Quad (119.880 fps)"
		echo "9 -> User Defined"
		echo ""
		printf "Select a Frame Rate format [default is 1]: "
		read frf
		case "$frf" in
			0) ofps="-ofps 24" ;;
			1|"") ofps="-ofps 25" ;;
			2) ofps="-ofps 50" ;;
			3) ofps="-ofps 100" ;;
			4) ofps="-ofps 24000/1001" ;;
			5) ofps="-ofps 30000/1001" ;;
			6) ofps="-ofps 30" ;;
			7) ofps="-ofps 60000/1001" ;;
			8) ofps="-ofps 120000/1001" ;;
			9)
			printf "Specify the Frame Rate value [default is 25]: "
			read frame_rate
			if [ ! -z "$(echo $frame_rate | grep '\.')" ]; then
				echo "-> Float is not allowed. Use fractions instead!"
				echo "-> Example: 30000/1001"
				exit 1
			fi
			if [ -z "$frame_rate" ]; then
				ofps="-ofps 25"
			else
				if [ "$(echo $frame_rate | awk -F/ '{print $2}')" != "1001" ]; then
					echo "-> You have to use 1001 as last value of the fraction!"
					echo "-> Example: 30000/1001"
					exit 1
				fi
				ofps="-ofps $frame_rate"
			fi
			;;
			*)
			echo "-> Unknown frame rate option: '$frf'"
			exit 1
			;;
		esac
	elif [ "$outfps" = "n" -o "$outfps" = "N" -o -z "$outfps" ]; then
		ofps=
		frf=
	fi
else
	GETFPS=null
fi

# 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 which doubles the output frame rate.

case "$GETFPS" in
	23.976|29.970|23.97|29.97|30.000|30.00|"")
	if [ "$interlacing" = ":nointerlacing" -a -z "$deintfps" ]; 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 ""
			echo "Telecine/3:2 Pulldown/IVTC/Pullup"
			echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			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 ""
			printf "Which process to use? [default is 0]: "
			read telproc
			case "$telproc" in
				0|"")
				echo ""
				echo "Available IVTC Filters"
				echo "~~~~~~~~~~~~~~~~~~~~~~"
				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 ""
					echo "DETC Frame Dropping Modes"
					echo "~~~~~~~~~~~~~~~~~~~~~~~~~"
					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
					;;
					*)
					echo "-> Unknown IVTC option: '$ivtc'"
					exit 1
					;;
				esac
				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 "-> Unknown IVTC/Pulldown option: '$telproc'"
				exit 1
				;;
			esac
		elif [ "$tpp" = "n" -o "$tpp" = "N" -o -z "$tpp" ]; then
			fps=
			ivtcfilter=
			telecinefilter=
		fi
	else
		fps=
		ivtcfilter=
		telecinefilter=
	fi
	;;
	*)
	fps=
	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


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

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

# Do a colorspace conversion?
if [ ! -z "$scale" ]; then
	video_colorspace_func
else
	colorspacefilter=
fi

# Aspect ratio
printf "Would you like to set/force the Video Aspect Ratio? [y/n]: "
read aratio
if [ "$aratio" = "y" -o "$aratio" = "Y" ]; then
	printf "Specify the Aspect Ratio [4:3/16:9/1.3333/1.777... - default is 16:9]: "
	read asra
	if [ -z "$asra" ]; then
		aspect="-aspect 16:9"
	else
		aspect="-aspect $asra"
	fi
elif [ "$aratio" = "n" -o "$aratio" = "N" -o -z "$aratio" ]; then
	aspect=
fi

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


echo ""
echo "+==================================+"
echo "| Xvid 1.1.x Encoder Configuration |"
echo "+==================================+"
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
		if [ "$2" = "-p" ]; then
			echo ""
		fi
		;;
	esac
fi

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

	# Advanced options for experienced
	# users only
	printf "Would you like to set some Advanced Options? [y/n]: "
	read adv
	if [ "$adv" = "y" -o "$adv" = "Y" ]; then
		echo ""
		echo "+========================================+"
		echo "| Advanced Options For Experienced Users |"
		echo "+========================================+"
		echo ""
		printf "Specify the Ratecontrol Reaction Delay Factor [default is 0]: "
		read rrdf
		if [ -z "$rrdf" ]; then
			rc_reaction_delay_factor=":rc_reaction_delay_factor=0"
		else
			rc_reaction_delay_factor=":rc_reaction_delay_factor=$rrdf"
		fi
		printf "Specify the Ratecontrol Averaging Period [default is 100]: "
		read rap
		if [ -z "$rap" ]; then
			rc_averaging_period=":rc_averaging_period=100"
		else
			rc_averaging_period=":rc_averaging_period=$rap"
		fi
		printf "Specify the Ratecontrol Buffer Size [default is 100]: "
		read rcbuf
		if [ -z "$rcbuf" ]; then
			rc_buffer=
		else
			rc_buffer=":rc_buffer=$rcbuf"
		fi
		printf "Specify the B-Frame Quantizer Ratio [default is 150]: "
		read bfr
		if [ -z "$bfr" ]; then
			bquant_ratio=
		else
			bquant_ratio=":bquant_ratio=$bfr"
		fi
		printf "Specify the B-Frame Quantizer Offset [default is 100]: "
		read bo
		if [ -z "$bo" ]; then
			bquant_offset=
		else
			bquant_offset=":bquant_offset=$bo"
		fi
		case "$1" in
			-2p)
			printf "Specify the Keyframe Boost Threshold [0-1000 - default is 0]: "
			read kbt
			if [ -z "$kbt" ]; then
				keyframe_boost=
			else
				keyframe_boost=":keyframe_boost=$kbt"
			fi
			printf "Specify the Keyframe Threshold [default is 0]: "
			read kt
			if [ -z "$kt" ]; then
				kfthreshold=
			else
				kfthreshold=":kfthreshold=$kt"
			fi
			printf "Specify the Keyframe Reduction [0-100 - default is 30]: "
			read kr
			if [ -z "$kr" ]; then
				kfreduction=
			else
				kfreduction=":kfreduction=$kr"
			fi
			printf "Specify the Low Curve Compression [0-100 - default is 0]: "
			read lcc
			if [ -z "$lcc" ]; then
				curve_compression_low=
			else
				curve_compression_low=":curve_compression_low=$lcc"
			fi
			printf "Specify the High Curve Compression [0-100 - default is 0]: "
			read hcc
			if [ -z "$hcc" ]; then
				curve_compression_high=
			else
				curve_compression_high=":curve_compression_high=$hcc"
			fi
			printf "Specify the Overflow Control Strength [0-100 - default is 5]: "
			read ocs
			if [ -z "$ocs" ]; then
				overflow_control_strength=
			else
				overflow_control_strength=":overflow_control_strength=$ocs"
			fi
			printf "Specify the Maximum Overflow Improvement [0-100 - default is 5]: "
			read maxoi
			if [ -z "$maxoi" ]; then
			max_overflow_improvement=
			else
				max_overflow_improvement=":max_overflow_improvement=$maxoi"
			fi
			printf "Specify the Maximum Overflow Degradation [0-100 - default is 5]: "
			read maxod
			if [ -z "$maxod" ]; then
				max_overflow_degradation=
			else
				max_overflow_degradation=":max_overflow_degradation=$maxod"
			fi
			;;
			-1p|-fq)
			keyframe_boost=
			kfthreshold=
			kfreduction=
			curve_compression_low=
			curve_compression_high=
			overflow_control_strength=
			max_overflow_improvement=
			max_overflow_degradation=
			;;
		esac
		custom_matrix_func
		advopts="$rc_reaction_delay_factor$rc_averaging_period$rc_buffer$bquant_ratio$bquant_offset$keyframe_boost$kfthreshold$kfreduction$curve_compression_low$curve_compression_high$overflow_control_strength$max_overflow_improvement$max_overflow_degradation$intramatrix$intermatrix"
	elif [ "$adv" = "n" -o "$adv" = "N" -o -z "$adv" ]; then
		# use script's default
		advopts=":rc_reaction_delay_factor=0:rc_averaging_period=100"
	fi
fi

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

# Set priority (nice value) of the whole
# encoding process
printf "Would you like to set the encoder priority level? [y/n]: "
read priolevel
if [ "$priolevel" = "y" -o "$priolevel" = "Y" ]; then
	echo ""
	echo "Encoder Priority Level"
	echo "~~~~~~~~~~~~~~~~~~~~~~"
	if [ $UID != 0 ]; then
		echo "You can adjust the encoder priority level so that"
		echo "you can get a more responsive system even with the"
		echo "encoding process going 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 ###################
##################################################

# Resample function
audio_resample_func() {
	printf "Would you like to Resample the Audio? [y/n]: "
	read rsmp
	if [ "$rsmp" = "y" -o "$rsmp" = "Y" ]; then
		printf "Specify the new Sample Rate in Hertz [default is 44100]: "
		read hz
		case "$audiocodec" in
			MP[2-3]|mp[2-3]|PCM|pcm|ADPCM|adpcm|WMA|wma|FLAC|flac|SONIC|sonic)
			case "$hz" in
				8000|11025|12000|16000|22050|24000|32000|44100|48000|"") true ;;
				*)
				echo "-> '$hz' is not a valid sample rate!"
				echo "-> Valid rates are: 8000|11025|12000|16000|22050"
				echo "                    24000|32000|44100|48000"
				exit 1
				;;
			esac
			;;
			AAC|aac)
			case "$hz" in
				8000|11025|12000|16000|22050|24000|32000|44100|48000|64000|88200|96000|"") true ;;
				*)
				echo "-> '$hz' is not a valid sample rate!"
				echo "-> Valid rates are: 8000|11025|12000|16000|22050|24000"
				echo "                    32000|44100|48000|64000|88200|96000"
				exit 1
				;;
			esac
			;;
			AC3|ac3)
			# AC3 supports only these
			# sampling rates!
			case "$hz" in
				32000|44100|48000|"") true ;;
				*)
				echo "-> '$hz' is not a valid AC3 sample rate!"
				echo "-> Valid rates are: 32000|44100|48000"
				exit 1
				;;
			esac
			;;
		esac
		if [ -z "$hz" ]; then
			resample="resample=44100:0:2 -srate 44100"
		else
			resample="resample=$hz:0:2 -srate $hz"
		fi
	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|FLAC|flac)
		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 ""
				echo "AC3 Channels Configuration"
				echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> Dolby AC3 Stereo      (2 front)"
				echo "4 -> Dolby AC3 Quadro 4.0  (2 front + 2 rear)"
				echo "6 -> Dolby AC3 Digital 5.1 (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				AAC|aac)
				echo ""
				echo "AAC Channels Configuration"
				echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> AAC Stereo (2 front)"
				echo "4 -> AAC Quadro (2 front + 2 rear)"
				echo "6 -> AAC 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				FLAC|flac)
				echo ""
				echo "FLAC Channels Configuration"
				echo "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> FLAC Stereo (2 front)"
				echo "4 -> FLAC Quadro (2 front + 2 rear)"
				echo "6 -> FLAC 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
			esac
			printf "How many channels to use/add? [default is 2]: "
			read uc
			if [ -z "$uc" ]; then
				channels=
			else
				channels="-channels $uc"
			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? [1/2/4/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? [1/2/4/6 - default is 6]: "
			read chancopy
			if [ -z "$chancopy" ]; then
				channels="-channels 6"
			else
				channels="-channels $chancopy"
			fi
			;;
		esac
		;;
		PCM|pcm)
		printf "How many channels to use? [1/2/4/6 - default is 2]: "
		read chan
		if [ -z "$chan" ]; then
			channels=
		else
			channels="-channels $chan"
		fi
		;;
	esac
}

# 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)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc')" ]; then
			echo "-> MEncoder does not support the libavcodecs audio collection!"
			echo "-> Download the official MPlayer package or use a different"
			echo "   audio codec."
			exit 1
		fi
		;;
		mp3|MP3|"")
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" ]; then
			echo "-> MEncoder does not support MP3 audio encoding!"
			echo "-> Download LAME and recompile MPlayer or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
		aac|AAC)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" ]; then
			echo "-> MEncoder does not support AAC audio encoding!"
			echo "-> Download 'faac' and recompile MPlayer or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
		pcm|PCM)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" ]; then
			echo "-> MEncoder does not support PCM audio encoding!"
			echo "-> Download the official MPlayer package or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
		copy|COPY)
		if [ -z "$(mencoder -oac help 2>/dev/null | awk '{print $1}' | grep 'copy')" ]; then
			echo "-> MEncoder does not support audio stream copy!"
			echo "-> Download the official MPlayer package or use"
			echo "   a different audio codec"
			exit 1
		fi
		;;
	esac
}

# Scan for the audio codec used in
# a video file. This function will
# only be used if user decides to
# copy the audio from the original
# input video file. If we detect
# that the audio codec in the input
# video file contains either MP3 or
# AAC audio we set a flag so that
# later he'll be able to convert it
# to MP4 format (if he wants to).
#
# As explained below, at the moment,
# MP4Box doesn't support other audio
# codecs than MP3 and AAC.
# This will not work if the input
# video file doesn't contain any audio
#
# Sometimes though, you can get jumpy
# audio due to synchronization issues
# so this really depends on how the
# audio was encoded in that file
audio_codec_in_video_file_func() {
	case "$vtype" in
		file|FILE|File)
		# Don't use the -nosound option
		# in mplayer so we can get the
		# audio codec!
		mplayer "$sourcetype" $aid -vo null -identify -frames 1 -nocache 2>/dev/null > $CONFIGDIR/xvidenc_audio_in_file
		ACODEC=$(grep -m1 "^ID_AUDIO_CODEC" $CONFIGDIR/xvidenc_audio_in_file | sed 's/ID_AUDIO_CODEC=//g')
		rm -f $CONFIGDIR/xvidenc_audio_in_file
		if [ "$ACODEC" = "mp3" -o "$ACODEC" = "MP3" ]; then
			audio_codec=mp3
		elif [ "$ACODEC" = "aac" -o "$ACODEC" = "AAC" -o "$ACODEC" = "faad" ]; then
			audio_codec=aac
		elif [ "$ACODEC" = "mp2" -o "$ACODEC" = "MP2" ]; then
			audio_codec=mp2
		else
			audio_codec=other
		fi
		;;
		dvd|DVD|Dvd)
		# DVDs don't use MP3 or
		# AAC audio so set flag
		# to 'other'
		audio_codec=other
		;;
	esac
}

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

echo ""
echo "Available Audio Codecs"
echo "~~~~~~~~~~~~~~~~~~~~~~"
echo "MP2 | WMA   | ADPCM"
echo "MP3 | SONIC | COPY"
echo "AC3 | FLAC  | NOSOUND"
echo "AAC | PCM   |"
echo ""
printf "Specify the Audio Codec [default is MP3]: "
read audiocodec
case "$audiocodec" in
	MP2|mp2)
	check_audio_codec_func
	audio_codec=mp2
	printf "Specify the MP2 Audio Bitrate [default is 128]: "
	read ab
	case "$ab" in
		32|40|48|56|64|80|96|112|128|160|192|224|256|320|"") true ;;
		*)
		echo "-> '$ab' is not a valid MP2 audio bitrate!"
		echo "-> Valid bitrates are: 32|40|48|56|64|80|96|112"
		echo "                       128|160|192|224|256|320"
		exit 1
		;;
	esac
	if [ -z "$ab" ]; then
		abitrate=128
	else
		abitrate=$ab
	fi
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac lavc -lavcopts acodec=mp2:abitrate=$abitrate"
	afilters="$volnorm$volume$resample"
	channels=
	ac3drc=
	;;
	MP3|mp3|"")
	# The volume normalizing filter is not
	# used when encoding to MP3 audio 'cause
	# LAME provides an audio input gain option
	# where user can set the amount of gain
	# he wants
	check_audio_codec_func
	audio_codec=mp3
	printf "Specify the MP3 Audio Encoding Mode [ABR/CBR/VBR - default is ABR]: "
	read mp3mode
	case "$mp3mode" in
		ABR|abr|a*|A*|"")
		printf "Specify the MP3 Average Audio Bitrate [default is 140]: "
		read ab
		if [ -z "$ab" ]; then
			abitrate="abr:br=140"
		else
			abitrate="abr:br=$ab"
		fi
		;;
		CBR|cbr|C*|c*)
		printf "Specify the MP3 Audio Bitrate [default is 128]: "
		read ab
		case "$ab" in
			32|40|48|56|64|80|96|112|128|160|192|224|256|320|"") true ;;
			*)
			echo "-> '$ab' is not a valid CBR bitrate!"
			echo "-> Valid bitrates are: 32|40|48|56|64|80|96|112"
			echo "                       128|160|192|224|256|320"
			exit 1
			;;
		esac
		if [ -z "$ab" ]; then
			abitrate="cbr:br=128"
		else
			abitrate="cbr:br=$ab"
		fi
		;;
		VBR|vbr|V*|v*)
		printf "Specify the desired MP3 Quality [0-9 - default is 3]: "
		read ab
		if [ -z "$ab" ]; then
			abitrate="q=3"
		else
			abitrate="q=$ab"
		fi
		;;
		*)
		echo "-> Unknown MP3 encoding mode: '$mp3mode'"
		exit 1
		;;
	esac
	printf "Specify the 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 ""
	echo "MP3 Channel Modes"
	echo "~~~~~~~~~~~~~~~~~"
	echo "0 -> Stereo"
	echo "1 -> Joint-Stereo"
	echo "2 -> Dual Channel"
	echo "3 -> Mono"
	echo ""
	printf "Select the MP3 Channel Mode [default is 1]: "
	read mp3chan
	case "$mp3chan" in
		0) mp3channel=":mode=0" ;;
		1|"") mp3channel=":mode=1" ;;
		2) mp3channel=":mode=2" ;;
		3) mp3channel=":mode=3" ;;
		*)
		echo "-> Unknown MP3 channel option: '$mp3chan'"
		exit 1
		;;
	esac
	printf "Specify the MP3 Highpass Frequency in Hertz [default is 0 (auto)]: "
	read mp3highpass
	if [ -z "$mp3highpass" ]; then
		highpassfreq=":highpassfreq=0"
	else
		highpassfreq=":highpassfreq=$mp3highpass"
	fi
	printf "Specify the MP3 Lowpass Frequency in Hertz [default is 0 (auto)]: "
	read mp3lowpass
	if [ -z "$mp3lowpass" ]; then
		lowpassfreq=":lowpassfreq=0"
	else
		lowpassfreq=":lowpassfreq=$mp3lowpass"
	fi
	audio_resample_func
	acodec="-oac mp3lame -lameopts $abitrate$aquality$again$mp3channel$highpassfreq$lowpassfreq"
	channels=
	ac3drc=
	afilters="$resample"
	;;
	AC3|ac3)
	check_audio_codec_func
	audio_codec=ac3
	printf "Specify the AC3 Audio Bitrate [default is 192]: "
	read ab
	case "$ab" in
		32|40|48|56|64|80|96|112|128|160|192|224|256|320|384|448|512|576|640|"") true ;;
		*)
		echo "-> '$ab' is not a valid AC3 audio bitrate!"
		echo "-> Valid bitrates are: 32|40|48|56|64|80|96|112|128|160"
		echo "                       192|224|256|320|448|512|576|640"
		exit 1
		;;
	esac
	if [ -z "$ab" ]; then
		abitrate=192
	else
		abitrate=$ab
	fi
	audio_channels_func
	printf "Specify the AC3 Dynamic Range Compression [0.0-1 - default is 1 (full)]: "
	read drc
	if [ -z "$drc" ]; then
		ac3drc="-a52drc 1"
	else
		ac3drc="-a52drc $drc"
	fi
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac lavc -lavcopts acodec=ac3:abitrate=$abitrate"
	afilters="$volnorm$volume$resample"
	;;
	AAC|aac)
	check_audio_codec_func
	audio_codec=aac
	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
		;;
		*)
		echo "-> Unknown AAC audio encoding mode: '$aacmode'"
		exit 1
		;;
	esac
	echo ""
	echo "AAC Object Type Complexity Profiles"
	echo "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "1 -> Main"
	echo "2 -> Low Complexity (LC)"
	echo "3 -> Scalable Sample Rate (SSR/SRS)"
	echo "4 -> Long Term Prediction (LTP - extremely slow)"
	echo ""
	printf "Select a AAC Object Type Complexity Profile [default is 2]: "
	read objtype
	if [ -z "$objtype" ]; then
		object_type=":object=2"
	else
		object_type=":object=$objtype"
	fi
	audio_channels_func
	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
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac faac -faacopts $mpeg_version$br$object_type$tns"
	afilters="$volnorm$volume$resample"
	ac3drc=
	;;
	WMA|wma)
	check_audio_codec_func
	audio_codec=wma
	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 ;;
		*)
		echo "-> '$wma_ver' is not a valid WMA version!"
		exit 1
		;;
	esac
	printf "Specify the WMA Audio Bitrate [default is 128]: "
	read ab
	case "$ab" in
		32|40|48|56|64|80|96|112|128|160|192|224|256|320|"") true ;;
		*)
		echo "-> '$ab' is not a valid WMA audio bitrate!"
		echo "-> Valid bitrates are: 32|40|48|56|64|80|96|112"
		echo "                       128|160|192|224|256|320"
		exit 1
		;;
	esac
	if [ -z "$ab" ]; then
		abitrate=128
	else
		abitrate=$ab
	fi
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac lavc -lavcopts acodec=$wma_version:abitrate=$abitrate"
	afilters="$volnorm$volume$resample"
	channels=
	ac3drc=
	;;
	SONIC|sonic)
	check_audio_codec_func
	audio_codec=sonic
	printf "Specify the Sonic Audio Bitrate [default is 128]: "
	read ab
	if [ -z "$ab" ]; then
		abitrate=128
	else
		abitrate=$ab
	fi
	#audio_resample_func
	audio_volnorm_func
	audio_volume_func
	acodec="-oac lavc -lavcopts acodec=sonic:abitrate=$abitrate"
	afilters="$volnorm$volume$resample"
	channels=
	ac3drc=
	;;
	FLAC|flac)
	check_audio_codec_func
	audio_channels_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	audio_codec=flac
	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
	audio_codec=pcm
	acodec="-oac pcm"
	afilters="$volnorm$volume$resample"
	ac3drc=
	;;
	ADPCM|adpcm)
	check_audio_codec_func
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	audio_codec=adpcm
	acodec="-oac lavc -lavcopts acodec=adpcm_ima_wav"
	afilters="$volnorm$volume$resample"
	channels=
	ac3drc=
	;;
	COPY|copy)
	check_audio_codec_func
	# Check which audio codec is used
	# in the input video file
	audio_codec_in_video_file_func
	audio_channels_func
	acodec="-oac copy"
	afilters=
	ac3drc=
	;;
	NOSOUND|nosound)
	audio_codec=nosound
	acodec="-nosound"
	aid=
	afilters=
	channels=
	ac3drc=
	;;
	*)
	echo "-> Unknown audio codec: '$audiocodec'"
	exit 1
	;;
esac

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

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

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

case "$1" in
	-1p|-2p)
	case "$audiocodec" in
		MP2|mp2|MP3|mp3|AC3|ac3|AAC|aac|WMA|wma|SONIC|sonic|COPY|copy|"")
		printf "Would you like xvidenc to calculate the video bitrate? [y/n]: "
		read calcvidbit
		if [ "$calcvidbit" = "y" -o "$calcvidbit" = "Y" ]; then
			# Currently the script does not support
			# quality values -> bitrate conversion
			# for the AAC codec. Have to dig more
			# info on that one
			if [ "$aacmode" = "VBR" -o "$aacmode" = "vbr" -o "$aacmode" = "V" -o "$aacmode" = "v" ]; then
				echo ""
				echo "-> You have chosen to use quality based audio mode (VBR)."
				echo "-> Currently xvidenc does not support video bitrate"
				echo "   calculation with VBR AAC audio!"
				echo ""
			else
				echo ""
				echo "Video Bitrate Calculation"
				echo "~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "xvidenc can calculate the video bitrate for you"
				echo "based on the video length, chosen audio bitrate and"
				echo "target file size. The only thing you have to provide"
				echo "here is the desired target size in Mebibytes 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 Mebibytes [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 | cut -f '2' -d '=')
						;;
						VBR|vbr|V*|v*)
						APPRO="~"
						# Use 10 kbps lesser compared
						# to the LAME specs
						case "$abitrate" in
							q=0) AUDIO_BITRATE=230 ;;
							q=1) AUDIO_BITRATE=200 ;;
							q=2) AUDIO_BITRATE=180 ;;
							q=3) AUDIO_BITRATE=165 ;;
							q=4) AUDIO_BITRATE=155 ;;
							q=5) AUDIO_BITRATE=120 ;;
							q=6) AUDIO_BITRATE=105 ;;
							q=7) AUDIO_BITRATE=90 ;;
							q=8) AUDIO_BITRATE=75 ;;
							q=9) AUDIO_BITRATE=54 ;;
						esac
						;;
					esac
					;;
					AAC|aac)
					APPRO="~"
					AUDIO_BITRATE=$(echo $br | cut -f '2' -d '=')
					;;
					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 | sed 's/ID_AUDIO_BITRATE=//g')/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 ""
				echo "-> Detecting video length..."
				mplayer "$sourcetype" $device $vid -identify -vo null -frames 1 -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 ""
					echo "-> Could not detect video length!"
					echo "-> Will skip video bitrate calculation!"
					echo ""
				else
					EST_BITRATE=$(($(($TARGET_SIZE*8192/$VIDEO_LENGTH))-$AUDIO_BITRATE))
					bits_per_pixel_func
					bits_per_block_func
					echo ""
					echo "-> Video length is $(($VIDEO_LENGTH/60)) minutes or $VIDEO_LENGTH seconds"
					echo "-> Chosen/detected audio bitrate is $APPRO$AUDIO_BITRATE kbps"
					echo ""
					echo "-> Estimated video bitrate for $TARGET_SIZE MiB is: $EST_BITRATE kbps"
					echo "-> Bits Per Pixel value: $BPP bpp"
					echo "-> Bits Per Block value: $BPB bpb"
					echo ""
					printf "Specify the new video bitrate [default is $EST_BITRATE]: "
					read new_bitrate
					if [ -z "$new_bitrate" ]; then
						vbitrate="bitrate=$EST_BITRATE"
					else
						vbitrate="bitrate=$new_bitrate"
					fi
				fi
			fi
		fi
		;;
	esac
	;;
esac

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

# 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 reduces 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$deblockfilter$denoisefilter$colorspacefilter,softskip,$scale$isws$swsparam$swsaccurate$unsharpfilter$noisefilter,harddup$intfilter$telecinefilter | sed -e 's/^,//' -e 's/,,/,/g' -e 's/,$//')"
else
	videofilters="-vf $(echo $ivtcfilter$deintfilter$cropfilter$deblockfilter$denoisefilter$colorspacefilter,softskip,$scale$isws$swsparam$swsaccurate$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 $sws $aspect $sid $spuaa $vobsubout $aid $audiofilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts $vbitrate$me_quality$vhq$use_threads$max_key_interval$quantizers$max_bframes$bf_threshold$bvhq$packed$qpel$gmc$trellis$quant_type$interlacing$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$cartoon$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 $sws $aspect $aid $audiofilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts pass=1$me_quality$vhq$use_threads$max_key_interval$quantizers$max_bframes$bf_threshold$bvhq$turbo$packed$qpel$gmc$trellis$quant_type$interlacing$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$cartoon$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 $sws $aspect $sid $spuaa $vobsubout $aid $audiofilters $channels $ac3drc \
		$acodec -ovc xvid -xvidencopts pass=2:$vbitrate$me_quality$vhq$use_threads$max_key_interval$quantizers$max_bframes$bf_threshold$bvhq$packed$qpel$gmc$trellis$quant_type$interlacing$chroma_me$chroma_opt$hq_ac$profile$lumi_mask$cartoon$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 ""
	echo "+===========================+"
	echo "| MEncoder encoding options |"
	echo "+===========================+"
	echo ""
	case "$1" in
		-1p|-fq)
		echo $(cat $XVID1PFQ)
		;;
		-2p)
		echo "First pass options"
		echo "~~~~~~~~~~~~~~~~~~"
		echo $(cat $XVID2P1)
		echo ""
		echo "Second pass options"
		echo "~~~~~~~~~~~~~~~~~~~"
		echo $(cat $XVID2P2)
		;;
	esac
	echo ""
fi

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

printf "Would you like to save the MEncoder options to a file? [y/n]: "
read saveopts
if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
	if [ ! -z "$3" ]; then
		printf "Where to store the options? [default is $HOME/xvidenc-$3-$(basename "$OUTPUT" | sed 's|\.avi||')]: "
	else
		printf "Where to store the options? [default is $HOME/xvidenc-options-$(basename "$OUTPUT" | sed 's|\.avi||')]: "
	fi
	read storeopts
	case "$1" in
		-1p|-fq)
		if [ ! -z "$3" ]; then
			OPTSFILE=$HOME/xvidenc-$3-$(basename "$OUTPUT" | sed 's|\.avi||')
		else
			OPTSFILE=$HOME/xvidenc-options-$(basename "$OUTPUT" | sed 's|\.avi||')
		fi
		if [ -z "$storeopts" ]; then
			echo $(cat $XVID1PFQ) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
		else
			if [ -z "$(echo $storeopts | grep '^/')" ]; then
				echo ""
				echo "-> You have to provide the full path!"
				echo "-> Will skip saving the options"
				echo ""
			else
				test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
				echo $(cat $XVID1PFQ) >> "$storeopts"
				echo "" >> "$storeopts"
			fi
		fi
		;;
		-2p)
		if [ ! -z "$3" ]; then
			OPTSFILE=$HOME/xvidenc-$3-$(basename "$OUTPUT" | sed 's|\.avi||')
		else
			OPTSFILE=$HOME/xvidenc-options-$(basename "$OUTPUT" | sed 's|\.avi||')
		fi
		if [ -z "$storeopts" ]; then
			echo $(cat $XVID2P1) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo $(cat $XVID2P2) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
		else
			if [ -z "$(echo $storeopts | grep '^/')" ]; then
				echo ""
				echo "-> You have to provide the full path!"
				echo "-> Will skip saving the options"
				echo ""
			else
				test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
				echo $(cat $XVID2P1) >> "$storeopts"
				echo "" >> "$storeopts"
				echo $(cat $XVID2P2) >> "$storeopts"
				echo "" >> "$storeopts"
			fi
		fi
		;;
	esac
fi

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

case "$audio_codec" in
	wma|adpcm|aac|flac|sonic)
	avi_to_mkv=no
	MKVCHAPS=
	MKVSUB=
	;;
	*)
	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 ""
			echo "-> Utility 'mkvmerge' is missing!"
			echo "-> Will skip AVI to Matroska conversion!"
		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
			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=$(echo "$OUTPUT" | sed 's|\.avi|\.idx|')
				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|')
				if [ -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "mkvmerge \"$OUTPUT\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "mkvmerge \"$OUTPUT\" -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ ! -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "mkvmerge \"$OUTPUT\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "mkvmerge \"$OUTPUT\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					fi
				elif [ ! -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "mkvmerge \"$OUTPUT\" --chapters \"$MKVCHAPS\" \"$MKVSUB\" -o \"$MKVOUT\"" >> "$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
	;;
esac

# Ask for AVI -> MP4 conversion
# This only works with MP3/AAC audio
# or NOSOUND as MP4Box doesn't support
# the other codecs
case "$audio_codec" in
	mp2|mp3|aac|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 ""
			echo "-> MP4Box (from gpac) is missing!"
			echo "-> Skipping AVI to MP4 conversion!"
		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
			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=$(echo "$OUTPUT" | sed 's|\.avi|\.idx|')
				else
					MP4SUB=
				fi
			else
				MP4SUB=
			fi
			# Export muxing commands
			# to the options file
			if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
				case "$audio_codec" in
					mp2)
					MVRAW="mv -f $CONFIGDIR/*.raw $CONFIGDIR/m2a_audio.m2a"
					RMRAW="rm -f $CONFIGDIR/*.cmp $CONFIGDIR/*.m2a"
					audiofile="m2a.m2a"
					audioinput="m2a_audio.m2a"
					;;
					mp3)
					MVRAW=
					RMRAW="rm -f $CONFIGDIR/*.cmp $CONFIGDIR/*.mp3"
					audiofile="mp3.mp3"
					audioinput="mp3_audio.mp3"
					;;
					aac)
					MVRAW="mv -f $CONFIGDIR/*.raw $CONFIGDIR/aac_audio.aac"
					RMRAW="rm -f $CONFIGDIR/*.cmp $CONFIGDIR/*.aac"
					audiofile="aac.aac"
					audioinput="aac_audio.aac"
					;;
				esac
				MP4OUT=$(echo "$OUTPUT" | sed 's|\.avi|\.mp4|')
				MP4VID="MP4Box -aviraw video \"$OUTPUT\" -out $CONFIGDIR/cmp.cmp"
				MP4AUD="MP4Box -aviraw audio \"$OUTPUT\" -out $CONFIGDIR/$audiofile"
				MP4NOTE="# NOTE TO SET THE CORRECT FPS VALUE FOR THE COMMAND BELOW WITH THE -fps OPTION!!! (eg, -fps 23.976)"
				if [ -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
					if [ ! -z "$storeopts" ]; then
						echo "$MP4VID" >> "$storeopts"
						echo "$MP4AUD" >> "$storeopts"
						echo "$MVRAW" >> "$storeopts"
						echo "$MP4NOTE" >> "$sotreopts"
						echo "MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/$audioinput \"$MP4OUT\"" >> "$storeopts"
						echo "$RMRAW" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4NOTE" >> "$OPTSFILE"
						echo "MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/$audioinput \"$MP4OUT\"" >> "$OPTSFILE"
						echo "$RMRAW" >> "$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 "$MP4NOTE" >> "$sotreopts"
						echo "MP4Box -add $CONFIGDIR/*.cmp -chap \"$MP4CHAPS\" -add $CONFIGDIR/$audioinput \"$MP4OUT\"" >> "$storeopts"
						echo "$RMRAW" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4NOTE" >> "$OPTSFILE"
						echo "MP4Box -add $CONFIGDIR/*.cmp -chap \"$MP4CHAPS\" -add $CONFIGDIR/$audioinput \"$MP4OUT\"" >> "$OPTSFILE"
						echo "$RMRAW" >> "$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 "$MP4NOTE" >> "$sotreopts"
						echo "MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/$audioinput -add \"$MP4SUB\" \"$MP4OUT\"" >> "$storeopts"
						echo "$RMRAW" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4NOTE" >> "$OPTSFILE"
						echo "MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/$audioinput -add \"$MP4SUB\" \"$MP4OUT\"" >> "$OPTSFILE"
						echo "$RMRAW" >> "$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 "$MP4NOTE" >> "$sotreopts"
						echo "MP4Box -add $CONFIGDIR/*.cmp -chap \"$MP4CHAPS\" -add $CONFIGDIR/$audioinput -add \"$MP4SUB\" \"$MP4OUT\"" >> "$storeopts"
						echo "$RMRAW" >> "$storeopts"
						echo "" >> "$storeopts"
					else
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4NOTE" >> "$OPTSFILE"
						echo "MP4Box -add $CONFIGDIR/*.cmp -chap \"$MP4CHAPS\" -add $CONFIGDIR/$audioinput -add \"$MP4SUB\" \"$MP4OUT\"" >> "$OPTSFILE"
						echo "$RMRAW" >> "$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

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

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

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

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

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


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

#######################################################
########### 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 ""
	echo "-> Will convert AVI to Matroska now, please wait..."
	sleep 3
	if [ -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
		nice -n 10 mkvmerge "$OUTPUT" -o "$OUTPUT_MKV" >/dev/null 2>&1
	elif [ ! -z "$MKVCHAPS" -a -z "$MKVSUB" ]; then
		nice -n 10 mkvmerge "$OUTPUT" --chapters "$MKVCHAPS" -o "$OUTPUT_MKV" >/dev/null 2>&1
	elif [ -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
		nice -n 10 mkvmerge "$OUTPUT" "$MKVSUB" -o "$OUTPUT_MKV" >/dev/null 2>&1
	elif [ ! -z "$MKVCHAPS" -a ! -z "$MKVSUB" ]; then
		nice -n 10 mkvmerge "$OUTPUT" --chapters "$MKVCHAPS" "$MKVSUB" -o "$OUTPUT_MKV" >/dev/null 2>&1
	fi
	if [ -e "$OUTPUT_MKV" ]; then
		echo "-> Done"
	else
		echo "-> 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 | sed 's/ID_VIDEO_FPS=//')"
	rm -f $CONFIGDIR/mp4fps
	
}

# Set output file for MP4
OUTPUT_MP4="$(echo "$OUTPUT" | sed 's|\.avi|\.mp4|')"

# Ask for optimization of the MP4
# file. This requires mp4creator.
# Only ask for this if the user
# doesn't want to embed subs in the
# container as it will make them
# all black and unreadable.
optimize_mp4_func() {
	if [ -z "$MP4SUB" ]; then
		if [ -x "$(which mp4creator 2>/dev/null)" ]; then
			if [ -e "$OUTPUT_MP4" ]; then
				echo ""
				printf "Optimize the MP4 file layout for streaming? [y/n]: "
				read optmp4
				if [ "$optmp4" = "y" -o "$optmp4" = "Y" ]; then
					echo ""
					echo "-> Optimizing MP4 file layout, please wait..."
					nice -n 10 mp4creator -optimize "$OUTPUT_MP4" 2>/dev/null
					echo "-> Done"
				fi
			fi
		fi
	fi
}


if [ "$avi_to_mp4" = "yes" ]; then
	test -e "$OUTPUT_MP4" && mv -f "$OUTPUT_MP4" "$OUTPUT_MP4.old"
	case "$audio_codec" in
		mp2)
		echo ""
		echo "-> Will convert AVI to MP4 now..."
		sleep 3
		# Extract Xvid video
		echo "-> Extracting video from the AVI file, please wait..."
		nice -n 10 MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/xvid.cmp >/dev/null 2>&1
		# Extract audio
		echo "-> Extracting audio from the AVI file, please wait..."
		nice -n 10 MP4Box -aviraw audio "$OUTPUT" -out $CONFIGDIR/mp2.raw >/dev/null 2>&1
		mv -f $CONFIGDIR/*.raw $CONFIGDIR/mp2audio.m2a
		# Mux video & audio
		echo "-> Muxing audio and video into the MP4 container, please wait..."
		mp4_fps_func
		if [ -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.m2a -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.m2a -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.m2a -add "$MP4SUB" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.m2a -add "$MP4SUB" -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		fi
		rm -f $CONFIGDIR/*.cmp $CONFIGDIR/*.m2a
		if [ -e "$OUTPUT_MP4" ]; then
			echo "-> Done"
		else
			echo "-> Failed!"
		fi
		optimize_mp4_func
		;;
		mp3)
		echo ""
		echo "-> Will convert AVI to MP4 now..."
		sleep 3
		# Extract Xvid video
		echo "-> Extracting video from the AVI file, please wait..."
		nice -n 10 MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/xvid.cmp >/dev/null 2>&1
		# Extract audio
		echo "-> Extracting audio from the AVI file, please wait..."
		nice -n 10 MP4Box -aviraw audio "$OUTPUT" -out $CONFIGDIR/mp3.mp3 >/dev/null 2>&1
		# Mux video & audio
		echo "-> Muxing audio and video into the MP4 container, please wait..."
		mp4_fps_func
		if [ -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.mp3 -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.mp3 -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.mp3 -add "$MP4SUB" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.mp3 -add "$MP4SUB" -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		fi
		rm -f $CONFIGDIR/*.cmp $CONFIGDIR/*.mp3
		if [ -e "$OUTPUT_MP4" ]; then
			echo "-> Done"
		else
			echo "-> Failed!"
		fi
		optimize_mp4_func
		;;
		aac)
		echo ""
		echo "-> Will convert AVI to MP4 now..."
		sleep 3
		# Extract Xvid video
		echo "-> Extracting video from the AVI file, please wait..."
		nice -n 10 MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/xvid.cmp >/dev/null 2>&1
		# Extract audio
		echo "-> Extracting audio from the AVI file, please wait..."
		nice -n 10 MP4Box -aviraw audio "$OUTPUT" -out $CONFIGDIR/aac.raw >/dev/null 2>&1
		mv -f $CONFIGDIR/*.raw $CONFIGDIR/aac_audio.aac
		# Mux video & audio
		echo "-> Muxing audio and video into the MP4 container, please wait..."
		mp4_fps_func
		if [ -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.aac -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.aac -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.aac -add "$MP4SUB" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add $CONFIGDIR/*.aac -add "$MP4SUB" -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		fi
		rm -f $CONFIGDIR/*.cmp $CONFIGDIR/*.aac
		if [ -e "$OUTPUT_MP4" ]; then
			echo "-> Done"
		else
			echo "-> Failed!"
		fi
		optimize_mp4_func
		;;
		nosound)
		echo ""
		echo "-> Will convert AVI to MP4 now..."
		sleep 3
		# Extract Xvid video
		echo "-> Extracting video from the AVI file, please wait..."
		nice -n 10 MP4Box -aviraw video "$OUTPUT" -out $CONFIGDIR/xvid.cmp >/dev/null 2>&1
		# Mux video
		echo "-> Muxing video into the MP4 container, please wait..."
		mp4_fps_func
		if [ -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add "$MP4SUB" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		elif [ ! -z "$MP4CHAPS" -a ! -z "$MP4SUB" ]; then
			nice -n 10 MP4Box -add $CONFIGDIR/*.cmp -add "$MP4SUB" -chap "$MP4CHAPS" -fps $MP4FPS "$OUTPUT_MP4" >/dev/null 2>&1
		fi
		rm -f $CONFIGDIR/*.cmp
		if [ -e "$OUTPUT_MP4" ]; then
			echo "-> Done"
		else
			echo "-> Failed!"
		fi
		optimize_mp4_func
		;;
	esac
fi

########################################################
########### File splitting for AVI/MKV/MP4 #############
########################################################

# The code to support file splitting for 3 container
# formats in various possible scenarios is pretty
# large but also gives the user a greater
# flexibility and works fairly well at the moment...
# of course, there's always room to improve it


check_for_avisplit_func() {
	if [ ! -x "$(which avisplit 2>/dev/null)" ]; then
		echo ""
		echo "-> Utility 'avisplit' is missing!"
		echo "-> Download 'transcode' to obtain 'avisplit'!"
		echo ""
		exit 1
	fi
}

get_filesize_func() {
	if [ "$avi_to_mkv" = "no" -a "$avi_to_mp4" = "no" ]; then
		FSIZE_AVI=$(echo "scale=3; $(stat -c %s "$OUTPUT" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
	elif [ "$avi_to_mkv" = "yes" -a "$avi_to_mp4" = "no" ]; then
		FSIZE_AVI=$(echo "scale=3; $(stat -c %s "$OUTPUT" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
		FSIZE_MKV=$(echo "scale=3; $(stat -c %s "$OUTPUT_MKV" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
	elif [ "$avi_to_mkv" = "no" -a "$avi_to_mp4" = "yes" ]; then
		FSIZE_AVI=$(echo "scale=3; $(stat -c %s "$OUTPUT" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
		FSIZE_MP4=$(echo "scale=3; $(stat -c %s "$OUTPUT_MP4" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
	elif [ "$avi_to_mkv" = "yes" -a "$avi_to_mp4" = "yes" ]; then
		FSIZE_AVI=$(echo "scale=3; $(stat -c %s "$OUTPUT" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
		FSIZE_MKV=$(echo "scale=3; $(stat -c %s "$OUTPUT_MKV" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
		FSIZE_MP4=$(echo "scale=3; $(stat -c %s "$OUTPUT_MP4" 2>/dev/null)/1048576" | bc -l | sed 's|^\.|0\.|')
	fi
}

split_format_func() {
	case "$1" in
		avi)
		echo ""
		echo "-> Splitting the AVI file, please wait..."
		nice -n 10 avisplit -s $filesize_avi -i "$OUTPUT" -o "$(echo "$OUTPUT" | sed 's|\.avi||')" >/dev/null 2>&1
		echo "-> Done"
		echo ""
		;;
		mkv)
		echo ""
		echo "-> Splitting the MKV file, please wait..."
		nice -n 10 mkvmerge --split ${filesize_mkv}M "$OUTPUT_MKV" -o "$(echo "$OUTPUT_MKV" | sed 's|\.mkv|-.mkv|g')" >/dev/null 2>&1
		echo "-> Done"
		echo ""
		;;
		mp4)
		echo ""
		echo "-> Splitting the MP4 file, please wait..."
		nice -n 10 MP4Box -splits $(($(echo $filesize_mp4)*1024)) "$OUTPUT_MP4" >/dev/null 2>&1
		echo "-> Done"
		echo ""
		;;
	esac
}

delete_original_func() {
	case "$1" in
		avi)
		printf "Delete the original AVI file? [y/n]: "
		read delete_avi
		if [ "$delete_avi" = "y" -o "$delete_avi" = "Y" ]; then
			rm -f "$OUTPUT"
		fi
		;;
		mkv)
		printf "Delete the original MKV file? [y/n]: "
		read delete_mkv
		if [ "$delete_mkv" = "y" -o "$delete_mkv" = "Y" ]; then
			rm -f "$OUTPUT_MKV"
		fi
		;;
		mp4)
		printf "Delete the original MP4 file? [y/n]: "
		read delete_mp4
		if [ "$delete_mp4" = "y" -o "$delete_mp4" = "Y" ]; then
			rm -f "$OUTPUT_MP4"
		fi
		;;
	esac
}


if [ "$avi_to_mkv" = "no" -a "$avi_to_mp4" = "no" ]; then
	# Get file size
	get_filesize_func
	echo ""
	echo "-> AVI file size is: $FSIZE_AVI MiB"
	echo ""
	printf "Would you like to split the AVI file? [y/n]: "
	read split
	if [ "$split" = "y" -o "$split" = "Y" ]; then
		check_for_avisplit_func
		printf "How much Megabytes to use for each file? [press 'Enter' to skip]: "
		read filesize_avi
		if [ -z "$filesize_avi" ]; then
			echo ""
			echo "-> Skipping AVI file splitting!"
			echo ""
		else
			split_format_func avi
			delete_original_func avi
		fi
	fi
elif [ "$avi_to_mkv" = "yes" -a "$avi_to_mp4" = "no" ]; then
	# Get file size
	get_filesize_func
	echo ""
	echo "-> AVI file size is: $FSIZE_AVI MiB"
	echo "-> MKV file size is: $FSIZE_MKV MiB"
	echo ""
	printf "Would you like to split one or both of the files? [y/n]: "
	read split
	if [ "$split" = "y" -o "$split" = "Y" ]; then
		printf "Which one to split? [avi/mkv/all]: "
		read choose_split
		if [ -z "$choose_split" ]; then
			echo ""
			echo "-> You didn't specify which file(s) to split!"
			echo ""
			exit 1
		fi
		case "$choose_split" in
			avi|AVI|Avi)
			check_for_avisplit_func
			printf "How much Megabytes to use for each file?: "
			read filesize_avi
			if [ -z "$filesize_avi" ]; then
				echo ""
				echo "-> You didn't specify a file size!"
				echo ""
				exit 1
			fi
			split_format_func avi
			delete_original_func avi
			;;
			mkv|MKV|Mkv)
			# No need to check for mkvmerge as
			# this is already been done when
			# asking user if he wants to mux
			# the avi to mkv
			printf "How much Megabytes to use for each file?: "
			read filesize_mkv
			if [ -z "$filesize_mkv" ]; then
				echo ""
				echo "-> You didn't specify a file size!"
				echo ""
				exit 1
			fi
			split_format_func mkv
			delete_original_func avi
			delete_original_func mkv
			;;
			all|ALL|All)
			# Check for avisplit and if it's missing
			# skip AVI splitting but continue with
			# the MKV splitting. No need to check for
			# mkvmerge as this is done when asking user
			# for AVI -> MKV conversion
			if [ ! -x "$(which avisplit 2>/dev/null)" ]; then
				echo ""
				echo "-> Utility 'avisplit' is missing!"
				echo "-> Download 'transcode' to obtain 'avisplit'!"
				echo "-> Skipping AVI file splitting!"
				echo ""
				skip_avi=yes
			fi
			if [ "$skip_avi" = "yes" ]; then
				printf "How much Megabytes to use for each MKV file?: "
				read filesize_mkv
				if [ -z "$filesize_mkv" ]; then
					echo ""
					echo "-> You didn't specify a file size!"
					echo ""
					exit 1
				fi
				split_format_func mkv
				delete_original_func avi
				delete_original_func mkv
			else
				printf "How much Megabytes to use for each AVI file? [press 'Enter' to skip]: "
				read filesize_avi
				if [ -z "$filesize_avi" ]; then
					echo ""
					echo "-> Skipping AVI file splitting!"
					echo ""
				fi
				printf "How much Megabytes to use for each MKV file? [press 'Enter' to skip]: "
				read filesize_mkv
				if [ -z "$filesize_mkv" ]; then
					echo ""
					echo "-> Skipping MKV file splitting!"
				fi
				if [ ! -z "$filesize_avi" ]; then
					split_format_func avi
				fi
				if [ ! -z "$filesize_mkv" ]; then
					split_format_func mkv
				fi
				if [ ! -z "$filesize_avi" -a -z "$filesize_mkv" ]; then
					delete_original_func avi
				elif [ -z "$filesize_avi" -a ! -z "$filesize_mkv" ]; then
					delete_original_func avi
					delete_original_func mkv
				elif [ ! -z "$filesize_avi" -a ! -z "$filesize_mkv" ]; then
					delete_original_func avi
					delete_original_func mkv
				elif [ -z "$filesize_avi" -a -z "$filesize_mkv" ]; then
					echo ""
				fi
			fi
			;;
			*)
			echo ""
			echo "-> Invalid option!"
			echo ""
			exit 1
			;;
			
		esac
	elif [ "$split" = "n" -o "$split" = "N" -o -z "$split" ]; then
		delete_original_func avi
	fi
elif [ "$avi_to_mkv" = "no" -a "$avi_to_mp4" = "yes" ]; then
	# Get file size
	get_filesize_func
	echo ""
	echo "-> AVI file size is: $FSIZE_AVI MiB"
	echo "-> MP4 file size is: $FSIZE_MP4 MiB"
	echo ""
	printf "Would you like to split one or both of the files? [y/n]: "
	read split
	if [ "$split" = "y" -o "$split" = "Y" ]; then
		printf "Which one to split? [avi/mp4/all]: "
		read choose_split
		if [ -z "$choose_split" ]; then
			echo ""
			echo "-> You didn't specify which file(s) to split!"
			echo ""
			exit 1
		fi
		case "$choose_split" in
			avi|AVI|Avi)
			check_for_avisplit_func
			printf "How much Megabytes to use for each file?: "
			read filesize_avi
			if [ -z "$filesize_avi" ]; then
				echo ""
				echo "-> You didn't specify a file size!"
				echo ""
				exit 1
			fi
			split_format_func avi
			delete_original_func avi
			;;
			mp4|MP4|Mp4)
			# No need to check for MP4Box as
			# this is already been done when
			# asking user if he wants to mux
			# the avi to mp4
			printf "How much Megabytes to use for each file?: "
			read filesize_mp4
			if [ -z "$filesize_mp4" ]; then
				echo ""
				echo "-> You didn't specify a file size!"
				echo ""
				exit 1
			fi
			split_format_func mp4
			delete_original_func avi
			delete_original_func mp4
			;;
			all|ALL|All)
			# Check for avisplit and if it's missing
			# skip AVI splitting but continue with
			# the MP4 splitting. No need to check for
			# MP4Box as this is done when asking user
			# for AVI -> MP4 conversion
			if [ ! -x "$(which avisplit 2>/dev/null)" ]; then
				echo ""
				echo "-> Utility 'avisplit' is missing!"
				echo "-> Download 'transcode' to obtain 'avisplit'!"
				echo "-> Skipping AVI file splitting!"
				echo ""
				skip_avi=yes
			fi
			if [ "$skip_avi" = "yes" ]; then
				printf "How much Megabytes to use for each MP4 file?: "
				read filesize_mp4
				if [ -z "$filesize_mp4" ]; then
					echo ""
					echo "-> You didn't specify a file size!"
					echo ""
					exit 1
				fi
				split_format_func mp4
				delete_original_func avi
				delete_original_func mp4
			else
				printf "How much Megabytes to use for each AVI file? [press 'Enter' to skip]: "
				read filesize_avi
				if [ -z "$filesize_avi" ]; then
					echo ""
					echo "-> Skipping AVI file splitting!"
					echo ""
				fi
				printf "How much Megabytes to use for each MP4 file? [press 'Enter' to skip]: "
				read filesize_mp4
				if [ -z "$filesize_mp4" ]; then
					echo ""
					echo "-> Skipping MP4 file splitting!"
				fi
				if [ ! -z "$filesize_avi" ]; then
					split_format_func avi
				fi
				if [ ! -z "$filesize_mp4" ]; then
					split_format_func mp4
				fi
				if [ ! -z "$filesize_avi" -a -z "$filesize_mp4" ]; then
					delete_original_func avi
				elif [ -z "$filesize_avi" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mp4
				elif [ ! -z "$filesize_avi" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mp4
				elif [ -z "$filesize_avi" -a -z "$filesize_mp4" ]; then
					echo ""
				fi
			fi
			;;
			*)
			echo ""
			echo "-> Invalid option!"
			echo ""
			exit 1
			;;
		esac
	elif [ "$split" = "n" -o "$split" = "N" -o -z "$split" ]; then
		delete_original_func avi
	fi
elif [ "$avi_to_mkv" = "yes" -a "$avi_to_mp4" = "yes" ]; then
	# Get file size
	get_filesize_func
	echo ""
	echo "-> AVI file size is: $FSIZE_AVI MiB"
	echo "-> MKV file size is: $FSIZE_MKV MiB"
	echo "-> MP4 file size is: $FSIZE_MP4 MiB"
	echo ""
	printf "Would you like to split some of the files? [y/n]: "
	read split
	if [ "$split" = "y" -o "$split" = "Y" ]; then
		printf "Which one to split? [avi/mkv/mp4/all/custom]: "
		read choose_split
		if [ -z "$choose_split" ]; then
			echo ""
			echo "-> You didn't specify which file(s) to split!"
			echo ""
			exit 1
		fi
		case "$choose_split" in
			avi|AVI|Avi)
			check_for_avisplit_func
			printf "How much Megabytes to use for each file?: "
			read filesize_avi
			if [ -z "$filesize_avi" ]; then
				echo ""
				echo "-> You didn't specify a file size!"
				echo ""
				exit 1
			fi
			split_format_func avi
			delete_original_func avi
			;;
			mkv|MKV|Mkv)
			# No need to check for mkvmerge as
			# this is already been done when
			# asking user if he wants to mux
			# the avi to mkv
			printf "How much Megabytes to use for each file?: "
			read filesize_mkv
			if [ -z "$filesize_mkv" ]; then
				echo ""
				echo "-> You didn't specify a file size!"
				echo ""
				exit 1
			fi
			split_format_func mkv
			delete_original_func avi
			delete_original_func mkv
			;;
			mp4|MP4|Mp4)
			# No need to check for MP4Box as
			# this is already been done when
			# asking user if he wants to mux
			# the avi to mp4
			printf "How much Megabytes to use for each file?: "
			read filesize_mp4
			if [ -z "$filesize_mp4" ]; then
				echo ""
				echo "-> You didn't specify a file size!"
				echo ""
				exit 1
			fi
			split_format_func mp4
			delete_original_func avi
			delete_original_func mp4
			;;
			all|ALL|All|custom|CUSTOM|Custom)
			if [ ! -x "$(which avisplit 2>/dev/null)" ]; then
				echo ""
				echo "-> Utility 'avisplit' is missing!"
				echo "-> Download 'transcode' to obtain 'avisplit'!"
				echo "-> Skipping AVI file splitting!"
				echo ""
				skip_avi=yes
			fi
			if [ "$skip_avi" = "yes" ]; then
				printf "How much Megabytes to use for each MKV file? [press 'Enter' to skip]: "
				read filesize_mkv
				if [ -z "$filesize_mkv" ]; then
					echo ""
					echo "-> Skipping MKV file splitting!"
					echo ""
				fi
				printf "How much Megabytes to use for each MP4 file? [press 'Enter' to skip]: "
				read filesize_mp4
				if [ -z "$filesize_mp4" ]; then
					echo ""
					echo "-> Skipping MP4 file splitting!"
					
				fi
				if [ ! -z "$filesize_mkv" ]; then
					split_format_func mkv
				fi
				if [ ! -z "$filesize_mp4" ]; then
					split_format_func mp4
				fi
				if [ ! -z "$filesize_mkv" -a -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mkv
				elif [ -z "$filesize_mkv" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mp4
				elif [ ! -z "$filesize_mkv" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mkv
					delete_original_func mp4
				elif [ -z "$filesize_mkv" -a -z "$filesize_mp4" ]; then
					echo ""
				fi
			else
				printf "How much Megabytes to use for each AVI file? [press 'Enter' to skip]: "
				read filesize_avi
				if [ -z "$filesize_avi" ]; then
					echo ""
					echo "-> Skipping AVI file splitting!"
					echo ""
				fi
				printf "How much Megabytes to use for each MKV file? [press 'Enter' to skip]: "
				read filesize_mkv
				if [ -z "$filesize_mkv" ]; then
					echo ""
					echo "-> Skipping MKV file splitting!"
					echo ""
				fi
				printf "How much Megabytes to use for each MP4 file? [press 'Enter' to skip]: "
				read filesize_mp4
				if [ -z "$filesize_mp4" ]; then
					echo ""
					echo "-> Skipping MP4 file splitting!"
				fi
				if [ ! -z "$filesize_avi" ]; then
					split_format_func avi
				fi
				if [ ! -z "$filesize_mkv" ]; then
					split_format_func mkv
				fi
				if [ ! -z "$filesize_mp4" ]; then
					split_format_func mp4
				fi
				if [ ! -z "$filesize_avi" -a -z "$filesize_mkv" -a -z "$filesize_mp4" ]; then
					delete_original_func avi
				elif [ ! -z "$filesize_avi" -a ! -z "$filesize_mkv" -a -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mkv
				elif [ ! -z "$filesize_avi" -a ! -z "$filesize_mkv" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mkv
					delete_original_func mp4
				elif [ ! -z "$filesize_avi" -a -z "$filesize_mkv" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mp4
				elif [ -z "$filesize_avi" -a ! -z "$filesize_mkv" -a -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mkv
				elif [ -z "$filesize_avi" -a ! -z "$filesize_mkv" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mkv
					delete_original_func mp4
				elif [ -z "$filesize_avi" -a -z "$filesize_mkv" -a ! -z "$filesize_mp4" ]; then
					delete_original_func avi
					delete_original_func mp4
				elif [ -z "$filesize_avi" -a -z "$filesize_mkv" -a -z "$filesize_mp4" ]; then
					echo ""
				fi
			fi
			;;
			*)
			echo ""
			echo "-> Invalid option!"
			echo ""
			exit 1
			;;
		esac
	elif [ "$split" = "n" -o "$split" = "N" -o -z "$split" ]; then
		delete_original_func avi
	fi

fi

echo ""
echo "-> Have a nice day ^_^"
echo ""

exit 0
