#!/bin/bash
# $Id: h264enc, v 8.6.0, 2008/11/23, gn Exp $
# UUID: 099ef3da-dc34-41bd-a488-5786f78ab95b
#
# Encode DVDs/video files to the H.264/AVC/MPEG-4 Part 10/JVT/H26L
# video format using MEncoder from MPlayer
#
# Copyright (C) 2006-2008, Grozdan Nikolov
#
# This program is free software ; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation ; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY ; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program ; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA


shopt -u expand_aliases
export PATH=$PATH:/usr/bin
version=8.6.0
configversion=2

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

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

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

# Create config dir
H264ENCDIR=$HOME/.h264enc
test -d $H264ENCDIR || mkdir -p $H264ENCDIR

# In case h264enc did not remove its unique temp
# directories, remove them after 15 days
find "$H264ENCDIR" -name h264enc_* -mtime 15 -type d -execdir rm -rf '{}' \; >/dev/null 2>&1

# Generate config file
genconfig_func() {
cat<<EOF>>$H264ENCDIR/config
############## Configuration file for h264enc ##############
#
# Version: $configversion - do not modify or remove this line !!!
#
# This file is used by the h264enc script and contains the
# programs needed for its correct operation. The user can
# use it to modify the path to the various programs in case
# one or more of these programs is not in a standard location
# and connot be found by the system. It can also be used in
# case the user has multiple executables of the same program but
# wants to use a specific executable for the job.
# Note that this file cannot be used to store encoding settings
# or other parameters! Everything after a # sign is a comment.
#

MPLAYER="$(which mplayer 2>/dev/null)"
MENCODER="$(which mencoder 2>/dev/null)"
X264="$(which x264 2>/dev/null)"
LSDVD="$(which lsdvd 2>/dev/null)"
DVDXCHAP="$(which dvdxchap 2>/dev/null)"

MP4BOX="$(which MP4Box 2>/dev/null)"
MKVMERGE="$(which mkvmerge 2>/dev/null)"
OGMMERGE="$(which ogmmerge 2>/dev/null)"
TSMUXER="$(which tsMuxeR 2>/dev/null)"

OGGENC="$(which oggenc 2>/dev/null)"
NEROAACENC="$(which neroAacEnc 2>/dev/null)"
AACPLUSENC="$(which aacplusenc 2>/dev/null)"

TIME="$(which time 2>/dev/null)"
BC="$(which bc 2>/dev/null)"
PV="$(which pv 2>/dev/null)"
DD="$(which dd 2>/dev/null)"
EOF
}

if [ -f $H264ENCDIR/config ]; then
	cver=$(grep '^# Version' $H264ENCDIR/config | awk '{print $3}')
	if [[ $cver -lt $configversion ]]; then
		mv -f $H264ENCDIR/config $H264ENCDIR/config.old
		genconfig_func
		echo ""
		error "Important notice! The configuration file of h264enc located in"
		error "'$H264ENCDIR/config' has been updated to the latest version!"
		echo ""
		error "If you have made any prior changes to the configuration file,"
		error "please commit those changes again and restart h264enc!"
		error "If no changes are made, just restart h264enc to get rid of"
		error "this notice."
		echo ""
		exit 1
	else
		. $H264ENCDIR/config
	fi
else
	genconfig_func
	. $H264ENCDIR/config
fi

# Get DVD devices
get_dvd_devices_func() {
	echo ""
	if [ -r /proc/sys/dev/cdrom/info ]; then
		DRIVE=$(grep 'drive name' /proc/sys/dev/cdrom/info | sed 's/drive name://g')
		if [ ! -z "$DRIVE" ]; then
			for i in $DRIVE; do
				green "-> Found device: /dev/$i"
			done
		fi
	else
		error "-> Could not detect the DVD device(s)!"
	fi
	for i in /dev/dvd /dev/dvd[1-9]; do
		if [ -L $i ]; then
			green "-> Found symbolic link to DVD device: $(ls -l $i | grep -o '/dev.*')"
		fi
	done
	echo ""
}

case "$1" in
	"")
	echo "Usage: h264enc [-1p|-2p|-3p|-fq|-b|-r|-sc|-scan|-iso|-bpp|-bpb|-v|--help] [-p <preset>] [preset_file]"
	exit 1
	;;
	-v)
	echo "h264enc $version"
	exit 0
	;;
	--help)
	echo ""
	echo "+=======================================================+"
	echo "|     h264enc - the interactive shell script ripper     |"
	echo "+=======================================================+"
	echo ""
	echo "h264enc 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 H.264 video format [also known as Advanced Video"
	echo "Coding (AVC) or MPEG-4 Part 10]"
	echo "Note: this script requires MEncoder version 1.0rc2 or higher!"
	echo "For more information, read the man page of h264enc (man h264enc)"
	echo "or visit its official Web site at http://h264enc.sourceforge.net"
	echo "where 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 " -3p        Encode the DVD/video file in three pass mode"
	echo ""
	echo " -fq        Encode the DVD/video file in fixed-quant/constant ratefactor mode"
	echo ""
	echo " <passmode> -p <preset>"
	echo ""
	echo "            Use a predefined H.264 quality preset, where <passmode> is"
	echo "            the desired encoding mode (-1p or -2p or -3p or -fq) and"
	echo "            <preset> is the desired preset to use (see below). You can"
	echo "            choose from 51 different presets:"
	echo ""
	echo "            PC Presets"
	echo "            ~~~~~~~~~~"
	echo "            cp --------> Load a custom preset file (see example below)"
	echo "            ulq -------> Ultra Low Quality preset"
	echo "            elq -------> Extreme Low Quality preset"
	echo "            vlq -------> Very Low Quality preset"
	echo "            lq --------> Low Quality preset"
	echo "            mq --------> Medium Quality preset"
	echo "            nq --------> Normal Quality preset (recommended)"
	echo "            hq --------> High Quality preset (recommended)"
	echo "            vhq -------> Very High Quality preset (recommended)"
	echo "            ehq -------> Extreme High Quality preset (recommended)"
	echo "            uhq -------> Ultra High Quality preset"
	echo "            ihq -------> Insane High Quality preset"
	echo "            nlq -------> Near Lossless Quality preset"
	echo "            ani -------> Anime preset"
	echo "            anihq -----> Anime High-Quality preset"
	echo ""
	echo "            Software Compatible Presets"
	echo "            ~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "            f9 --------> Flash Player 9 preset"
	echo "            f9hq ------> Flash Player 9 High-Quality preset"
	echo "            qt --------> QuickTime preset"
	echo "            qthq ------> QuickTime High-Quality preset"
	echo ""
	echo "            Device Presets"
	echo "            ~~~~~~~~~~~~~~"
	echo "            bd40 ------> Blu-ray (Main@L4.0) preset"
	echo "            bdhq40 ----> Blu-ray High-Quality (High@L4.0) preset"
	echo "            bd41 ------> Blu-ray (Main@L4.1) preset"
	echo "            bdhq41 ----> Blu-ray High-Quality (High@L4.1) preset"
	echo "            sdb -------> Stand-alone HW players SD (Baseline@L3.0) preset"
	echo "            sdm -------> Stand-alone HW players SD (Main@L3.0) preset"
	echo "            sdh -------> Stand-alone HW players SD (High@L3.0) preset"
	echo "            hdb -------> Stand-alone HW players HD (Baseline@L4.0) preset"
	echo "            hdm -------> Stand-alone HW players HD (Main@L4.0) preset"
	echo "            hdh -------> Stand-alone HW players HD (High@L4.0) preset"
	echo "            ipc -------> Apple iPod Classic preset"
	echo "            ipchq -----> Apple iPod Classic High-Quality preset"
	echo "            ip --------> Apple iPod preset"
	echo "            iphq ------> Apple iPod High-Quality preset"
	echo "            iph -------> Apple iPhone preset"
	echo "            iphhq -----> Apple iPhone High-Quality preset"
	echo "            atv -------> AppleTV preset"
	echo "            atvhq -----> AppleTV High-Quality preset"
	echo "            ar --------> Archos 605 preset"
	echo "            arhq ------> Archos 605 High-Quality preset"
	echo "            bb --------> Blackberry 9000 preset"
	echo "            bbhq ------> Blackberry 9000 High-Quality preset"
	echo "            nks60 -----> Nokia S60 preset"
	echo "            nks60hq ---> Nokia S60 High-Quality preset"
	echo "            psp -------> Sony PSP preset"
	echo "            psphq -----> Sony PSP High-Quality preset"
	echo "            ps3 -------> Sony PS3 preset"
	echo "            ps3hq -----> Sony PS3 High-Quality preset"
	echo "            mz --------> Microsoft Zune preset"
	echo "            mzhq ------> Microsoft Zune High-Quality preset"
	echo "            mx --------> Microsoft XBOX 360 preset"
	echo "            mxhq ------> Microsoft XBOX 360 High-Quality preset"
	echo ""
	echo "            Example of presets usage: h264enc -2p -p hq"
	echo ""
	echo "            The above example will encode the DVD or input video file"
	echo "            in 2-pass mode using the High Quality (HQ) preset"
	echo ""
	echo "            Load a custom preset from a file:"
	echo "            h264enc -2p -p cp /path/to/file/preset.cfg"
	echo ""
	echo "            Please have a look at the 'preset.cfg' file inside the"
	echo "            h264enc package to give you an example on how to write"
	echo "            a custom preset. The 'preset.cfg' file is usually located"
	echo "            inside the doc directory of the h264enc package."
	echo ""
	echo " -b /path/to/file/batchfile"
	echo ""
	echo "            Load a batch file generated by *this* script. This option"
	echo "            can be used for testing or debugging the encoding parameters"
	echo "            and for batch encoding."
	echo ""
	echo " -r         Reset configuration file. As of version 8.5.7, h264enc uses a"
	echo "            configuration file which contains the paths to the programs"
	echo "            needed for its correct operation. This option tells the script"
	echo "            to remove and recreate the configuration file using the default"
	echo "            values. It can be used to restore the original values of the"
	echo "            config file in case the user has modified it and wants to get"
	echo "            rid of those modifications. The configuration file is located"
	echo "            in $H264ENCDIR/config"
	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/video file and display extensive information"
	echo "            about it. With this option, one can display or export the information"
	echo "            to a file on disk in text, perl, python, ruby or xml format (only"
	echo "            for DVD scans)"
	echo ""
	echo " -iso       Create an ISO image out of the DVD content and store it to disk."
	echo ""
	echo " -bpp       This is an informative option which lets you calculate"
	echo "            the Bits Per Pixel (bpp) values for various resolutions."
	echo "            The bpp value represents how much bits each pixel gets. The"
	echo "            higher the bpp value is, the more distinct colors the pixels"
	echo "            will have which leads to a higher overall picture quality."
	echo "            Note that these values are not absolute! For video content"
	echo "            with a lot of black in it, a bpp value of 0.14 may look"
	echo "            very good. Video content with a lot of high motion scenes"
	echo "            may still look bad with a bpp value of 0.20, so this really"
	echo "            depends on the content you are willing to encode and the"
	echo "            video bitrate and resolution you choose when scaling down."
	echo ""
	echo " -bpb       This option is similar to the -bpp one, except it calculates"
	echo "            the Bits Per Block (bpb) values for various resolutions."
	echo "            The bpb value expresses how many bits each 16x16 macroblock"
	echo "            gets. Good bpb values are between 37-52. As is the case with"
	echo "            Bits Per Pixel, the bpb values are not absolute and depend"
	echo "            on the video content you are willing to encode and the"
	echo "            video bitrate and resolution you choose when scaling down."
	echo ""
	echo " -v         Display version of this script and exit"
	echo ""
	echo " --help     Display this help screen and exit"
	echo ""
	echo ""
	echo "TIP: if you don't want to use an option, instead of always answering"
	echo "with 'n', just press Enter."
	echo ""
	echo "For bug reporting, suggestions, comments, questions, or if this script"
	echo "was useful to you, send me an e-mail at <neutrino8@gmail.com>"
	echo ""
	exit 0
	;;
	-bpp|-bpb)
	# Bits per pixel/block calculation
	if [ ! -x "$BC" ]; then
		error "-> Checking for 'bc'... FAILED!"
		exit 1
	fi
	case "$1" in
		-bpp)
		echo ""
		brown "+============================+"
		brown "| Bits Per Pixel Calculation |"
		brown "+============================+"
		echo ""
		;;
		-bpb)
		echo ""
		brown "+============================+"
		brown "| Bits Per Block Calculation |"
		brown "+============================+"
		echo ""
		;;
	esac
	cal0() {
		echo "scale=0; $1" | $BC -l | sed 's@^\.@0\.@'
	}
	cal3() {
		echo "scale=3; $1" | $BC -l | sed 's@^\.@0\.@'
	}
	round() {
		D_PART=$(echo "$1" | awk -F. '{print $1}')
		F_PART=$(echo "$1" | awk -F. '{print $2}')
		if [ $F_PART -lt 500 ]; then
			echo $D_PART
		else
			echo $[$D_PART+1]
		fi
	}
	printf "Provide the original unscaled resolution [default is 720x576]: "
	read O_RES
	if [ -z "$O_RES" ]; then
		R_ASP=$(cal3 "720/576")
	else
		R_ASP=$(cal3 $(echo $O_RES | tr '[:alpha:]' '/'))
	fi
	printf "Provide the original unscaled but cropped resolution [WxH]: "
	read U_RES
	if [ -z "$U_RES" ]; then
		error "-> Cropped resolution value is required!"
		exit 1
	fi
	printf "Provide the aspect ratio [16/9 or 4/3 - default is 16/9]: "
	read AR
	if [ -z "$AR" ]; then
		A_RAT=16/9
	else
		A_RAT=$AR
	fi
	printf "Provide the video bitrate: "
	read V_BTR
	if [ -z "$V_BTR" ]; then
		error "-> Video bitrate is required!"
		exit 1
	fi
	printf "Provide the video's FPS value [integer or float - default is 25]: "
	read VFPS
	if [ -z "$VFPS" ]; then
		M_FPS=25
	else
		M_FPS=$VFPS
	fi
	U_WID=$(echo $U_RES | awk -Fx '{print $1}')
	U_HEI=$(echo $U_RES | awk -Fx '{print $2}')
	E_RAT=$(cal3 "$A_RAT")
	S_WID=$(cal0 "$U_WID*$E_RAT/$R_ASP")
	S_HEI=$U_HEI
	P_AR=$(cal3 "$S_WID/$S_HEI")
	echo ""
	brown "Prescaled picture: ${S_WID}x$S_HEI - Aspect Ratio: $P_AR"
	case "$1" in
		-bpp)
		for ((WID=$(echo $U_RES | awk -Fx '{print $1}'); WID>=320; WID=WID-16)); do
			R_H=$(cal3 "$WID/$P_AR/16")
			HEI=$[16*$(round "$R_H")]
			BPP=$(cal3 "1000*$V_BTR/($WID*$HEI*$M_FPS)")
			BITRATE=$(cal0 "($WID*$HEI*$M_FPS*$BPP)/1000")
			echo "Resolution: $(green "${WID}x$HEI") -- BPP: $(green $BPP) -- Bitrate based on BPP: $(green "$BITRATE kbps")"
		done
		;;
		-bpb)
		for ((WID=$(echo $U_RES | awk -Fx '{print $1}'); WID>=320; WID=WID-16)); do
			R_H=$(cal3 "$WID/$P_AR/16")
			HEI=$[16*$(round "$R_H")]
			BPB=$(cal3 "$V_BTR*1000/($M_FPS*($WID*$HEI)/(16*16))")
			echo "Resolution: $(green "${WID}x$HEI") -- BPB: $(green $BPB)"
		done
		;;
	esac
	echo ""
	exit 0
	;;
	-b)
	if [ -z "$2" ]; then
		error "-> Option '-b' requires an input file!"
		error "-> Use: $(basename $0) --help"
		exit 1
	fi
	if [ ! -f "$2" ]; then
		error "-> No such file: '$2'"
		exit 1
	fi
	. "$2"
	exit $?
	;;
	-r)
	green "-> Resetting the config file values"
	rm -f $H264ENCDIR/config
	genconfig_func
	exit 0
	;;
	-sc)
	echo ""
	if [ -x "$MPLAYER" ]; then
		echo "-> Checking for 'MPlayer'..................... $(green OK)"
	else
		echo "-> Checking for 'MPlayer'..................... $(error FAILED!)"
	fi
	if [ -x "$MENCODER" ]; then
		echo "-> Checking for 'MEncoder'.................... $(green OK)"
		if [ -z "$($MENCODER -ovc help 2>/dev/null | awk '{print $1}' | grep 'x264')" ]; then
			echo "-> H.264 video support in MEncoder............ $(error NO)"
		else
			echo "-> H.264 video support in MEncoder............ $(green YES)"
		fi
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" ]; then
			echo "-> AAC (FAAC) audio support in MEncoder....... $(error NO)"
		else
			echo "-> AAC (FAAC) audio support in MEncoder....... $(green YES)"
		fi
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" ]; then
			echo "-> MP3 (LAME) audio support in MEncoder....... $(error NO)"
		else
			echo "-> MP3 (LAME) audio support in MEncoder....... $(green YES)"
		fi
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc')" ]; then
			echo "-> AC3 (lavc) audio support in MEncoder....... $(error NO)"
			echo "-> FLAC (lavc) audio support in MEncoder...... $(error NO)"
		else
			echo "-> AC3 (lavc) audio support in MEncoder....... $(green YES)"
			echo "-> FLAC (lavc) audio support in MEncoder...... $(green YES)"
		fi
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" ]; then
			echo "-> PCM audio support in MEncoder.............. $(error NO)"
		else
			echo "-> PCM audio support in MEncoder.............. $(green YES)"
		fi
	else
		echo "-> Checking for MEncoder...................... $(error FAILED!)"
	fi
	echo ""
	if [ -x "$BC" ]; then
		echo "-> Checking for 'bc'.......................... $(green OK)"
	else
		echo "-> Checking for 'bc'.......................... $(error FAILED!)"
	fi
	if [ -x "$PV" ]; then
		echo "-> Checking for 'pv'.......................... $(green OK)"
	else
		echo "-> Checking for 'pv'.......................... $(error "FAILED! [no support for DVD ISO dumps]")"
	fi
	if [ -x "$DD" ]; then
		echo "-> Checking for 'dd'.......................... $(green OK)"
	else
		echo "-> Checking for 'dd'.......................... $(error "FAILED! [no support for DVD ISO dumps]")"
	fi
	if [ -x "$NEROAACENC" ]; then
		echo "-> Checking for 'neroAacEnc'.................. $(green OK)"
	else
		echo "-> Checking for 'neroAacEnc'.................. $(error "FAILED! [no support for AAC+ audio]")"
	fi
	if [ -x "$AACPLUSENC" ]; then
		echo "-> Checking for 'aacplusenc'.................. $(green OK)"
	else
		echo "-> Checking for 'aacplusenc'.................. $(error "FAILED! [no support for AAC+ audio]")"
	fi
	if [ -x "$OGGENC" ]; then
		echo "-> Checking for 'oggenc'...................... $(green OK)"
	else
		echo "-> Checking for 'oggenc'...................... $(error "FAILED! [no support for Vorbis audio]")"
	fi
	if [ -x "$(which less 2>/dev/null)" ]; then
		echo "-> Checking for 'less'........................ $(green OK)"
	else
		echo "-> Checking for 'less'........................ $(error FAILED!)"
	fi
	if [ -x "$LSDVD" ]; then
		echo "-> Checking for 'lsdvd'....................... $(green OK)"
	else
		echo "-> Checking for 'lsdvd'....................... $(error "FAILED! [no support for DVD title scans]")"
	fi
	if [ -x "$DVDXCHAP" ]; then
		echo "-> Checking for 'dvdxchap' (from ogmtools).... $(green OK)"
	else
		echo "-> Checking for 'dvdxchap' (from ogmtools).... $(error "FAILED! [no support for DVD chapters export]")"
	fi
	if [ -x "$MKVMERGE" ]; then
		echo "-> Checking for 'mkvmerge' (from mkvtoolnix).. $(green OK)"
	else
		echo "-> Checking for 'mkvmerge' (from mkvtoolnix).. $(error "FAILED! [no support for the MKV container]")"
	fi
	if [ -x "$OGMMERGE" ]; then
		echo "-> Checking for 'ogmmerge' (from ogmtools).... $(green OK)"
	else
		echo "-> Checking for 'ogmmerge' (from ogmtools).... $(error "FAILED! [no support for the OGM container]")"
	fi
	if [ -x "$MP4BOX" ]; then
		echo "-> Checking for 'MP4Box' (from gpac).......... $(green OK)"
	else
		echo "-> Checking for 'MP4Box' (from gpac).......... $(error "FAILED! [no support for the MP4 container]")"
	fi
	if [ -x "$TSMUXER" ]; then
		echo "-> Checking for 'tsMuxeR'..................... $(green OK)"
	else
		echo "-> Checking for 'tsMuxeR'..................... $(error "FAILED! [no support for the TS container]")"
	fi
	echo ""
	exit 0
	;;
	-scan)
	echo ""
	printf "Would you like to scan a video file or a DVD? [file/dvd]: "
	read scantype
	case "$scantype" in
		file|FILE|File)
		if [ ! -x "$BC" -o ! -x "$MPLAYER" ]; then
			error "-> bc or mplayer missing!"
			exit 1
		fi
		printf "Provide the input video file: "
		read -e infile
		if [ -z "$infile" -o -z "$(echo "$infile" | grep '^/')" ]; then
			error "-> You didn't specify the input file or the full path to it!"
			exit 1
		fi
		if [ ! -e "$infile" ]; then
			error "-> No such file: '$infile'"
			exit 1
		fi
		echo ""
		green "-> Scanning the file..."
		INFO="$HOME/.h264enc/info_$$"
		$MPLAYER "$infile" -identify -vo null -nocache -frames 1 2>/dev/null > $INFO
		echo ""
		echo "MPlayer Demuxer:   $(grep '^ID_DEMUXER' $INFO | tail -1 | awk -F= '{print $2}')"
		echo "Video Format:      $(grep '^ID_VIDEO_FORMAT' $INFO | awk -F= '{print $2}')"
		echo "Video Bitrate:     $(echo "scale=1; $(grep '^ID_VIDEO_BITRATE' $INFO | awk -F= '{print $2}')/1000" | $BC -l) kbps"
		echo "Video FPS:         $(grep '^ID_VIDEO_FPS' $INFO | awk -F= '{print $2}')"
		echo "Video Resolution:  $(grep '^VIDEO:' $INFO | tail -1 | awk '{print $3}')"
		echo "Video Aspect:      $(grep '^ID_VIDEO_ASPECT' $INFO | tail -1 | awk -F= '{print $2}')"
		echo "Video Length:      $(echo "scale=1; $(grep '^ID_LENGTH' $INFO | awk -F= '{print $2}')/60" | $BC -l | sed 's/^\./0\./') minutes"
		echo ""
		echo "Audio Codec:       $(grep '^ID_AUDIO_CODEC' $INFO | tail -1 | awk -F= '{print $2}')"
		echo "Audio Bitrate:     $(($(grep '^ID_AUDIO_BITRATE' $INFO | tail -1 | awk -F= '{print $2}')/1000)) kbps"
		echo "Audio Sample Rate: $(grep '^ID_AUDIO_RATE' $INFO | tail -1 | awk -F= '{print $2}') Hz"
		echo "Audio Channels:    $(grep '^ID_AUDIO_NCH' $INFO | tail -1 | awk -F= '{print $2}') (May not be accurate)"
		echo ""
		rm -f $INFO
		exit 0
		;;
		dvd|DVD|Dvd)
		# Scan the DVD disc and display
		# info about it, titles, chapters,
		# audio streams, subs, cells, etc...
		if [ ! -x "$MPLAYER" -o ! -x "$LSDVD" -o ! -x "$(which less 2>/dev/null)" ]; then
			error "-> 'mplayer', 'lsdvd' or 'less' missing!"
			exit 1
		fi
		get_dvd_devices_func
		printf "Specify the DVD device [default is /dev/dvd]: "
		read -e dvd_dev
		if [ -z "$dvd_dev" ]; then
			device="/dev/dvd"
		else
			if [ -z "$(echo $dvd_dev | grep '^/')" ]; then
				error "-> You have to provide the full path to the DVD device!"
				exit 1
			fi
			if [ ! -e "$dvd_dev" ]; then
				error "-> No such device: '$dvd_dev'"
				exit 1
			fi
			device="$dvd_dev"
		fi
		echo ""
		green "-> Unlocking the DVD disc..."
		GET_TITLES="$($MPLAYER dvd://1 -dvd-device $device -nosound -nocache -vo null -frames 1 2>/dev/null | grep -m1 'titles')"
		TITLE="$(echo $GET_TITLES | awk '{print $3}')"
		green "-> $GET_TITLES"
		green "-> $($LSDVD $device 2>/dev/null | grep 'Longest' | sed 's/track:/title:/')"
		echo ""
		brown "DVD Information Menu"
		brown "~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Display Audio Streams"
		echo "1 -> Display Cells"
		echo "2 -> Display Angles"
		echo "3 -> Display Chapters"
		echo "4 -> Display Subtitles"
		echo "5 -> Display Palette Info"
		echo "6 -> Display Title/Video Info"
		echo "7 -> Display All Of The Above"
		echo "8 -> Export Info To A File"
		echo "9 -> Exit"
		echo ""
		printf "Select an option: "
		read option
		case "$option" in
			[0-8]) true ;;
			9) exit 0 ;;
			""|*)
			error "-> Option unknown or not specified!"
			exit 1
			;;
		esac
		printf "Specify the DVD title [1-$TITLE/all]: "
		read dvd_title
		if [ "$dvd_title" != "all" ]; then
			title="-t $dvd_title"
			titlenum="title$dvd_title"
		else
			title=
			titlenum="alltitles"
		fi
		case "$option" in
			0) $LSDVD $title -a -Oh $device 2>/dev/null | less ;;
			1) $LSDVD $title -d -Oh $device 2>/dev/null | less ;;
			2) $LSDVD $title -n -Oh $device 2>/dev/null | less ;;
			3) $LSDVD $title -c -Oh $device 2>/dev/null | less ;;
			4) $LSDVD $title -s -Oh $device 2>/dev/null | less ;;
			5) $LSDVD $title -P -Oh $device 2>/dev/null | less ;;
			6) $LSDVD $title -v -Oh $device 2>/dev/null | less ;;
			7) $LSDVD $title -x -Oh $device 2>/dev/null | less ;;
			8)
			printf "Which option to export? [0-7/all]: "
			read opt
			case "$opt" in
				0) info="-a" ;;
				1) info="-d" ;;
				2) info="-n" ;;
				3) info="-c" ;;
				4) info="-s" ;;
				5) info="-P" ;;
				6) info="-v" ;;
				7|all) info="-x" ;;
				""|*)
				error "-> Option unknown or not specified!"
				exit 1
				;;
			esac
			printf "In which format to export? [text/perl/python/ruby/xml]: "
			read format
			case "$format" in
				text) ext="txt" ;;
				perl) ext="pl" ;;
				python) ext="py" ;;
				ruby) ext="rb" ;;
				xml) ext="xml" ;;
				""|*)
				error "-> Format unsupported or not specified!"
				exit 1
				;;
			esac
			DT="$HOME/$($LSDVD $device 2>/dev/null | grep '^Disc Title' | awk -F': ' '{print $2}')"
			if [ ! -z "$DT" ]; then
				DISC_TITLE="$DT"
			else
				DISC_TITLE="DVD"
			fi
			store_func() {
				case "$1" in
					0) EXPORT_FILE="$DISC_TITLE-$titlenum-audiostreams.$ext" ;;
					1) EXPORT_FILE="$DISC_TITLE-$titlenum-cells.$ext" ;;
					2) EXPORT_FILE="$DISC_TITLE-$titlenum-angles.$ext" ;;
					3) EXPORT_FILE="$DISC_TITLE-$titlenum-chapters.$ext" ;;
					4) EXPORT_FILE="$DISC_TITLE-$titlenum-subtitles.$ext" ;;
					5) EXPORT_FILE="$DISC_TITLE-$titlenum-palette.$ext" ;;
					6) EXPORT_FILE="$DISC_TITLE-$titlenum-title+video.$ext" ;;
					7|all) EXPORT_FILE="$DISC_TITLE-$titlenum-allinfo.$ext" ;;
				esac
			}
			info_func() {
				echo ""
				green "-> Saving to '$EXPORT_FILE'"
				echo ""
			}
			case "$format" in
				text)
				store_func $opt
				info_func
				$LSDVD $title $info -Oh $device 2>/dev/null > $EXPORT_FILE
				;;
				perl)
				store_func $opt
				info_func
				$LSDVD $title $info -Op $device 2>/dev/null > $EXPORT_FILE
				;;
				python)
				store_func $opt
				info_func
				$LSDVD $title $info -Oy $device 2>/dev/null > $EXPORT_FILE
				;;
				ruby)
				store_func $opt
				info_func
				$LSDVD $title $info -Or $device 2>/dev/null > $EXPORT_FILE
				;;
				xml)
				store_func $opt
				info_func
				$LSDVD $title $info -Ox $device 2>/dev/null > $EXPORT_FILE
				;;
			esac
			;;
		esac
		exit 0
		;;
		*|"")
		error "-> You didn't specify the type!"
		exit 1
		;;
	esac
	;;
	-iso)
	# DVD ISO dumping. This requiers
	# 'pv' but we fall back to 'dd'
	# if 'pv' is not on the user's
	# system
	if [ ! -x "$BC" -o ! -x "$DD" -o ! -x "$MPLAYER" -o ! -x "$LSDVD" ]; then
		error "-> bc, dd, mplayer or lsdvd missing!"
		exit 1
	fi
	interrupt_func() {
		echo ""
		error "-> Exiting..."
		sleep 1
		rm -f "$OUTPUT" 2>/dev/null
		exit 1
	}
	trap 'interrupt_func' SIGHUP SIGTSTP SIGINT SIGQUIT SIGKILL SIGABRT SIGFPE SIGSEGV SIGTERM SIGPIPE SIGIO
	check_space_func() {
		HDSPACE="$(df -m "$(dirname "$OUTPUT")" | tail -1 | sed -r 's/^.*\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+[0-9]+%.*/\1/')"
		if [ $HDSPACE -le 9216 ]; then
			echo ""
			error "-> You are running out of disk space in '$(dirname "$OUTPUT")'"
			error "-> Space left over: $HDSPACE MB ($(echo "scale=3; $HDSPACE/1024" | $BC -l | sed 's|^\.|0\.|') GB)"
			error "-> Please provide a different output directory!"
			echo ""
			exit 1
		fi
	}
	echo ""
	brown "+=======================+"
	brown "| DVD ISO Image Dumping |"
	brown "+=======================+"
	echo ""
	if [ -r /proc/sys/dev/cdrom/info ]; then
		DRIVE=$(grep "drive name" /proc/sys/dev/cdrom/info | sed 's/drive name://g')
		if [ ! -z "$DRIVE" ]; then
			for i in $DRIVE; do
				green "-> Found device: /dev/$i"
			done
		fi
	fi
	for i in /dev/dvd /dev/dvd[1-9]; do
		if [ -L $i ]; then
			green "-> Found symbolic link to DVD device: $(ls -l $i | grep -o '/dev.*')"
		fi
	done
	echo ""
	printf "Specify the DVD device [default is /dev/dvd]: "
	read -e dvd_dev
	if [ -z "$dvd_dev" ]; then
		device="/dev/dvd"
	else
		if [ ! -b "$dvd_dev" ]; then
			error "-> '$dvd_dev' is not a block device!"
			exit 1
		fi
		device="$dvd_dev"
	fi
	echo ""
	green "-> Unlocking the DVD disc..."
	$MPLAYER dvd://1 -dvd-device $device -vo null -nosound -nocache -frames 1 >/dev/null 2>&1
	green "-> Scanning for DVD title name..."
	TITLE="$($LSDVD $device 2>/dev/null | grep '^Disc Title' | awk -F': ' '{print $2}')"
	if [ ! -z "$TITLE" ]; then
		OUT="$HOME/$TITLE.iso"
	else
		OUT="$HOME/DVD-$$.iso"
	fi
	test -e "$OUT" && mv -f "$OUT" "$OUT.old"
	echo ""
	printf "Specify the Output for the ISO image [default is $OUT]: "
	read -e iso_out
	if [ -z "$iso_out" ]; then
		OUTPUT="$OUT"
		check_space_func
	else
		if [ -z "$(echo $iso_out | grep '^/')" ]; then
			error "-> You have to provide the full path!"
			exit 1
		fi
		test -d "$(dirname "$iso_out")" || mkdir -p "$(dirname "$iso_out")" 2>/dev/null
		OUTPUT="$iso_out"
		check_space_func
	fi
	echo ""
	green "-> Available disk space: $HDSPACE MB ($(echo "scale=3; $HDSPACE/1024" | $BC -l) GB)"
	green "-> Dumping disc content to ISO image, please wait..."
	green "-> This can take a while..."
	echo ""
	if [ -x "$PV" ]; then
		$PV "$device" > "$OUTPUT"
	else
		$DD if="$device" of="$OUTPUT" 2>/dev/null
	fi
	green "-> Done"
	echo ""
	exit 0
	;;
	-[1-3]p|-fq)
	true
	;;
	*)
	error "-> Unknown option: '$1'"
	error "-> Use: '$(basename $0) --help'"
	exit 1
	;;
esac


if [ -z "$3" ]; then
	error "-> No preset specified!"
	error "-> Use: h264enc --help"
	exit 1
fi

case "$2" in
	-p)
	case "$3" in
		ulq|elq|vlq|lq|mq|nq|hq|vhq|ehq|uhq|ihq|nlq|ani|anihq|sdb|sdm|sdh|hdb|hdm|hdh|f9|f9hq|qt|qthq|bd40|bdhq40|bd41|bdhq41|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq|mx|mxhq)
		true
		;;
		cp)
		if [ -z "$4" ]; then
			error "-> You have to load a custom preset file!"
			error "-> Use: h264enc $1 -p cp /path/to/file/preset.cfg"
			exit 1
		fi
		if [ -z "$(echo "$4" | grep '^/')" ]; then
			error "-> Please provide the full path to the preset file!"
			exit 1
		fi
		if [ ! -f "$4" ]; then
			error "-> No such file: '$4'"
			exit 1
		fi
		;;
		"")
		error "-> No preset specified!"
		error "-> Use: 'h264enc --help'"
		exit 1
		;;
		*)
		error "-> Unknown preset: '$3'"
		error "-> Use: 'h264enc --help'"
		exit 1
		;;
	esac
	;;
	*)
	error "-> Unknown option: '$2'"
	error "-> Use: 'h264enc --help' for more info"
	exit 1
	;;
esac

# The NLQ preset is suppored only in
# fixed-quant mode! Check and warn user
# about that.

if [ "$3" = "nlq" ]; then
	if [ "$1" != "-fq" ]; then
		error "-> The Near Lossless Quality (NLQ) preset is supported only in Fixed-Quant mode!"
		error "-> Use: h264enc -fq -p nlq"
		exit 1
	fi
fi

# For the Blu-ray presets, we need x264
# to be patched with the NAL HRD patch
# which is required for BD content

case "$3" in
	bd40|bdhq40|bd41|bdhq41)
	if [ -z "$($X264 --longhelp | grep '\--nal-hrd')" ]; then
		error "-> It appears that your x264 library is not patched with"
		error "   the NAL HRD patch. This is required for the Blu-ray"
		error "   presets!"
		echo ""
		error "-> Download the NAL HRD patch along with install instructions"
		error "   from http://h264enc.sourceforge.net/download.html"
		exit 1
	fi
	;;
esac

# Some portable device presets are
# not supported in -fq mode.

case "$3" in
	ipc|ipchq|ip|iphq|iph|iphhq|ar|arhq|bb|bbhq|nks60|nks60hq|psp|psphq|mz|mzhq)
	if [ "$1" = "-fq" ]; then
		error "-> The '$3' preset is only supported in 1-, 2-, or 3-pass encoding mode!"
		exit 1
	fi
	;;
esac

# Informative function for displaying
# the selected quality preset
display_quality_preset_func() {
	case "$1" in
		cp)		green "-> Using custom preset file: '$2'" ;;
		ulq)		green "-> Using \"Ultra Low Quality\" preset" ;;
		elq)		green "-> Using \"Extreme Low Quality\" preset" ;;
		vlq)		green "-> Using \"Very Low Quality\" preset" ;;
		lq)		green "-> Using \"Low Quality\" preset" ;;
		mq)		green "-> Using \"Medium Quality\" preset" ;;
		nq)		green "-> Using \"Normal Quality\" preset" ;;
		hq)		green "-> Using \"High Quality\" preset" ;;
		vhq)		green "-> Using \"Very High Quality\" preset" ;;
		ehq)		green "-> Using \"Extreme High Quality\" preset" ;;
		uhq)		green "-> Using \"Ultra High Quality\" preset" ;;
		ihq)		green "-> Using \"Insane High Quality\" preset" ;;
		nlq)		green "-> Using \"Near Lossless Quality\" preset" ;;
		ani)		green "-> Using \"Anime\" preset" ;;
		anihq)		green "-> Using \"Anime High-Quality\" preset" ;;
		f9)		green "-> Using \"Flash Player 9\" preset" ;;
		f9hq)		green "-> Using \"Flash Player 9 High-Quality\" preset" ;;
		qt)		green "-> Using \"QuickTime\" preset" ;;
		qthq)		green "-> Using \"QuickTime High-Quality\" preset" ;;
		bd40)		green "-> Using \"Blu-ray (Main@L4.0)\" preset" ;;
		bdhq40)		green "-> Using \"Blu-ray High-Quality (High@L4.0)\" preset" ;;
		bd41)		green "-> Using \"Blu-ray (Main@L4.0)\" preset" ;;
		bdhq41)		green "-> Using \"Blu-ray High-Quality (High@L4.1)\" preset" ;;
		sdb)		green "-> Using \"Stand-alone HW Players SD (Baseline@L3.0)\" preset" ;;
		sdm)		green "-> Using \"Stand-alone HW Players SD (Main@L3.0)\" preset" ;;
		sdh)		green "-> Using \"Stand-alone HW Players SD (High@L3.0)\" preset" ;;
		hdb)		green "-> Using \"Stand-alone HW Players HD (Baseline@L4.0)\" preset" ;;
		hdm)		green "-> Using \"Stand-alone HW Players HD (Main@L4.0)\" preset" ;;
		hdh)		green "-> Using \"Stand-alone HW Players HD (High@L4.0)\" preset" ;;
		ipc)		green "-> Using \"Apple iPod Classic\" preset" ;;
		ipchq)		green "-> Using \"Apple iPod Classic High-Quality\" preset" ;;
		ip)		green "-> Using \"Apple iPod\" preset" ;;
		iphq)		green "-> Using \"Apple iPod High-Quality\" preset" ;;
		iph)		green "-> Using \"Apple iPhone\" preset" ;;
		iphhq)		green "-> Using \"Apple iPhone High-Quality\" preset" ;;
		atv)		green "-> Using \"AppleTV\" preset" ;;
		atvhq)		green "-> Using \"AppleTV High-Quality\" preset" ;;
		ar)		green "-> Using \"Archos 605\" preset" ;;
		arhq)		green "-> Using \"Archos 605 High-Quality\" preset" ;;
		bb)		green "-> Using \"Blackberry 9000\" preset" ;;
		bbhq)		green "-> Using \"Blackberry 9000 High-Quality\" preset" ;;
		nks60)		green "-> Using \"Nokia S60\" preset" ;;
		nks60hq)	green "-> Using \"Nokia S60 High-Quality\" preset" ;;
		psp)		green "-> Using \"Sony PSP\" preset" ;;
		psphq)		green "-> Using \"Sony PSP High-Quality\" preset" ;;
		ps3)		green "-> Using \"Sony PS3\" preset" ;;
		ps3hq)		green "-> Using \"Sony PS3 High-Quality\" preset" ;;
		mz)		green "-> Using \"Microsoft Zune\" preset" ;;
		mzhq)		green "-> Using \"Microsoft Zune High-Quality\" preset" ;;
		mx)		green "-> Using \"Microsoft XBOX 360\" preset" ;;
		mxhq)		green "-> Using \"Microsoft XBOX 360\" preset" ;;
	esac
}

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

if [ ! -x "$BC" ]; then
	error "-> Checking for utility 'bc'... FAILED!"
	exit 1
fi

if [ ! -x "$MENCODER" ]; then
	error "-> Checking for MEncoder... FAILED!"
	exit 1
fi

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

if [ ! -x "$MPLAYER" ]; then
	error "-> Checking for MPlayer... FAILED!"
	exit 1
fi

# Make config dir
CONFIGDIR=$H264ENCDIR/h264enc_$$
test -d $CONFIGDIR || mkdir -p $CONFIGDIR

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

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

# Remove config dir on
# user error
rmconf() {
	rm -rf $CONFIGDIR
	rm -f $H264ENCDIR/batch$$
	exit 1
}

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

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

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

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

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

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

# Denoising
video_denoise_func() {
	printf "Would you like to Denoise the $type? [y/n]: "
	read dn
	if [ "$dn" = "y" -o "$dn" = "Y" ]; then
		echo ""
		brown "Available Video Denoise Filters"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "All filters below have tunable parameters."
		echo "The higher the individual values are, the"
		echo "more filtering will be done."
		echo ""
		echo "0 -> 3D Denoise Filter (denoise3d)"
		echo "1 -> High-Quality 3D Denoise Filter (hqdn3d)"
		echo "2 -> Overcomplete Wavelet Denoiser (ow)"
		echo "3 -> Temporal Denoiser (tn)"
		echo "4 -> x264's Internal Denoiser (nr)"
		echo "5 -> Skip denoising"
		echo ""
		printf "Select a Denoise filter [default is 1]: "
		read dnfilt
		case "$dnfilt" in
			0)
			echo ""
			brown "3D Denoise Filter"
			brown "~~~~~~~~~~~~~~~~~"
			echo "This filter aims to reduce image noise producing"
			echo "smooth images and making still images really still"
			echo "This also should enhance compressibility."
			echo ""
			echo "0 -> Weak denoising"
			echo "1 -> Medium denoising"
			echo "2 -> Strong denoising"
			echo "3 -> Extra strong denoising"
			echo "4 -> User defined"
			echo ""
			printf "Select the Denoising level [default is 1]: "
			read denoiselevel
			case "$denoiselevel" in
				0) denoisefilter="denoise3d=3:2:5," ;;
				1|"") denoisefilter="denoise3d=4:3:6," ;;
				2) denoisefilter="denoise3d=7:6:9," ;;
				3) denoisefilter="denoise3d=10:9:12," ;;
				4)
				printf "Specify the Denoise values [default is 3:2:4]: "
				read dnvalues
				if [ -z "$dnvalues" ]; then
					denoisefilter="denoise3d=3:2:4,"
				else
					denoisefilter="denoise3d=$dnvalues,"
				fi
				;;
				*)
				error "-> Unknown option: '$denoiselevel'"
				error "-> Exiting in function: video_denoise_func()"
				rmconf
				;;
			esac
			;;
			1|"")
			echo ""
			brown "High-Quality 3D Denoise Filter"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "This filter aims to reduce image noise producing"
			echo "smooth images and making still images really still"
			echo "This also should enhance compressibility."
			echo ""
			echo "0 -> Weak denoising"
			echo "1 -> Medium denoising"
			echo "2 -> Strong denoising"
			echo "3 -> Extra strong denoising"
			echo "4 -> User defined"
			echo ""
			printf "Select the Denoising level [default is 1]: "
			read denoiselevel
			case "$denoiselevel" in
				0) denoisefilter="hqdn3d=3:2:5," ;;
				1|"") denoisefilter="hqdn3d=4:3:6," ;;
				2) denoisefilter="hqdn3d=7:6:9," ;;
				3) denoisefilter="hqdn3d=10:9:12," ;;
				4)
				printf "Specify the Denoise values [default is 3:2:4]: "
				read dnvalues
				if [ -z "$dnvalues" ]; then
					denoisefilter="hqdn3d=3:2:4,"
				else
					denoisefilter="hqdn3d=$dnvalues,"
				fi
				;;
				*)
				error "-> Unknown option: '$denoiselevel'"
				error "-> Exiting in function: video_denoise_func()"
				rmconf
				;;
			esac
			;;
			2)
			echo ""
			brown "Overcomplete Wavelet Denoiser"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "This filter belongs to the new generation of"
			echo "denoisers which use wavelets to denoise the"
			echo "video content. The filter has three parameters"
			echo ""
			echo "Depth (integer)"
			echo "Luma Strength (integer/float)"
			echo "Chroma Strength (integer/float)"
			echo ""
			echo "Larger depth values will denoise lower frequency"
			echo "components more, but will slow down filtering."
			echo "The format is as follows: depth:luma:chroma"
			echo ""
			printf "Specify the Denoise Filter Parameters [default is 3:1.0:1.0]: "
			read dfp
			if [ -z "$dfp" ]; then
				denoisefilter="ow=3:1.0:1.0,"
			else
				denoisefilter="ow=$dfp,"
			fi
			;;
			3)
			echo ""
			brown "Temporal Denoiser"
			brown "~~~~~~~~~~~~~~~~~"
			echo "This is a temporal denoiser (without motion"
			echo "compensation) which aims to reduce image"
			echo "noise in the video content. It has three"
			echo "thresholds. The higher the values, the more"
			echo "filtering will be done. The format is as"
			echo "follows: threshold1:threshold2:threshold3"
			echo ""
			echo "Note that the second value should be higher"
			echo "than or equal to the first one, and the"
			echo "third value should be higher than or equal"
			echo "to the second value."
			echo ""
			printf "Specify the Denoise Filter Parameters [default is 64:128:256]: "
			read dfp
			if [ -z "$dfp" ]; then
				denoisefilter="pp=tn:64:128:256:c,"
			else
				denoisefilter="pp=tn:$dfp:c,"
			fi
			;;
			4)
			denoisefilter=
			printf "Specify the Noise Reduction Range [0-100000 - default is 350]: "
			read nrr
			if [ -z "$nrr" ]; then
				nr=":nr=350"
			else
				nr=":nr=$nrr"
			fi
			;;
			5)
			false
			;;
			*)
			error "-> Unknown denoise option: '$dnfilt'"
			error "-> Exiting in function: video_denoise_func()"
			rmconf
			;;
		esac
	elif [ "$dn" = "n" -o "$dn" = "N" -o -z "$dn" ]; then
		denoisefilter=
	fi
}

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

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

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

# Subtitles
get_subtitles_func() {
	echo ""
	green "-> Scanning for subtitles..."
	$MPLAYER "$sourcetype" $device -nosound -vo null -frames 1 -nocache 2>/dev/null > $CONFIGDIR/subs
	SUBS=$(grep "^subtitle" $CONFIGDIR/subs)
	rm -f $CONFIGDIR/subs
	echo ""
	brown "Available Subtitles On Disc"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
	if [ ! -z "$SUBS" ]; then
		echo "$SUBS" | sed -e 's/^subtitle //g' -e 's/( sid ):/Subtitle ID:/g' -e 's/language:/- Language:/g'
	else
		green "-> No subtitles available or failed to detect them!"
	fi
	echo ""
}

video_subtitles_func() {
	printf "Would you like to include/rip a Subtitle? [y/n]: "
	read sub
	if [ "$sub" = "y" -o "$sub" = "Y" ]; then
		case "$source" in
			file|FILE|File)
			echo ""
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "For video file encodings, h264enc supports two"
			echo "subtitle methods: hardcoding the subtitle into"
			echo "the movie or importing it into the chosen container."
			echo "Only two subtitle formats are supported and have"
			echo "been tested at the moment: VobSub and SRT subtitles."
			echo "When importing a subtitle, only the MP4 and MKV"
			echo "containers are supported!"
			echo ""
			echo "0 -> Hardcode the given subtitle into the movie."
			echo "1 -> Import the given subtitle into the MP4 and/or MKV container"
			echo "2 -> Skip subtitle inclusion"
			echo ""
			printf "Select the Subtitle Method [default is 0]: "
			read submethod
			suberror() {
				case "$1" in
					sf)
					if [ ! -f "$subfile" -o -z "$(echo "$subfile" | grep '^/')" ]; then
						error "-> Subtitle file doesn't exist or you didn't"
						error "   specify the full path to it!"
						error "-> Exiting in function: video_subtitles_func()"
						rmconf
					fi
					;;
					option)
					error "-> Subtitle format unknown or not specified!"
					error "-> Exiting in function: video_subtitles_func()"
					rmconf
					;;
				esac
			}
			case "$submethod" in
				0|"")
				printf "Which subtitle format are you using? [vobsub/srt]: "
				read subformat
				case "$subformat" in
					vobsub)
					printf "Provide the subtitle .sub file: "
					read -e subfile
					suberror sf
					;;
					srt)
					printf "Provide the subtitle .srt file: "
					read -e subfile
					suberror sf
					;;
					*)
					suberror option
					;;
				esac
				subtitle="-sub \"$subfile\" -subfont-autoscale 1"
				;;
				1)
				printf "Which subtitle format are you using? [vobsub/srt]: "
				read subformat
				case "$subformat" in
					vobsub)
					printf "Provide the subtitle .idx file: "
					read -e subfile
					suberror sf
					;;
					srt)
					printf "Provide the subtitle .srt file: "
					read -e subfile
					suberror sf
					;;
					*)
					suberror option
					;;
				esac
				# The below variable is used to import
				# subtitles into the MP4/MKV containers
				IDXFILE="$subfile"
				;;
				2)
				false
				;;
				*)
				error "-> Unknown option: '$submethod'"
				error "-> Exiting in function: video_subtitles_func()"
				rmconf
				;;
			esac
			;;
			dvd|DVD|Dvd)
			echo ""
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "0 -> Hardcode a subtitle into the movie"
			echo "1 -> Dump subtitle(s) to file(s) on disk"
			echo "2 -> Skip subtitle inclusion"
			echo ""
			printf "Select the Subtitle Method [default is 1]: "
			read submethod
			case "$submethod" in
				0)
				get_subtitles_func
				printf "Specify the Subtitle ID number [press 'Enter' to skip]: "
				read subid
				if [ ! -z "$(echo $subid | grep '[a-zA-Z]')" ]; then
					error "-> You have to specify the Subtitle ID number, not the language code!"
					error "-> Exiting in function: video_subtitles_func()"
					rmconf
				fi
				if [ -z "$subid" ]; then
					subtitle=
				else
					subtitle="-sid $subid -spuaa 4 -spugauss 0.7"
				fi
				;;
				1|"")
				# First subtitle gets dumped during
				# encoding time, second one after
				# encoding has finished
				get_subtitles_func
				printf "Specify the Subtitle ID number (subtitle 1) [press 'Enter' to skip]: "
				read subid1
				if [ ! -z "$(echo $subid1 | grep '[a-zA-Z]')" ]; then
					error "-> You have to specify the Subtitle ID number, not the language code!"
					error "-> Exiting in function: video_subtitles_func()"
					rmconf
				fi
				if [ -z "$subid1" ]; then
					subtitle=
					vobsubout=
				else
					subtitle="-sid $subid1"
					vobsubout="-vobsubout $(echo \"$OUTPUT\" | sed 's|\.avi||') -vobsuboutindex 0"
				fi
				printf "Specify the Subtitle ID number (subtitle 2) [press 'Enter' to skip]: "
				read subid2
				if [ ! -z "$(echo $subid2 | grep '[a-zA-Z]')" ]; then
					error "-> You have to specify the Subtitle ID number, not the language code!"
					error "-> Exiting in function: video_subtitles_func()"
					rmconf
				fi
				if [ -z "$subid2" ]; then
					subtitle2=
					vobsubout2=
				else
					subtitle2="-sid $subid2"
					vobsubout2="-vobsubout $(echo \"$OUTPUT\" | sed 's|\.avi|_sub2|') -vobsuboutindex 1"
				fi
				printf "Specify the Subtitle ID number (subtitle 3) [press 'Enter' to skip]: "
				read subid3
				if [ ! -z "$(echo $subid3 | grep '[a-zA-Z]')" ]; then
					error "-> You have to specify the Subtitle ID number, not the language code!"
					error "-> Exiting in function: video_subtitles_func()"
					rmconf
				fi
				if [ -z "$subid3" ]; then
					subtitle3=
					vobsubout3=
				else
					subtitle3="-sid $subid3"
					vobsubout3="-vobsubout $(echo \"$OUTPUT\" | sed 's|\.avi|_sub3|') -vobsuboutindex 2"
				fi
				# Set IDXFILE variables for
				# the MKV/MP4 containers.
				# These are used to import
				# the subtitle(s)
				if [ -z "$subtitle" -a -z "$subtitle2" -a -z "$subtitle3" ]; then
					IDXFILE1=
					IDXFILE2=
					IDXFILE3=
				elif [ ! -z "$subtitle" -a -z "$subtitle2" -a -z "$subtitle3" ]; then
					IDXFILE1=$(echo "$OUTPUT" | sed 's|\.avi|\.idx|')
					IDXFILE2=
					IDXFILE3=
				elif [ -z "$subtitle" -a ! -z "$subtitle2" -a -z "$subtitle3" ]; then
					IDXFILE1=
					IDXFILE2=$(echo "$OUTPUT" | sed 's|\.avi|_sub2.idx|')
					IDXFILE3=
				elif [ -z "$subtitle" -a -z "$subtitle2" -a ! -z "$subtitle3" ]; then
					IDXFILE1=
					IDXFILE2=
					IDXFILE3=$(echo "$OUTPUT" | sed 's|\.avi|_sub3.idx|')
				elif [ ! -z "$subtitle" -a ! -z "$subtitle2" -a -z "$subtitle3" ]; then
					IDXFILE1=$(echo "$OUTPUT" | sed 's|\.avi|\.idx|')
					IDXFILE2=$(echo "$OUTPUT" | sed 's|\.avi|_sub2.idx|')
					IDXFILE3=
				elif [ ! -z "$subtitle" -a -z "$subtitle2" -a ! -z "$subtitle3" ]; then
					IDXFILE1=$(echo "$OUTPUT" | sed 's|\.avi|\.idx|')
					IDXFILE2=
					IDXFILE3=$(echo "$OUTPUT" | sed 's|\.avi|_sub3.idx|')
				elif [ -z "$subtitle" -a ! -z "$subtitle2" -a ! -z "$subtitle3" ]; then
					IDXFILE1=
					IDXFILE2=$(echo "$OUTPUT" | sed 's|\.avi|_sub2.idx|')
					IDXFILE3=$(echo "$OUTPUT" | sed 's|\.avi|_sub3.idx|')
				elif [ ! -z "$subtitle" -a ! -z "$subtitle2" -a ! -z "$subtitle3" ]; then
					IDXFILE1=$(echo "$OUTPUT" | sed 's|\.avi|\.idx|')
					IDXFILE2=$(echo "$OUTPUT" | sed 's|\.avi|_sub2.idx|')
					IDXFILE3=$(echo "$OUTPUT" | sed 's|\.avi|_sub3.idx|')
				fi
				SUBFILE1=$(echo "$IDXFILE1" | sed 's|\.idx|\.sub|')
				SUBFILE2=$(echo "$IDXFILE2" | sed 's|\.idx|\.sub|')
				SUBFILE3=$(echo "$IDXFILE3" | sed 's|\.idx|\.sub|')
				for i in "$IDXFILE1" "$IDXFILE2" "$IDXFILE3" "$SUBFILE1" "$SUBFILE2" "$SUBFILE3"; do
					test -e "$i" && mv -f "$i" "$i.old"
				done
				;;
				2)
				false
				;;
				*)
				error "-> Unknown subtitle method option: '$submethod'"
				error "-> Exiting in function: video_subtitles_func()"
				rmconf
				;;
			esac
			;;
		esac
	fi
}

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

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

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

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


# Custom matrices for quality presets
# and manual codec configuration
custom_matrix_func() {
	printf "Would you like to use Predefined/Custom Quantization Matrices (cqm)? [y/n]: "
	read cuma
	if [ "$cuma" = "y" -o "$cuma" = "Y" ]; then
		echo ""
		brown "Predefined/Custom Quantization Matrices"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Flat -> Predefined flat 16 matrix"
		echo "1 -> JVT --> Predefined JVT matrix"
		echo "2 -> Load a custom matrix file"
		echo "3 -> Skip loading/using matrices"
		echo ""
		printf "Which one to use? [default is 0]: "
		read cmatrix
		case "$cmatrix" in
			0|"") cqm=":cqm=flat" ;;
			1) cqm=":cqm=jvt" ;;
			2)
			printf "Provide the Custom Matrix file: "
			read -e matrixfile
			if [ -z "$(echo "$matrixfile" | grep '^/')" -o ! -f "$matrixfile" ]; then
				echo ""
				green "-> File does not exist or you didn't provide the full path to it!"
				green "-> Skipping loading of a matrix!"
				echo ""
				cqm=
			else
				cqm=":cqm=$matrixfile"
			fi
			;;
			3) false ;;
			*) cqm= ;;
		esac
	elif [ "$cuma" = "n" -o "$cuma" = "N" -o -z "$cuma" ]; then
		cqm=
	fi
}

# Set output filename.
check_outfile_func() {
	if [ -z "$(echo "$outfile" | grep '^/')" ]; then
		error "-> You have to specify the full path!"
		error "-> Exiting in function: set_output_filename_func()"
		rmconf
	fi
	if [ -z "$(echo "$outfile" | grep '\.avi')" ]; then
		error "-> You have to use the '.avi' extension for the output file!"
		error "-> Exiting in function: set_output_filename_func()"
		rmconf
	fi
}

set_output_filename_func() {
	case "$source" in
		file|FILE|File)
		printf "Provide a name for the Output File [default is $HOME/H264-$$.avi]: "
		read -e outfile
		if [ -z "$outfile" ]; then
			OUTPUT="$HOME/H264-$$.avi"
		else
			check_outfile_func
			OUTPUT="$outfile"
		fi
		;;
		dvd|DVD|Dvd)
		green "-> Scanning for DVD title name..."
		GET_TITLE=$($LSDVD $(echo $device | awk '{print $2}') 2>/dev/null | grep '^Disc Title:' | sed 's/Disc Title: //')
		SET_TITLE=$(echo "$GET_TITLE" | sed 's/_/ /g')
		echo ""
		if [ ! -z "$GET_TITLE" ]; then
			printf "Provide a name for the Output File [default is $HOME/$SET_TITLE.avi]: "
			read -e outfile
			if [ -z "$outfile" ]; then
				OUTPUT="$HOME/$SET_TITLE.avi"
			else
				check_outfile_func
				OUTPUT="$outfile"
			fi
		else
			printf "Provide a name for the Output File [default is $HOME/H264-$$.avi]: "
			read -e outfile
			if [ -z "$outfile" ]; then
				OUTPUT="$HOME/H264-$$.avi"
			else
				check_outfile_func
				OUTPUT="$outfile"
			fi
		fi
		;;
	esac
	# Create destination directory if not present
	if [ ! -d "$(dirname "$OUTPUT")" ]; then
		mkdir -p "$(dirname "$OUTPUT")" 2>/dev/null
		if [ $? != 0 ]; then
			error "-> Failed to create the destination directory!"
			error "-> Maybe a permissions problem?"
			error "-> Exiting in function: set_output_filename_func()"
			rmconf
		fi
	fi
	# Check to see if destination directory
	# is writable
	TESTFILE="$(dirname "$(echo "$OUTPUT")")/.h264enctest_$$"
	touch "$TESTFILE" 2>/dev/null
	if [ $? != 0 ]; then
		error "-> Destination directory '$(dirname "$(echo "$OUTPUT")")' is not writable!"
		error "-> Exiting in function: set_output_filename_func()"
		rmconf
	else
		rm -f "$TESTFILE"
	fi
	test -e "$OUTPUT" && mv -f "$OUTPUT" "$OUTPUT.old"
}

# 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 convert it to MKV/MP4/OGM, just play
# it safe and check if it's <= 4 GB
# Do the same for the $CONFIGDIR directory
# since it will be used to store temporary
# files when converting from AVI -> MP4

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


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

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

printf "Would you like to encode a Video File or a DVD? [file/dir/dvd]: "
read source
case "$source" in
	file|FILE|File)
	type="video file"
	printf "Provide the Input Video File: "
	read -e infile
	if [ ! -f "$infile" ]; then
		error "-> No such file: '$infile'"
		rmconf
	fi
	set_output_filename_func
	check_diskspace_func
	sourcetype="$infile"
	if [ "$sourcetype" = "$OUTPUT" ]; then
		error "-> You cannot use the same name for both the input and output file!"
		rmconf
	fi
	# Scan to see if input file has
	# more than one video stream
	printf "Scan for multiple video streams? [y/n]: "
	read mvs
	if [ "$mvs" = "y" -o "$mvs" = "Y" ]; then
		echo ""
		green "-> Scanning for video streams..."
		$MPLAYER "$sourcetype" -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/videostreams
		if [ $(grep '^ID_VIDEO_ID' $CONFIGDIR/videostreams | wc -l) -lt 2 ]; then
			vid=
			green "-> Found only one video stream"
			green "-> Skipping stream selection"
			echo ""
		else
			echo ""
			for i in $(grep '^ID_VIDEO_ID' $CONFIGDIR/videostreams); do
				echo "$(echo "Video stream: $(echo $i | awk -F= '{print $2}')")"
			done
			echo ""
			VIDSTREAM=$(grep '^ID_VIDEO_ID' $CONFIGDIR/videostreams | awk -F= '{print $2}')
			printf "Specify the video stream number for encoding [default is $(echo $VIDSTREAM | awk '{print $1}')]: "
			read vidstream
			if [ -z "$vidstream" ]; then
				vid="-vid 0"
			else
				vid="-vid $vidstream"
			fi
		fi
		rm -f $CONFIGDIR/videostreams
	elif [ "$mvs" = "n" -o "$mvs" = "N" -o -z "$mvs" ]; then
		vid=
	fi
	printf "Would you like to use Pre/Postprocessing video filters? [y/n]: "
	read vfilters
	if [ "$vfilters" = "y" -o "$vfilters" = "Y" ]; then
		echo ""
		brown "+==================================+"
		brown "| Pre/Postprocessing Video Filters |"
		brown "+==================================+"
		echo ""
		video_deinterlace_func
		video_interlace_func
		video_deblock_func
		video_denoise_func
		video_unsharp_func
		video_brightness_func
	elif [ "$vfilters" = "n" -o "$vfilters" = "N" -o -z "$vfilters" ]; then
		interlaced=":nointerlaced"
	fi
	video_crop_func
	video_subtitles_func
	;;
	dir|DIR|Dir)
	type="video files"
	printf "Provide one Input Video File from the directory: "
	read -e infile
	if [ ! -f "$infile" ]; then
		error "-> No such file: '$infile'"
		rmconf
	fi
	sourcetype="$infile"
	printf "Where to store the encodings? [default is $HOME/h264enc_$$]: "
	read -e outdir
	if [ -z "$outdir" ]; then
		OUTPUT="$HOME/h264enc_$$"
		if [ ! -d "$OUTPUT" ]; then
			mkdir -p "$OUTPUT" 2>/dev/null
			if [ $? != 0 ]; then
				error "-> Failed to create the output directory!"
				error "-> Maybe a permissions problem?"
				rmconf
			fi
		fi
	else
		if [ "$(dirname "$sourcetype")" = "$outdir" ]; then
			error "-> You cannot use the input directory as output directory!"
			rmconf
		fi
		OUTPUT="$outdir"
		if [ ! -d "$OUTPUT" ]; then
			mkdir -p "$OUTPUT" 2>/dev/null
			if [ $? != 0 ]; then
				error "-> Failed to create the output directory!"
				error "-> Maybe a permissions problem?"
				rmconf
			fi
		fi
	fi
	printf "Would you like to use Pre/Postprocessing video filters? [y/n]: "
	read vfilters
	if [ "$vfilters" = "y" -o "$vfilters" = "Y" ]; then
		echo ""
		brown "+==================================+"
		brown "| Pre/Postprocessing Video Filters |"
		brown "+==================================+"
		echo ""
		video_deinterlace_func
		video_interlace_func
		video_deblock_func
		video_denoise_func
		video_unsharp_func
		video_brightness_func
	elif [ "$vfilters" = "n" -o "$vfilters" = "N" -o -z "$vfilters" ]; then
		interlaced=":nointerlaced"
	fi
	video_crop_func
	;;
	dvd|DVD|Dvd)
	type=DVD
	vid=
	if [ ! -x "$LSDVD" ]; then
		error "-> Checking for lsdvd... FAILED!"
		rmconf
	fi
	check_spaces_func() {
		if [ ! -z "$(echo "$device" | sed 's/-dvd-device //' | grep ' ')" ]; then
			error "-> Spaces in file names for devices/ISO/VIDEO_TS not supported!"
			rmconf
		fi
	}
	echo ""
	brown "Input Selection"
	brown "~~~~~~~~~~~~~~~"
	echo "0 -> Encode from a DVD disc/drive"
	echo "1 -> Encode from a DVD ISO image"
	echo "2 -> Encode from a DVD VIDEO_TS directory"
	echo ""
	printf "Select the input [default is 0]: "
	read dvdsource
	case "$dvdsource" in
		0|"")
		get_dvd_devices_func
		printf "Specify the DVD Device [default is /dev/dvd]: "
		read -e dev
		if [ -z "$dev" ]; then
			device="-dvd-device /dev/dvd"
		else
			if [ ! -b "$dev" ]; then
				error "-> '$dev' is not a block device!"
				rmconf
			fi
			device="-dvd-device $dev"
		fi
		check_spaces_func
		;;
		1)
		printf "Provide the DVD ISO image: "
		read -e dvdiso
		if [ -z "$dvdiso" -o -z "$(echo "$dvdiso" | grep '^/')" -o ! -e "$dvdiso" ]; then
			error "-> ISO image not specified, does not exist or full path not provided!"
			rmconf
		else
			device="-dvd-device $dvdiso"
		fi
		check_spaces_func
		;;
		2)
		printf "Provide the DVD VIDEO_TS directory: "
		read -e dvdvt
		if [ -z "$dvdvt" -o -z "$(echo "$dvdvt" | grep '^/')" -o ! -d "$dvdvt" ]; then
			error "-> Directory not specified, does not exist or full path not provided!"
			rmconf
		else
			device="-dvd-device $dvdvt"
		fi
		check_spaces_func
		;;
		*)
		error "-> Unknown option: '$dvdsource'"
		rmconf
		;;
	esac
	# Before scanning the DVD with 'lsdvd' it has to be
	# unlocked or 'lsdvd' will fail to read it, so we
	# run mplayer here just to unlock it
	echo ""
	green "-> Unlocking the DVD disc..."
	$MPLAYER dvd://1 $device -nosound -vo null -frames 1 -nocache >/dev/null 2>&1
	set_output_filename_func
	check_diskspace_func
	echo ""
	green "-> Scanning for DVD titles..."
	$LSDVD $(echo $device | awk '{print $2}') 2>/dev/null > $CONFIGDIR/dvdtitles
	ALLTITLES=$(grep '^Title' $CONFIGDIR/dvdtitles | awk '{print $1,$2,$3,$4}' | sed 's/,/ -/g' | cut -f '1' -d '.')
	DVDTITLE=$(grep 'Longest' $CONFIGDIR/dvdtitles | awk '{print $3}' | sed 's/^0//')
	TOTAL_TITLES=$(grep '^Title' $CONFIGDIR/dvdtitles | sed 's/,//g' | awk 'END{print $2}' | sed 's/^0//')
	TITLE_LENGTH=$($LSDVD -t $DVDTITLE $(echo $device | awk '{print $2}') 2>/dev/null | grep "Length" | awk '{print $4}' | cut -f '1' -d '.')
	rm -f $CONFIGDIR/dvdtitles
	echo ""
	if [ -z "$DVDTITLE" ]; then
		brown "Disc Title: $GET_TITLE"
		echo "$ALLTITLES"
		echo ""
		green "-> Titles On Disc: $TOTAL_TITLES"
		green "-> Failed to detect longest DVD title!"
		green "-> You have to specify it yourself!"
		DVDTITLE="??"
	else
		brown "Disc Title: $GET_TITLE"
		echo "$ALLTITLES"
		echo ""
		green "-> Titles On Disc: $TOTAL_TITLES"
		green "-> Longest Title:  $DVDTITLE - Title Length: $TITLE_LENGTH"
		
	fi
	echo ""
	printf "Specify the DVD title for encoding [default/longest is $DVDTITLE]: "
	read title
	if [ -z "$title" -a "$DVDTITLE" = "??" ]; then
		error "-> You have to specify the DVD title for encoding!"
		rmconf
	fi
	if [ -z "$title" ]; then
		sourcetype="dvd://$DVDTITLE"
	else
		sourcetype="dvd://$title"
	fi
	printf "Would you like to encode from a different DVD angle? [y/n]: "
	read angle
	if [ "$angle" = "y" -o "$angle" = "Y" ]; then
		echo ""
		green "-> Scanning for angles in title $(echo $sourcetype | sed 's|dvd://||')..."
		ANGLES=$($MPLAYER $sourcetype $device -nosound -vo null -frames 1 -nocache 2>/dev/null | grep "angles")
		if [ ! -z "$ANGLES" ]; then
			green "-> $ANGLES"
		else
			green "-> Could not detect any angles in this DVD title!"
		fi
		echo ""
		printf "From which angle to encode the DVD? [default is 1]: "
		read dvd_angle
		if [ -z "$dvd_angle" ]; then
			dvdangle=
		else
			dvdangle="-dvdangle $dvd_angle"
		fi
	elif [ "$angle" = "n" -o "$angle" = "N" -o -z "$angle" ]; then
		dvdangle=
	fi
	printf "Would you like to encode only Specific Chapters? [y/n]: "
	read chap
	if [ "$chap" = "y" -o "$chap" = "Y" ]; then
		echo ""
		green "-> Scanning for chapters in title $(echo $sourcetype | sed 's|dvd://||')..."
		$MPLAYER $sourcetype $device -nosound -vo null -frames 1 -identify -nocache 2>/dev/null > $CONFIGDIR/chapters
		echo ""
		brown "Available Chapters On Disc"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
		if [ ! -z "$(grep '^CHAPTERS' $CONFIGDIR/chapters)" ]; then
			grep '^CHAPTERS' $CONFIGDIR/chapters | sed -e 's/CHAPTERS: //' -e 's/,/ /g' > $CONFIGDIR/getchaps
			for i in $(cat $CONFIGDIR/getchaps); do
				echo "Chapter: $i - Start position: " >> $CONFIGDIR/lschaps
			done
			nl $CONFIGDIR/lschaps | awk '{print $2,$1,$4,$5,$6,$3}'
		else
			green "-> Could not detect any chapters in this DVD title!"
		fi
		rm -f $CONFIGDIR/*
		echo ""
		printf "Which chapter(s) to encode from this DVD title? [example 1-3]: "
		read chapenc
		if [ -z "$chapenc" ]; then
			chapters=
		else
			chapters="-chapter $chapenc"
		fi
		# Overwirte output name and
		# append chapter info to it
		if [ ! -z "$chapters" ]; then
			OUTPUT="$(echo "$OUTPUT" | sed 's/\.avi//')_chapter$(echo $chapters | awk '{print $2}').avi"
			test -e "$OUTPUT" && mv -f "$OUTPUT" "$OUTPUT.old"
		fi
	elif [ "$chap" = "n" -o "$chap" = "N" -o -z "$chap" ]; then
		chapters=
	fi
	# Export chapters information to a file.
	# This can be used to import chapters
	# info when muxing into MKV/MP4/OGM. It
	# requires ogmtools' 'dvdxchap'.
	if [ -x "$DVDXCHAP" ]; then
		printf "Export DVD chapters information to a file on disk? [y/n]: "
		read chapexp
		if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
			CHAPTERSFILE=$(echo "$OUTPUT" | sed 's|\.avi|\.chaps|')
			test -e "$CHAPTERSFILE" && mv -f "$CHAPTERSFILE" "$CHAPTERSFILE.old"
			$DVDXCHAP -t $(echo $sourcetype | sed 's|dvd://||') $(echo $device | awk '{print $2}') | grep '^CHAPTER' > "$CHAPTERSFILE"
		fi
	fi
	printf "Would you like to use Pre/Postprocessing video filters? [y/n]: "
	read vfilters
	if [ "$vfilters" = "y" -o "$vfilters" = "Y" ]; then
		echo ""
		brown "+==================================+"
		brown "| Pre/Postprocessing Video Filters |"
		brown "+==================================+"
		echo ""
		video_deinterlace_func
		video_interlace_func
		video_deblock_func
		video_denoise_func
		video_unsharp_func
		video_brightness_func
	elif [ "$vfilters" = "n" -o "$vfilters" = "N" -o -z "$vfilters" ]; then
		interlaced=":nointerlaced"
	fi
	video_crop_func
	video_subtitles_func
	;;
	*)
	error "-> You have to specify the input source type (file/dir/dvd)!"
	rmconf
	;;
esac

# This can be tricky if we deal with mixed Progressive
# NTSC/NTSC content.
# Skip frame rate selection if interlacing progressive
# content or deinterlacing interlaced content with a
# deinterlacing filter which doubles the output frame
# rate. Both actions are mutually exclusive with the
# option below.

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

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

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

# Pulldown reversal/inverse telecine/telecine
# 3:2 pulldown filters. Mutually exclusive with
# (frame doubling) deinterlacing filters and
# FPS conversion

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

# Overwrite input/output frame rate if the
# user has chosen to interlace his progressive
# content during the encoding process or if
# the user is deinterlacing it with a deinterlace
# filter which doubles the output frame rate.
# Only one at a time of the below conditionals
# can be true, the appropriate functions take
# care of that.

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

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

# Valid resolutions for
# portable devices
device_resolution_info() {
	case "$1" in
		f9|f9hq)			green "-> Valid Flash Player 9 resolutions: unrestricted, up to 1080p (1920x1080)" ;;
		ipc|ipchq)			green "-> Valid iPod Classic resolutions: 320x240" ;;
		ip|iphq)			green "-> Valid iPod resolutions: 320x240|480x320|640x480" ;;
		iph|iphhq)			green "-> Valid iPhone resolutions: 320x240|640x480" ;;
		atv|atvhq)			green "-> Valid AppleTV resolutions: unrestricted, up to 720p (1280x720)" ;;
		ar|arhq)			green "-> Valid Archos 605 resolutions: up to 720x576" ;;
		bb|bbhq)			green "-> Valid Blackberry 9000 resolutions: 320x240|480x320|640x480" ;;
		nks60|nks60hq)			green "-> Valid Nokia S60 resolutions: 320x240|352x416" ;;
		psp|psphq)			green "-> Valid Sony PSP resolutions: 320x240|368x208|352x480|480x272|720x480" ;;
		ps3|ps3hq)			green "-> Valid Sony PS3 resolutions: unrestricted, up to 1080p (1920x1080)" ;;
		mz|mzhq)			green "-> Valid MS Zune resolutions: 320x240|720x480|720x576" ;;
		mx|mxhq)			green "-> Valid XBOX 360 resolutions: unrestricted, up to 1080p (1920x1080)" ;;
		bd40|bdhq40|bd41|bdhq41)	green "-> Valid Blu-ray resolutions: 720i/p (1280x720) and 1080i/p (1920x1080)" ;;
	esac
}

# Get resolution from the source and ask
# user if he wants to keep it. If cropping
# was used, then default resolution value
# will be that of the visible area left
# over after the cropping. If no cropping
# was used, then default resolution value
# will be the original one from the source

echo ""
if [ ! -z "$cropfilter" ]; then
	green "-> Detecting cropped resolution..."
	GETRES=$(echo $cropfilter | sed -e 's/crop=//' -e 's/,//' | tr ':' ' ' | awk '{print $1,$2}' | sed 's/ /x/')
	if [ ! -z "$GETRES" ]; then
		green "-> Resolution after cropping is: $GETRES"
		device_resolution_info $3
	else
		echo ""
		green "-> Failed to detect cropped resolution!"
		green "-> You have to provide it yourself!"
		device_resolution_info $3
		GETRES="??"
	fi
else
	green "-> Detecting original resolution..."
	$MPLAYER "$sourcetype" $device $vid -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > $CONFIGDIR/resolution
	GETRES=$(grep "^VIDEO:" $CONFIGDIR/resolution | tail -1 | awk '{print $3}')
	rm -f $CONFIGDIR/resolution
	if [ ! -z "$GETRES" ]; then
		green "-> Original resolution is: $GETRES"
		device_resolution_info $3
	else
		echo ""
		green "-> Failed to detect original resolution!"
		green "-> You have to provide it yourself!"
		device_resolution_info $3
		GETRES="??"
	fi
fi
echo ""
printf "Specify the desired Resolution [default is $GETRES]: "
read vres
if [ -z "$vres" -a "$GETRES" = "??" ]; then
	error "-> You have to specify the resolution!"
	rmconf
fi

# Bypass the scaling stuff if user
# decides to keep the original
# resolution of the source
case "$vres" in
	$GETRES|"")
	scale=
	sws=
	isws=
	swsparam=
	;;
	*)
	scale="scale=$(echo $vres | tr '[:alpha:]' ':')"
	# Interlacing parameters for the scale filter.
	# The first conditional sets the SWS parameters
	# to progressive if the user is interlacing
	# progressive content with the 'tinterlace' filter
	# and if the 'telecine' filter is not being used.
	# As this filter comes *after* the 'scale' filter,
	# there is no need to enable interlaced mode in
	# the SWS scaler during the resizing process.
	# The second conditional sets the SWS to interlaced
	# mode if the user is not using the 'tinterlace'
	# filter but does want to preserve the interlacing
	# of his content and if the 'telecine' filter is not
	# used. The third conditional sets the SWS parameters
	# to progressive if the user is not interlacing the
	# content with 'tinterlace' but is using the 'telecine'
	# filter. As is the case with the first conditional,
	# the 'telecine' filter also comes after the scaler
	# so again there's no need to enable interlaced
	# mode in the scaler. The last conditional sets the
	# SWS parameters to progressive mode if the content
	# is not interlaced or if it is, but the user is
	# deinterlacing it with one of the filters.
	
	if [ "$interlaced" = ":interlaced" -a ! -z "$intfilter" -a -z "$telecinefilter" ]; then
		isws=":0:0"
	elif [ "$interlaced" = ":interlaced" -a -z "$intfilter" -a -z "$telecinefilter" ]; then
		isws=":1:0"
	elif [ "$interlaced" = ":interlaced" -a -z "$intfilter" -a ! -z "$telecinefilter" ]; then
		isws=":0:0"
	elif [ "$interlaced" = ":nointerlaced" ]; then
		isws=":0:0"
	fi
	echo ""
	brown "Available Software Scalers"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 --> Fast Bilinear"
	echo "1 --> Bilinear"
	echo "2 --> Bicubic"
	echo "3 --> Experimental"
	echo "4 --> Nearest Neighbor/Point"
	echo "5 --> Area Averaging"
	echo "6 --> Luma Bicubic/Chroma Bilinear"
	echo "7 --> Gaussian"
	echo "8 --> Sinc"
	echo "9 --> Lanczos"
	echo "10 -> Natural Bicubic Spline"
	echo ""
	# Check if width & height are divisible
	# by 16 and if not display a warning
	WMOD16=$(echo "scale=3; $(echo $scale | sed 's/scale=//' | awk -F: '{print $1}')/16" | $BC -l | awk -F. '{print $2}')
	HMOD16=$(echo "scale=3; $(echo $scale | sed 's/scale=//' | awk -F: '{print $2}')/16" | $BC -l | awk -F. '{print $2}')
	if [ "$WMOD16" != "000" -o "$HMOD16" != "000" ]; then
		green "-> Warning: width and/or height not divisible by 16!"
		green "-> Compression will suffer!"
		echo ""
	fi
	printf "Select a Software Scaler [default is 10]: "
	read softscale
	if [ -z "$softscale" ]; then
		sws="-sws 10"
	else
		sws="-sws $softscale"
	fi
	# software scaler tuning, only supported
	# by bicubic, bicubic spline, gaussian
	# and lanczos scalers
	case $(echo "$sws" | awk '{print $2}') in
		2|10)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			brown "Software Scaler Parameters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "Here you can tune some parameters of"
			echo "the Bicubic/Natural Bicubic Spline"
			echo "software scalers. The first value"
			echo "represents the amount of blurring while"
			echo "the second value represents the amount"
			echo "of ringing. The higher the values, the"
			echo "more blurring/ringing you'll get."
			echo ""
			echo "Below are some frequently used settings"
			echo "Format is as follows: blurring:ringing"
			echo ""
			echo "0 -> 0.00:0.60 -> Default"
			echo "1 -> 0.00:0.75 -> VirtualDub's \"Precise Bicubic\""
			echo "2 -> 0.00:0.50 -> Catmull-Rom Spline"
			echo "3 -> 0.33:0.33 -> Mitchell-Netravali Spline"
			echo "4 -> 1.00:0.00 -> Cubic B-Spline"
			echo "5 -> User defined"
			echo "6 -> Skip parameter settings"
			echo ""
			printf "Select the Software Scaler Parameters [default is 0]: "
			read ssparam
			case "$ssparam" in
				0|"") swsparam=":0.00:0.60" ;;
				1) swsparam=":0.00:0.75" ;;
				2) swsparam=":0.00:0.50" ;;
				3) swsparam=":0.33:0.33" ;;
				4) swsparam=":1.00:0.00" ;;
				5)
				printf "Specify the Software Scaler Parameters [default is 0.00:0.60]: "
				read ssp
				if [ -z "$ssp" ]; then
					swsparam=":0.00:0.60"
				else
					swsparam=":$ssp"
				fi
				;;
				6) false ;;
				*)
				error "-> Unknown software scaler parameters option: '$ssparam'"
				rmconf
				;;
			esac
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			swsparam=
		fi
		;;
		7)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			brown "Software Scaler Parameters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "Here you can tune the sharpness of the"
			echo "Gaussian software scaler. Values are"
			echo "between 0 and 100. The higher the value"
			echo "the sharper the image will be"
			echo ""
			printf "Specify the Software Scaler Parameter [default is 0]: "
			read ssparam
			if [ -z "$ssparam" ]; then
				swsparam=
			else
				swsparam=":$ssparam"
			fi
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			swsparam=
		fi
		;;
		9)
		printf "Would you like to tune the Software Scaler? [y/n]: "
		read sstune
		if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
			echo ""
			brown "Software Scaler Parameters"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "Here you can tune the filter length of"
			echo "the Lanczos software scaler. Values are"
			echo "between 1 and 10. The higher the value"
			echo "the sharper the image will be"
			echo ""
			printf "Specify the Software Scaler Parameter [default is 1]: "
			read ssparam
			if [ -z "$ssparam" ]; then
				swsparam=
			else
				swsparam=":$ssparam"
			fi
		elif [ "$sstune" = "n" -o "$sstune" = "N" -o -z "$sstune" ]; then
			swsparam=
		fi
		;;
		*)
		swsparam=
		;;
	esac
	;;
esac

# Do a colorspace conversion?
# Don't ask for this when using
# the portable device presets
case "$3" in
	bd40|bdhq40|bd41|bdhq41|ar|arhq|bb|bbhq|nks60|nks60hq|ipc|ipchq|ip|iphq|iph|iphhq|psp|psphq|mz|mzhq)
	colorspacefilter=
	;;
	*)
	if [ ! -z "$scale" ]; then
		if [ -z "$fpsfilter" -a -z "$intfilter" -a -z "$telecinefilter" -a "$interlaced" = ":nointerlaced" ]; then
			video_colorspace_func
		else
			colorspacefilter=
		fi
	else
		colorspacefilter=
	fi
	;;
esac

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

##############################################
############## H.264 Settings ################
##############################################

echo ""
brown "+=============================+"
brown "| H.264 Encoder Configuration |"
brown "+=============================+"
echo ""

# Skip bitrate/quant settings if
# user chooses the NLQ preset
if [ "$3" = "nlq" ]; then
	false
else
	case "$1" in
		-[1-3]p)
		printf "Specify the desired Video Bitrate in kbps [default is 1000]: "
		read vbitrate
		if [ -z "$vbitrate" ]; then
			bitrate="bitrate=1000"
		else
			bitrate="bitrate=$vbitrate"
		fi
		# Check to see if we're not overflowing
		# the maximum allowed bitrate by some
		# devices
		case "$3" in
			bd40)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 20000 ]; then
				error "-> Blu-ray video bitrate may not exceed 20000 kbps!"
				rmconf
			fi
			;;
			bdhq40)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 25000 ]; then
				error "-> Blu-ray video bitrate may not exceed 25000 kbps!"
				rmconf
			fi
			;;
			bd41|bdhq41)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 30000 ]; then
				error "-> Blu-ray video bitrate may not exceed 30000 kbps!"
				rmconf
			fi
			;;
			ipc|ipchq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 768 ]; then
				echo ""
				green "-> iPod Classic bitrate may not exceed 768 kbps!"
				green "-> Falling back to maximum allowed bitrate!"
				bitrate="bitrate=768"
			fi
			;;
			ip|iphq|mz|mzhq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 2500 ]; then
				error "-> iPod/Zune video bitrate may not exceed 2500 kbps!"
				rmconf
			fi
			;;
			iph|iphhq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 1500 ]; then
				error "-> iPhone video bitrate may not exceed 1500 kbps!"
				rmconf
			fi
			;;
			atv|atvhq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 12000 ]; then
				error "-> AppleTV video bitrate may not exceed 12000 kbps!"
				rmconf
			fi
			;;
			ar|arhq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 5000 ]; then
				error "-> Archos 605 video bitrate may not exceed 5000 kbps!"
				rmconf
			fi
			;;
			bb|bbhq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 1500 ]; then
				error "-> Blackberry 9000 video bitrate may not exceed 1500 kbps!"
				rmconf
			fi
			;;
			nks60|nks60hq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 384 ]; then
				echo ""
				green "-> Nokia S60 video bitrate may not exceed 384 kbps!"
				green "-> Falling back to maximum allowed bitrate!"
				bitrate="bitrate=384"
			fi
			;;
			psp|psphq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 4000 ]; then
				error "-> PSP video bitrate may not exceed 4000 kbps!"
				rmconf
			fi
			;;
			ps3|ps3hq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 20000 ]; then
				error "-> PS3 video bitrate may not exceed 20000 kbps!"
				rmconf
			fi
			;;
			mx|mxhq)
			if [ $(echo $bitrate | awk -F= '{print $2}') -gt 20000 ]; then
				error "-> XBOX 360 video bitrate may not exceed 20000 kbps!"
				rmconf
			fi
			;;
		esac
		bits_per_pixel_func
		bits_per_block_func
		;;
		-fq)
		# The H.264 quantization parameter
		# is on a logarithmic scale so a
		# quantizer of 18 equals a quantizer
		# of 2 in MPEG-4 Part 2 (Xvid, DivX, etc...)
		printf "Which fixed-quant mode to use? [QP/CRF - default is CRF]: "
		read fqmode
		case "$fqmode" in
			QP|qp)
			printf "Specify the desired Quantizer [1.0-51.0 - default is 19.0]: "
			read quant
			if [ -z "$quant" ]; then
				bitrate="qp=19"
			else
				bitrate="qp=$quant"
			fi
			;;
			CRF|crf|"")
			printf "Specify the desired Quantizer [1.0-51.0 - default is 19.0]: "
			read quant
			if [ -z "$quant" ]; then
				bitrate="crf=19"
			else
				bitrate="crf=$quant"
			fi
			;;
			*)
			error "-> Unknown fixed-quant mode: '$fqmode'"
			rmconf
			;;
		esac
		echo ""
		;;
	esac
fi

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

# Set min/max keyframes according
# to chosen/detected FPS value

case "$GETFPS" in
	5.000|5.00)			keyint=":keyint=50" ;;
	10.000|10.00)			keyint=":keyint=100" ;;
	12.000|12.00)			keyint=":keyint=120" ;;
	15.000|15.00)			keyint=":keyint=150" ;;
	15.98[4-5]|15.98)		keyint=":keyint=160" ;;
	17.982|17.98)			keyint=":keyint=180" ;;
	25.000|25.00)			keyint=":keyint=250" ;;
	50.000|50.00)			keyint=":keyint=500" ;;
	100.000|100.00)			keyint=":keyint=1000" ;;
	23.976|24.000|23.97|24.00)	keyint=":keyint=240" ;;
	29.970|29.97|30.000|30.00)	keyint=":keyint=300" ;;
	59.940|59.94|60.000|60.00)	keyint=":keyint=600" ;;
	119.880|119.88)			keyint=":keyint=1200" ;;
	*|"")				keyint=":keyint=250" ;;
esac
# Overwrite the above if the user has
# chosen to set the fps manually or
# has chosen to do an ivtc/3:2 pulldown
# or if he wants to interlace his
# progressive content during the encoding
# or deinterlace it with a frame doubling
# filter.
if [ ! -z "$ofps" ]; then
	if [ ! -z "$(echo $ofps | grep '/')" ]; then
		keyint=":keyint=$(($(echo $ofps | awk '{print $2}')+1))0"
	else
		keyint=":keyint=$(echo $ofps | awk '{print $2}')0"
	fi
fi
keyint_min=":keyint_min=$(($(echo $keyint | awk -F= '{print $2}')/10))"

case "$1" in
	-[2-3]p)
	turbo=":turbo=2"
	;;
	-1p|-fq)
	turbo=
	;;
esac

display_quality_preset_func $3 $4
case "$3" in
	cp)
	# Load a custom preset and take care of
	# some of the options which are not
	# supported by all encoding modes.
	# We do this by resetting the values
	. "$4"
	case "$1" in
		-fq)
		turbo=
		qp_min=
		qp_max=
		qp_step=
		qcomp=
		ratetol=
		vbv_maxrate=
		vbv_bufsize=
		vbv_init=
		;;
		-1p)
		turbo=
		cplx_blur=
		qblur=
		;;
	esac
	;;
	ulq)
	# Ultra Low Quality
	frameref=":frameref=0"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	me=":me=dia"
	me_range=
	subq=":subq=1"
	chroma_me=":nochroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	deblock=":nodeblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=none"
	fast_pskip=":fast_pskip"
	dct_decimate=":dct_decimate"
	level_idc=":level_idc=41"
	;;
	elq)
	# Extreme Low Quality
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	me=":me=dia"
	me_range=
	subq=":subq=2"
	chroma_me=":nochroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	deblock=":nodeblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=none"
	fast_pskip=":fast_pskip"
	dct_decimate=":dct_decimate"
	level_idc=":level_idc=41"
	;;
	vlq)
	# Very Low Quality
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=4"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	me=":me=dia"
	me_range=
	subq=":subq=3"
	chroma_me=":nochroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	level_idc=":level_idc=41"
	;;
	lq)
	# Low Quality
	frameref=":frameref=2"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=6"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=spatial"
	me=":me=dia"
	me_range=
	subq=":subq=4"
	chroma_me=":nochroma_me"
	trellis=":trellis=0"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	level_idc=":level_idc=41"
	;;
	mq)
	# Medium Quality
	frameref=":frameref=2"
	mixed_refs=":mixed_refs"
	bframes=":bframes=8"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=spatial"
	me=":me=hex"
	me_range=
	subq=":subq=4"
	chroma_me=":nochroma_me"
	trellis=":trellis=0"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	level_idc=":level_idc=41"
	;;
	nq)
	# Normal Quality
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=10"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=spatial"
	me=":me=hex"
	me_range=
	subq=":subq=5"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	hq)
	# High Quality - from here till IHQ
	# it's High profile, baby :D
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=14"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=16"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	vhq)
	# Very High Quality
	frameref=":frameref=4"
	mixed_refs=":mixed_refs"
	bframes=":bframes=16"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	ehq)
	# Extreme High Quality
	frameref=":frameref=5"
	mixed_refs=":mixed_refs"
	bframes=":bframes=16"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=32"
	subq=":subq=8"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	uhq)
	# Ultra High Quality
	frameref=":frameref=6"
	mixed_refs=":mixed_refs"
	bframes=":bframes=16"
	b_adapt=":b_adapt=2"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=esa"
	me_range=":me_range=48"
	subq=":subq=9"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	ihq)
	# Insane High Quality
	frameref=":frameref=8"
	mixed_refs=":mixed_refs"
	bframes=":bframes=16"
	b_adapt=":b_adapt=2"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=tesa"
	me_range=":me_range=64"
	subq=":subq=9"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	nlq)
	# Near Lossless Quality
	bitrate="crf=18"
	frameref=":frameref=2"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	subq=":subq=5"
	me=":me=dia"
	direct_pred=":direct_pred=spatial"
	partitions=":partitions=p8x8,b8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":fast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	ani)
	# Anime
	frameref=":frameref=8"
	mixed_refs=":mixed_refs"
	bframes=":bframes=16"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=auto"
	me=":me=hex"
	me_range=":me_range=16"
	subq=":subq=6"
	psy_rd=":psy_rd=0.0,0.0"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	anihq)
	# Anime High-Quality
	frameref=":frameref=10"
	mixed_refs=":mixed_refs"
	bframes=":bframes=16"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.0,0.0"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	f9)
	# Flash Player 9
	frameref=":frameref=2"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=spatial"
	me=":me=hex"
	me_range=":me_range=16"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	f9hq)
	# Flash Player 9 HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=6"
	b_adapt=":b_adapt=1"
	b_pyramid=":b_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	qt)
	# QuickTime
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=hex"
	me_range=":me_range=16"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	qthq)
	# QuickTime HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	;;
	bd40)
	# Blu-ray (Main@L4.0)
	# For strict compliancy with BD hardware players
	# we have to use access unit delimiters, NAL HRD
	# signaling and one second keyframe interval
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=hex"
	me_range=":me_range=16"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=40"
	vbv_maxrate=":vbv_maxrate=20000"
	vbv_bufsize=":vbv_bufsize=20000"
	keyint=":keyint=$(($(echo $keyint | sed 's/:keyint=//')/10))"
	keyint_min=":keyint_min=1"
	nal_hrd=":nal_hrd"
	aud=":aud"
	;;
	bdhq40)
	# Blu-ray HQ (High@L4.0)
	# maxrate set to 25000 (max by Level)
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=40"
	vbv_maxrate=":vbv_maxrate=25000"
	vbv_bufsize=":vbv_bufsize=20000"
	keyint=":keyint=$(($(echo $keyint | sed 's/:keyint=//')/10))"
	keyint_min=":keyint_min=1"
	nal_hrd=":nal_hrd"
	aud=":aud"
	;;
	bd41)
	# Blu-ray (Main@L4.1)
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=hex"
	me_range=":me_range=16"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,b8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	vbv_maxrate=":vbv_maxrate=30000"
	vbv_bufsize=":vbv_bufsize=30000"
	keyint=":keyint=$(($(echo $keyint | sed 's/:keyint=//')/10))"
	keyint_min=":keyint_min=1"
	nal_hrd=":nal_hrd"
	aud=":aud"
	;;
	bdhq41)
	# Blu-ray HQ (High@L4.1)
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	a8x8dct=":8x8dct"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	level_idc=":level_idc=41"
	vbv_maxrate=":vbv_maxrate=30000"
	vbv_bufsize=":vbv_bufsize=30000"
	keyint=":keyint=$(($(echo $keyint | sed 's/:keyint=//')/10))"
	keyint_min=":keyint_min=1"
	nal_hrd=":nal_hrd"
	aud=":aud"
	;;
	sdb|hdb)
	# Stand-alone HW players SD/HD (Baseline)
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	deblock=":deblock"
	a8x8dct=":no8x8dct"
	partitions=":partitions=p8x8,i4x4"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	aud=":aud"
	case "$3" in
		sdb)
		level_idc=":level_idc=30"
		vbv_maxrate=":vbv_maxrate=10000"
		vbv_bufsize=":vbv_bufsize=5000"
		;;
		hdb)
		level_idc=":level_idc=40"
		vbv_maxrate=":vbv_maxrate=20000"
		vbv_bufsize=":vbv_bufsize=14475"
		;;
	esac
	;;
	sdm|sdh|hdm|hdh)
	# Stand-alone HW players SD/HD (Main/High)
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	me=":me=umh"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	deblock=":deblock"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	aud=":aud"
	case "$3" in
		sdm)
		a8x8dct=":no8x8dct"
		partitions=":partitions=p8x8,b8x8,i4x4"
		level_idc=":level_idc=30"
		vbv_maxrate=":vbv_maxrate=10000"
		vbv_bufsize=":vbv_bufsize=5000"
		;;
		sdh)
		a8x8dct=":8x8dct"
		partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
		level_idc=":level_idc=30"
		vbv_maxrate=":vbv_maxrate=12500"
		vbv_bufsize=":vbv_bufsize=5000"
		;;
		hdm)
		a8x8dct=":no8x8dct"
		partitions=":partitions=p8x8,b8x8,i4x4"
		level_idc=":level_idc=40"
		vbv_maxrate=":vbv_maxrate=20000"
		vbv_bufsize=":vbv_bufsize=14475"
		;;
		hdh)
		a8x8dct=":8x8dct"
		partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
		level_idc=":level_idc=40"
		vbv_maxrate=":vbv_maxrate=25000"
		vbv_bufsize=":vbv_bufsize=14475"
		;;
	esac
	;;
	ipc)
	# iPod Classic
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=hex"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":fast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=13"
	vbv_maxrate=":vbv_maxrate=768"
	vbv_bufsize=":vbv_bufsize=500"
	;;
	ipchq)
	# iPod Classic HQ
	display_quality_preset_func $3
	frameref=":frameref=3"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=umh"
	me_range=":me_range=24"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=13"
	vbv_maxrate=":vbv_maxrate=768"
	vbv_bufsize=":vbv_bufsize=500"
	;;
	ip|iph)
	# iPod/iPhone
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=hex"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":fast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=30"
	case "$3" in
		ip)
		vbv_maxrate=":vbv_maxrate=2500"
		vbv_bufsize=":vbv_bufsize=2000"
		;;
		iph)
		vbv_maxrate=":vbv_maxrate=1500"
		vbv_bufsize=":vbv_bufsize=1000"
		;;
	esac
	;;
	iphq|iphhq)
	# iPod/iPhone HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=umh"
	me_range=":me_range=24"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=30"
	case "$3" in
		iphq)
		vbv_maxrate=":vbv_maxrate=2500"
		vbv_bufsize=":vbv_bufsize=2000"
		;;
		iphhq)
		vbv_maxrate=":vbv_maxrate=1500"
		vbv_bufsize=":vbv_bufsize=1000"
		;;
	esac
	;;
	atv)
	# AppleTV
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=2"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=hex"
	me_range=
	partitions=":partitions=p8x8,b8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=30"
	vbv_maxrate=":vbv_maxrate=12000"
	vbv_bufsize=":vbv_bufsize=5000"
	;;
	atvhq)
	# AppleTV HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	direct_pred=":direct_pred=auto"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=umh"
	me_range=":me_range=24"
	partitions=":partitions=p8x8,b8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=30"
	vbv_maxrate=":vbv_maxrate=12000"
	vbv_bufsize=":vbv_bufsize=5000"
	;;
	ar)
	# Archos 605
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=hex"
	me_range=
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=5000"
	vbv_bufsize=":vbv_bufsize=3000"
	level_idc=":level_idc=30"
	;;
	arhq)
	# Archos 605 HQ
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=8"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=umh"
	me_range=":me_range=24"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=5000"
	vbv_bufsize=":vbv_bufsize=3000"
	level_idc=":level_idc=30"
	;;
	bb)
	# Blackberry 9000
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=hex"
	me_range=
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=1500"
	vbv_bufsize=":vbv_bufsize=1000"
	level_idc=":level_idc=30"
	;;
	bbhq)
	# Blackberry 9000 HQ
	frameref=":frameref=2"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=8"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=umh"
	me_range=":me_range=24"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=1500"
	vbv_bufsize=":vbv_bufsize=1000"
	level_idc=":level_idc=30"
	;;
	nks60)
	# Nokia S60
	frameref=":frameref=2"
	mixed_refs=":mixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=hex"
	me_range=
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=384"
	vbv_bufsize=":vbv_bufsize=900"
	level_idc=":level_idc=12"
	;;
	nks60hq)
	# Nokia S60 HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=umh"
	me_range=":me_range=24"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=384"
	vbv_bufsize=":vbv_bufsize=900"
	level_idc=":level_idc=12"
	;;
	psp)
	# PSP
	frameref=":frameref=2"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	me=":me=hex"
	direct_pred=":direct_pred=spatial"
	partitions=":partitions=p8x8,b8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":fast_pskip"
	dct_decimate=":nodct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=4000"
	vbv_bufsize=":vbv_bufsize=2500"
	level_idc=":level_idc=30"
	;;
	psphq)
	# PSP HQ
	frameref=":frameref=2"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	me_range=":me_range=24"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	me=":me=umh"
	direct_pred=":direct_pred=auto"
	partitions=":partitions=p8x8,b8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=4000"
	vbv_bufsize=":vbv_bufsize=2500"
	level_idc=":level_idc=30"
	;;
	ps3)
	# PS3
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	me=":me=hex"
	me_range=
	direct_pred=":direct_pred=spatial"
	partitions=":partitions=p8x8,b8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=41"
	vbv_maxrate=":vbv_maxrate=20000"
	vbv_bufsize=":vbv_bufsize=20000"
	aud=":aud"
	;;
	ps3hq)
	# PS3 HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	me_range=":me_range=24"
	me=":me=umh"
	direct_pred=":direct_pred=auto"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	a8x8dct=":8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=41"
	vbv_maxrate=":vbv_maxrate=20000"
	vbv_bufsize=":vbv_bufsize=20000"
	aud=":aud"
	;;
	mz)
	# Zune
	frameref=":frameref=1"
	mixed_refs=":nomixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=hex"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":fast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=2500"
	vbv_bufsize=":vbv_bufsize=2000"
	level_idc=":level_idc=30"
	;;
	mzhq)
	# Zune HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=0"
	b_adapt=":b_adapt=0"
	b_pyramid=":nob_pyramid"
	weight_b=":noweight_b"
	direct_pred=":direct_pred=none"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.0"
	me=":me=umh"
	me_range=":me_range=24"
	partitions=":partitions=p8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=0"
	cabac=":nocabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":dct_decimate"
	#global_header=":global_header"
	vbv_maxrate=":vbv_maxrate=2500"
	vbv_bufsize=":vbv_bufsize=2000"
	level_idc=":level_idc=30"
	;;
	mx)
	# XBOX 360
	frameref=":frameref=2"
	mixed_refs=":mixed_refs"
	bframes=":bframes=3"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	subq=":subq=6"
	psy_rd=":psy_rd=0.5,0.3"
	me_range=
	me=":me=hex"
	direct_pred=":direct_pred=spatial"
	partitions=":partitions=p8x8,b8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	a8x8dct=":no8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=41"
	vbv_maxrate=":vbv_maxrate=20000"
	vbv_bufsize=":vbv_bufsize=20000"
	;;
	mxhq)
	# XBOX 360 HQ
	frameref=":frameref=3"
	mixed_refs=":mixed_refs"
	bframes=":bframes=6"
	b_adapt=":b_adapt=1"
	b_pyramid=":nob_pyramid"
	weight_b=":weight_b"
	subq=":subq=7"
	psy_rd=":psy_rd=0.5,0.3"
	me_range=":me_range=24"
	me=":me=umh"
	direct_pred=":direct_pred=auto"
	partitions=":partitions=p8x8,b8x8,i8x8,i4x4"
	deblock=":deblock"
	chroma_me=":chroma_me"
	trellis=":trellis=1"
	cabac=":cabac"
	a8x8dct=":8x8dct"
	fast_pskip=":nofast_pskip"
	dct_decimate=":nodct_decimate"
	#global_header=":global_header"
	level_idc=":level_idc=41"
	vbv_maxrate=":vbv_maxrate=20000"
	vbv_bufsize=":vbv_bufsize=20000"
	;;
esac
echo ""
# Custom matrices are only
# supported by presets which
# use High profile settings!
case "$3" in
	cp|ulq|elq|vlq|lq|mq|nq|nlq|f9|f9hq|qt|qthq|bd40|bdhq40|bd41|bdhq41|sdb|sdm|hdb|hdm|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq|mx|mxhq)
	false
	;;
	*)
	custom_matrix_func
	;;
esac

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


#################################################
############## Audio Functions ##################
#################################################

# Check availability of the
# selected audio codec in
# MEncoder
check_audio_codec_func() {
	case "$audiocodec" in
		ac3|AC3|flac|FLAC)
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'lavc')" ]; then
			error "-> MEncoder does not support the libavcodecs audio collection!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
		mp3|MP3)
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'mp3lame')" ]; then
			error "-> MEncoder does not support MP3 audio encoding!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
		aac|AAC|"")
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'faac')" ]; then
			error "-> MEncoder does not support AAC audio encoding!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
		neroaac|neroAAC)
		if [ ! -x "$NEROAACENC" ]; then
			error "-> 'neroAacEnc' is missing from your system!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
		aac+|AAC+)
		if [ ! -x "$AACPLUSENC" ]; then
			error "-> 'aacplusenc' is missing from your system!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
		vorbis|VORBIS)
		if [ ! -x "$OGGENC" ]; then
			error "-> 'oggenc' is missing from your system!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
		pcm|PCM)
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'pcm')" ]; then
			error "-> MEncoder does not support PCM audio encoding!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
		copy|COPY)
		if [ -z "$($MENCODER -oac help 2>/dev/null | awk '{print $1}' | grep 'copy')" ]; then
			error "-> MEncoder does not support audio stream copy!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmconf
		fi
		;;
	esac
}

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

# Volume normalizing.
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.
# Mutually 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
# neroAacEnc doesn't support
# multichannel audio!
audio_channels_func() {
	case "$audiocodec" in
		AC3|ac3|AAC|aac|neroAAC|neroaac|VORBIS|vorbis|FLAC|flac|PCM|pcm|"")
		printf "Would you like to use/have more than 2 Audio Channels? [y/n]: "
		read chan
		if [ "$chan" = "y" -o "$chan" = "Y" ]; then
			case "$audiocodec" in
				AC3|ac3)
				echo ""
				brown "AC3 Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> Dolby AC3 Stereo  (2 front)"
				echo "4 -> Dolby AC3 Quadro  (2 front + 2 rear)"
				echo "5 -> Dolby AC3 5.0     (2 front + 2 rear + 1 center)"
				echo "6 -> Dolby AC3 Digital (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				AAC|aac|neroAAC|neroaac|"")
				echo ""
				brown "AAC(+) Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> AAC(+) Stereo (2 front)"
				echo "4 -> AAC(+) Quadro (2 front + 2 rear)"
				echo "5 -> AAC(+) 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> AAC(+) 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				VORBIS|vorbis)
				echo ""
				brown "Vorbis Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> Vorbis Stereo (2 front)"
				echo "4 -> Vorbis Quadro (2 front + 2 rear)"
				echo "5 -> Vorbis 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> Vorbis 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				FLAC|flac)
				echo ""
				brown "FLAC Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> FLAC Stereo (2 front)"
				echo "4 -> FLAC Quadro (2 front + 2 rear)"
				echo "5 -> FLAC 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> FLAC 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
				PCM|pcm)
				echo ""
				brown "PCM Channels Configuration"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "2 -> PCM Stereo (2 front)"
				echo "4 -> PCM Quadro (2 front + 2 rear)"
				echo "5 -> PCM 5.0    (2 front + 2 rear + 1 center)"
				echo "6 -> PCM 5.1    (2 front + 2 rear + 1 center + LFE)"
				echo ""
				;;
			esac
			printf "How many channels to use/add? [default is 2]: "
			read chanuse
			if [ -z "$chanuse" ]; then
				channels=
			else
				channels="-channels $chanuse"
			fi
		elif [ "$chan" = "n" -o "$chan" = "N" -o -z "$chan" ]; then
			channels=
		fi
		;;
		COPY|copy)
		case "$source" in
			file|FILE|File)
			printf "How many channels to copy? [2/4/5/6 - default is 2]: "
			read chancopy
			if [ -z "$chancopy" ]; then
				channels="-channels 2"
			else
				channels="-channels $chancopy"
			fi
			;;
			dvd|DVD|Dvd)
			printf "How many channels to copy? [2/4/5/6 - default is 6]: "
			read chancopy
			if [ -z "$chancopy" ]; then
				channels="-channels 6"
			else
				channels="-channels $chancopy"
			fi
			;;
		esac
		;;
	esac
}

#####################################################
############## Audio Configuration ##################
#####################################################

echo ""
brown "+=====================+"
brown "| Audio Configuration |"
brown "+=====================+"
echo ""
case "$source" in
	dir|DIR|Dir)
	false
	;;
	dvd|DVD|Dvd)
	green "-> Scanning for audio streams..."
	$MPLAYER $sourcetype $device -nosound -vo null -frames 1 -nocache 2>/dev/null > $CONFIGDIR/audiostreams
	STREAMS=$(grep "^audio stream" $CONFIGDIR/audiostreams)
	rm -f $CONFIGDIR/audiostreams
	echo ""
	if [ ! -z "$STREAMS" ]; then
		echo "$STREAMS" | sed -e 's/^audio/Audio/g' -e 's/format:/Format:/g' -e 's/language:/Language:/g' \
		-e 's/aid:/ID:/g' -e 's/ac3/AC3/g' -e 's/eac3/E-AC3/g' -e 's/dts/DTS/g' -e 's/lpcm/LPCM/g' -e 's/pcm/PCM/g'
	else
		green "-> Could not detect any audio streams!"
	fi
	echo ""
	printf "Specify the DVD Audio Stream ID [default is 128]: "
	read dac
	if [ ! -z "$(echo $dac | grep '[a-zA-Z]')" ]; then
		error "-> You have to specify the 'ID' number, not the language code!"
		rmconf
	fi
	if [ -z "$dac" ]; then
		aid="-aid 128"
	else
		aid="-aid $dac"
	fi
	;;
	file|FILE|File)
	# If input source contains more than
	# one audio stream (like MPEG TS or
	# Matroska files), then offer the
	# user a option to select the channel
	# he/she wants. If input source has
	# only 1 or none at all audio streams
	# then skip the channel selection
	printf "Scan for multiple audio streams? [y/n]: "
	read multiaudio
	if [ "$multiaudio" = "y" -o "$multiaudio" = "Y" ]; then
		echo ""
		green "-> Scanning for audio streams..."
		$MPLAYER "$sourcetype" -nosound -vo null -identify -frames 1 -nocache 2>/dev/null > $CONFIGDIR/audiostreams
		if [ $(grep "^ID_AUDIO_ID" $CONFIGDIR/audiostreams | wc -l) -le 1 ]; then
			aid=
			green "-> Zero or one audio stream found"
			green "-> Skipping stream selection"
		else
			echo ""
			for i in $(grep "^ID_AUDIO_ID" $CONFIGDIR/audiostreams); do
				echo "$(echo "Audio stream: $(echo $i | awk -F= '{print $2}')")"
			done
			echo ""
			AID=$(grep "^ID_AUDIO_ID" $CONFIGDIR/audiostreams | awk -F= '{print $2}')
			printf "Specify the Audio Stream number [default is $(echo $AID | awk '{print $1}')]: "
			read dac
			if [ -z "$dac" ]; then
				aid="-aid $(echo $AID | awk '{print $1}')"
			else
				aid="-aid $dac"
			fi
		fi
		rm -f $CONFIGDIR/audiostreams
	elif [ "$multiaudio" = "n" -o "$multiaudio" = "N" -o -z "$multiaudio" ]; then
		aid=
	fi
	;;
esac

###############################################
########## Audio codec functions ##############
###############################################

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

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

aac_audio_func() {
	case "$1" in
		f9|f9hq|qt|qthq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq)
		printf "Specify the AAC Average Audio Bitrate [default is 128]: "
		read abitrate
		if [ -z "$abitrate" ]; then
			br=":br=128"
		else
			br=":br=$abitrate"
		fi
		case "$1" in
			ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|bb|bbhq|nks60|nks60hq|psp|psphq)
			# Restrict audio bitrate for devices
			# with a maximum allowed bitrate
			if [ $(echo $br | awk -F= '{print $2}') -gt 160 ]; then
				echo ""
				green "-> Audio bitrate for this portable device may not exceed 160 kbps!"
				green "-> Falling back to 128 kbps!"
				echo ""
				br=":br=128"
			fi
			;;
		esac
		;;
		*)
		printf "Specify the AAC Average Audio Bitrate [default is 110]: "
		read abitrate
		if [ -z "$abitrate" ]; then
			br=":br=110"
		else
			br=":br=$abitrate"
		fi
		;;
	esac
	printf "Enable AAC Temporal Noise Shaping? [y/n]: "
	read tempns
	if [ "$tempns" = "y" -o "$tempns" = "Y" ]; then
		tns=":tns"
	elif [ "$tempns" = "n" -o "$tempns" = "N" -o -z "$tempns" ]; then
		tns=
	fi
	acodec="-oac faac -faacopts mpeg=4$br:object=2$tns"
	ac3drc=
}

neroaac_audio_func() {
	acodec="-oac pcm"
	case "$1" in
		qt|qthq|ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|bb|bbhq|nks60|nks60hq|psp|psphq|ps3|ps3hq|mz|mzhq|mx|mxhq)
		aacprof="-lc"
		printf "Specify the AAC Audio Bitrate in kbps [default is 128]: "
		read ab
		if [ -z "$ab" ]; then
			neroaacbr="-br 128000 $aacprof"
		else
			neroaacbr="-br ${ab}000 $aacprof"
		fi
		case "$1" in
			ipc|ipchq|ip|iphq|iph|iphhq|atv|atvhq|ar|arhq|bb|bbhq|nks60|nks60hq|psp|psphq)
			if [ $(echo $neroaacbr | awk '{print $2}') -gt 160000 ]; then
				echo ""
				green "-> Audio bitrate for this portable device may not exceed 160 kbps!"
				green "-> Falling back to 128 kbps!"
				echo ""
				neroaacbr="-br 128000 $aacprof"
			fi
			;;
		esac
		;;
		*)
		printf "Which AAC Profile to use? [LC/HE/HEv2 - default is HE]: "
		read aaclche
		case "$aaclche" in
			LC|lc) aacprof="-lc" ;;
			HE|he|"") aacprof="-he" ;;
			HEv2|hev2) aacprof="-hev2" ;;
			*)
			error "-> Unknown AAC profile!"
			error "-> Exiting in function: neroaac_audio_func()"
			rmconf
			;;
		esac
		printf "Specify the AAC Encoding Mode [ABR/CBR - default is ABR]: "
		read aacmode
		case "$aacmode" in
			a*|A*|"")
			printf "Specify the AAC Average Audio Bitrate in kbps [default is 100]: "
			read ab
			if [ -z "$ab" ]; then
				neroaacbr="-br 100000 $aacprof"
			else
				neroaacbr="-br ${ab}000 $aacprof"
			fi
			;;
			c*|C*)
			echo ""
			brown "AAC Audio Bitrates"
			brown "~~~~~~~~~~~~~~~~~~"
			echo "0 -> 32 kbps   7 --> 112 kbps"
			echo "1 -> 40 kbps   8 --> 128 kbps"
			echo "2 -> 48 kbps   9 --> 160 kbps"
			echo "3 -> 56 kbps   10 -> 192 kbps"
			echo "4 -> 64 kbps   11 -> 224 kbps"
			echo "5 -> 80 kbps   12 -> 256 kbps"
			echo "6 -> 96 kbps   13 -> 320 kbps"
			echo ""
			printf "Select the AAC Audio Bitrate [default is 7]: "
			read ab
			case "$ab" in
				0) neroaacbr="-cbr 32000 $aacprof" ;;
				1) neroaacbr="-cbr 40000 $aacprof" ;;
				2) neroaacbr="-cbr 48000 $aacprof" ;;
				3) neroaacbr="-cbr 56000 $aacprof" ;;
				4) neroaacbr="-cbr 64000 $aacprof" ;;
				5) neroaacbr="-cbr 80000 $aacprof" ;;
				6) neroaacbr="-cbr 96000 $aacprof" ;;
				7|"") neroaacbr="-cbr 112000 $aacprof" ;;
				8) neroaacbr="-cbr 128000 $aacprof" ;;
				9) neroaacbr="-cbr 160000 $aacprof" ;;
				10) neroaacbr="-cbr 192000 $aacprof" ;;
				11) neroaacbr="-cbr 224000 $aacprof" ;;
				12) neroaacbr="-cbr 256000 $aacprof" ;;
				13) neroaacbr="-cbr 320000 $aacprof" ;;
				*)
				error "-> Unknown option: '$ab'"
				error "-> Exiting in function: neroaac_audio_func()"
				rmconf
				;;
			esac
			;;
			*)
			error "-> Unknown option: '$aacmode'"
			error "-> Exiting in function: neroaac_audio_func()"
			rmconf
			;;
		esac
		;;
	esac
}

aacplus_audio_func() {
	acodec="-oac pcm"
	channels="-channels 2"
	printf "Specify the AAC+ Audio Bitrate in kbps [default is 55]: "
	read ab
	if [ -z "$ab" ]; then
		aacplusbr="55"
	else
		aacplusbr="$ab"
		if [[ $aacplusbr -ge 64 ]]; then
			echo ""
			green "-> Bitrates of 64 kbps and up are not supported!"
			green "-> Using default bitrate of 55 kbps"
			echo ""
			aacplusbr="55"
		elif [[ $aacplusbr -lt 48 ]]; then
			echo ""
			green "-> Bitrates below 48 kbps use Parametric Stereo"
			green "   which is not recommended!"
			green "-> Using default bitrate of 55 kbps"
			echo ""
			aacplusbr="55"
		fi
	fi
}

vorbis_audio_func() {
	acodec="-oac pcm"
	printf "Specify the Vorbis Audio Quality [-1-10 - default is 3]: "
	read ab
	if [ -z "$ab" ]; then
		vorbq="-q 3"
	else
		if [ ! -z "$(echo $ab | grep '\.')" ]; then
			echo ""
			green "-> Floating point values are not supported yet!"
			green "-> Using default value of 3"
			echo ""
			vorbq="-q 3"
		else
			vorbq="-q $ab"
		fi
	fi
}


# Call the audio functions above.
case "$3" in
	f9|f9hq)
	printf "Specify the Audio Codec [AAC/neroAAC/AAC+ - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func ;;
		aac+|AAC+) aacplus_audio_func ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=22050:0:2 -srate 22050"
	channels="-channels 2"
	;;
	qt|qthq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_resample_func
	audio_volnorm_func
	audio_volume_func
	channels="-channels 2"
	;;
	bd40|bdhq40|bd41|bdhq41)
	printf "Specify the Audio codec [AC3/COPY - default is AC3]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AC3|ac3|"")
		ac3_audio_func
		audio_channels_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		;;
		COPY|copy)
		acodec="-oac copy"
		audio_channels_func
		;;
		*)
		error "-> Unknown audio codec: '$audiocodec'"
		rmconf
		;;
	esac
	;;
	ipc|ipchq|ip|iphq|iph|iphhq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
	channels="-channels 2"
	;;
	atv|atvhq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
	channels="-channels 2"
	;;
	ar|arhq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
	channels="-channels 2"
	;;
	bb|bbhq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
	channels="-channels 2"
	;;
	nks60|nks60hq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=44100:0:2 -srate 44100"
	channels="-channels 2"
	;;
	psp|psphq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
	channels="-channels 2"
	;;
	ps3|ps3hq)
	printf "Specify the Audio Codec [AAC/neroAAC/COPY - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"")
		aac_audio_func $3
		audio_channels_func
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
		;;
		neroAAC|neroaac)
		neroaac_audio_func $3
		audio_channels_func
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
		;;
		copy|COPY)
		acodec="-oac copy"
		audio_channels_func
		;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	;;
	mz|mzhq)
	printf "Specify the Audio Codec [MP3/AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		MP3|mp3)
		mp3_audio_func
		afilters="resample=48000:0:2 -srate 48000"
		channels="-channels 2"
		;;
		AAC|aac|"")
		aac_audio_func $3
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
		channels="-channels 2"
		;;
		neroAAC|neroaac)
		neroaac_audio_func $3
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
		channels="-channels 2"
		;;
	esac
	;;
	mx|mxhq)
	printf "Specify the Audio Codec [AAC/neroAAC - default is AAC]: "
	read audiocodec
	check_audio_codec_func
	case "$audiocodec" in
		AAC|aac|"") aac_audio_func $3 ;;
		neroAAC|neroaac) neroaac_audio_func $3 ;;
		*) error "-> Unknown audio codec: '$audiocodec'"; rmconf ;;
	esac
	audio_volnorm_func
	audio_volume_func
	afilters="$volnorm$volume,resample=48000:0:2 -srate 48000"
	channels="-channels 2"
	;;
	*|"")
	echo ""
	brown "Available Audio Codecs"
	brown "~~~~~~~~~~~~~~~~~~~~~~"
	echo "MP3 -----> Container support: AVI, MKV, MP4, OGM, TS"
	echo "AC3 -----> Container support: AVI, MKV, OGM, TS"
	echo "AAC -----> Container support: AVI, MKV, MP4, TS"
	echo "AAC+ ----> Container support: MP4, MKV"
	echo "neroAAC -> Container support: MP4, MKV"
	echo "VORBIS --> Container support: MP4, MKV, OGM"
	echo "FLAC ----> Container support: AVI"
	echo "PCM -----> Container support: AVI, MKV, OGM"
	echo "COPY ----> Container support: Depends on audio codec"
	echo "NOSOUND -> Container support: AVI, MKV, MP4, OGM, TS"
	echo ""
	printf "Select the Audio Codec [default is AAC]: "
	read audiocodec
	case "$audiocodec" in
		MP3|mp3)
		check_audio_codec_func
		mp3_audio_func
		audio_resample_func
		afilters="$resample"
		;;
		AC3|ac3)
		check_audio_codec_func
		ac3_audio_func
		audio_channels_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume$resample"
		;;
		AAC|aac|"")
		check_audio_codec_func
		aac_audio_func
		audio_channels_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume$resample"
		;;
		neroAAC|neroaac)
		check_audio_codec_func
		neroaac_audio_func
		audio_channels_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume$resample"
		;;
		aac+|AAC+)
		check_audio_codec_func
		aacplus_audio_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume$resample"
		;;
		VORBIS|vorbis)
		check_audio_codec_func
		vorbis_audio_func
		audio_channels_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		afilters="$volnorm$volume$resample"
		;;
		FLAC|flac)
		check_audio_codec_func
		audio_channels_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		acodec="-oac lavc -lavcopts acodec=flac"
		afilters="$volnorm$volume$resample"
		ac3drc=
		;;
		PCM|pcm)
		check_audio_codec_func
		audio_channels_func
		audio_resample_func
		audio_volnorm_func
		audio_volume_func
		acodec="-oac pcm"
		afilters="$volnorm$volume$resample"
		ac3drc=
		;;
		COPY|copy)
		check_audio_codec_func
		audio_channels_func
		acodec="-oac copy"
		afilters=
		ac3drc=
		;;
		NOSOUND|nosound)
		acodec="-nosound"
		aid=
		afilters=
		channels=
		ac3drc=
		;;
		*)
		error "-> Unknown audio codec: '$audiocodec'"
		rmconf
		;;
	esac
	;;
esac


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

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


case "$1" in
	-[1-3]p)
	case "$audiocodec" in
		MP3|mp3|AC3|ac3|AAC|aac|AAC+|aac+|neroAAC|neroaac|VORBIS|vorbis|PCM|pcm|COPY|copy|NOSOUND|nosound|"")
		printf "Would you like to set a target file size? [y/n]: "
		read calcvidbit
		if [ "$calcvidbit" = "y" -o "$calcvidbit" = "Y" ]; then
			echo ""
			brown "Video Bitrate Calculation/Target File Size"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "h264enc can calculate the video bitrate for you"
			echo "based on the video length, chosen audio bitrate and"
			echo "target file size. The only thing you have to provide"
			echo "here is the desired target size in Megabytes for the"
			echo "encode. After that, you can choose to keep the bitrate"
			echo "calculated by h264enc, or you can provide a new one."
			echo ""
			printf "Specify the desired Target File Size in Megabytes [default is 700]: "
			read tfsm
			if [ -z "$tfsm" ]; then
				TARGET_SIZE=700
			else
				TARGET_SIZE=$tfsm
			fi
			# Get the chosen audio bitrate
			case "$audiocodec" in
				AC3|ac3)
				AUDIO_BITRATE=$abitrate
				;;
				MP3|mp3)
				case "$mp3mode" in
					a*|A*|c*|C*|"")
					AUDIO_BITRATE=$(echo $abitrate | awk -F= '{print $2}')
					;;
					v*|V*)
					APPRO="~"
					# Use 10 kbps lesser compared
					# to the LAME specs
					case "$abitrate" in
						q=0) AUDIO_BITRATE="230" ;;
						q=1) AUDIO_BITRATE="200" ;;
						q=2) AUDIO_BITRATE="180" ;;
						q=3) AUDIO_BITRATE="165" ;;
						q=4) AUDIO_BITRATE="155" ;;
						q=5) AUDIO_BITRATE="120" ;;
						q=6) AUDIO_BITRATE="105" ;;
						q=7) AUDIO_BITRATE="90" ;;
						q=8) AUDIO_BITRATE="75" ;;
						q=9) AUDIO_BITRATE="54" ;;
					esac
					;;
				esac
				;;
				AAC|aac|"")
				APPRO="~"
				AUDIO_BITRATE=$(echo $br | awk -F= '{print $2}')
				;;
				AAC+|aac+)
				APPRO="~"
				AUDIO_BITRATE="$aacplusbr"
				;;
				neroAAC|neroaac)
				APPRO="~"
				AUDIO_BITRATE=$(($(echo $neroaacbr | awk '{print $2}')/1000))
				;;
				VORBIS|vorbis)
				APPRO="~"
				# Quality values -> bitrate mappings
				case "$(echo $vorbq | awk '{print $2}')" in
					-1) AUDIO_BITRATE="45" ;;
					0) AUDIO_BITRATE="64" ;;
					1) AUDIO_BITRATE="80" ;;
					2) AUDIO_BITRATE="96" ;;
					3) AUDIO_BITRATE="112" ;;
					4) AUDIO_BITRATE="128" ;;
					5) AUDIO_BITRATE="160" ;;
					6) AUDIO_BITRATE="192" ;;
					7) AUDIO_BITRATE="224" ;;
					8) AUDIO_BITRATE="256" ;;
					9) AUDIO_BITRATE="320" ;;
					10) AUDIO_BITRATE="500" ;;
				esac
				;;
				PCM|pcm)
				# Get channels info. Resampling is not
				# taken into account so we assume 48 kHz
				case "$(echo $channels | awk '{print $2}')" in
					2|""|*) AUDIO_BITRATE="1536" ;;
					4) AUDIO_BITRATE="3072" ;;
					5) AUDIO_BITRATE="3840" ;;
					6) AUDIO_BITRATE="4608" ;;
				esac
				;;
				COPY|copy)
				# Lets hope this works
				# for most sources
				$MPLAYER "$sourcetype" $device $aid -identify -vo null -frames 1 -nocache 2>/dev/null > $CONFIGDIR/audio_copy
				AUDIO_BITRATE=$(echo $(($(grep '^ID_AUDIO_BITRATE' $CONFIGDIR/audio_copy | tail -1 | awk -F= '{print $2}')/1000)) | awk -F. '{print $1}')
				rm -f $CONFIGDIR/audio_copy
				;;
			esac
			echo ""
			green "-> Detecting video length..."
			$MPLAYER "$sourcetype" $device $vid -identify -vo null -frames 1 -nosound -nocache 2>/dev/null > $CONFIGDIR/videoinfo
			VIDEO_LENGTH=$(grep "^ID_LENGTH" $CONFIGDIR/videoinfo | awk -F= '{print $2}')
			VFPS=$(grep '^ID_VIDEO_FPS' $CONFIGDIR/videoinfo | awk -F= '{print $2}')
			rm -f $CONFIGDIR/videoinfo
			if [ -z "$VIDEO_LENGTH" ]; then
				echo ""
				green "-> Could not detect the video length!"
				green "-> Will skip video bitrate calculation!"
				echo ""
			else
				case "$audiocodec" in
					nosound|NOSOUND)
					VBITRATE=$(echo "scale=0; $TARGET_SIZE * 1024 * 1024 / $VIDEO_LENGTH * 8 / 1000" | $BC -l)
					;;
					*|"")
					# Calculate audio filesize in MB
					AUDSIZE=$(echo "scale=3; $AUDIO_BITRATE * 1000 * $VIDEO_LENGTH / 8 / 1048576" | $BC -l)
					VBITRATE=$(echo "scale=0; ($TARGET_SIZE - $AUDSIZE) * 1024 * 1024 / $VIDEO_LENGTH * 8 / 1000" | $BC -l)
					;;
				esac
				bits_per_pixel_func
				bits_per_block_func
				green "-> Video length is $(echo "scale=2; $VIDEO_LENGTH / 60" | $BC -l) minutes or $VIDEO_LENGTH seconds"
				green "-> Number of frames: $(echo "scale=0; $VIDEO_LENGTH * $VFPS" | $BC -l)"
				case "$audiocodec" in
					nosound|NOSOUND)
					false
					;;
					*|"")
					green "-> Chosen/detected audio bitrate is $APPRO$AUDIO_BITRATE kbps"
					;;
				esac
				echo ""
				green "-> Estimated video bitrate for $TARGET_SIZE MB: $VBITRATE kbps"
				green "-> Bits Per Pixel value: $BPP bpp"
				green "-> Bits Per Block value: $BPB bpb"
				echo ""
				printf "Specify the new video bitrate in kbps [default is $VBITRATE]: "
				read new_vbitrate
				if [ -z "$new_vbitrate" ]; then
					bitrate="bitrate=$VBITRATE"
				else
					bitrate="bitrate=$new_vbitrate"
				fi
			fi
		fi
		;;
	esac
	;;
esac

###############################################################
################# MEncoder configuration ######################
###############################################################

# 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 correctly. 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 so that duplicate
# frames will never get interlaced. The (un)sharp mask /
# gaussian blur filter should come after the scale filter.
# The 'tfields' filter should come after the crop filter
# as it alters the resolution and MEncoder will error out
# with a "crop area outside of the original" message!
#
# Log file for 2- and 3-pass
PASSLOG="$CONFIGDIR/h264.log"

if [ ! -z "$(echo $deintfilter | grep '^tfields')" ]; then
	videofilters="-vf $(echo $ivtcfilter$cropfilter$deintfilter$fpsfilter$ild$deblockfilter$denoisefilter$ili$brightnessfilter$colorspacefilter,softskip,$scale$isws$swsparam$unsharpfilter,harddup$intfilter$telecinefilter | sed -e 's/^,//' -e 's/,,/,/g' -e 's/,$//')"
else
	videofilters="-vf $(echo $ivtcfilter$deintfilter$cropfilter$fpsfilter$ild$deblockfilter$denoisefilter$ili$brightnessfilter$colorspacefilter,softskip,$scale$isws$swsparam$unsharpfilter,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\" $device $vid $chapters $dvdangle $subtitle $vobsubout $fps $ofps $videofilters $field_dominance $aspect $sws $aid $audiofilters $channels $ac3drc $acodec \
		-ovc x264 -x264encopts $bitrate$me$me_range$dct_decimate$interlaced$a8x8dct$fast_pskip$trellis$scenecut$chroma_qp_offset$nr$ip_factor$pb_factor$qcomp$partitions$mixed_refs$global_header$qp_min$qp_max$qp_step$keyint$keyint_min$psy_rd$frameref$bframes$b_adapt$b_bias$b_pyramid$weight_b$direct_pred$subq$chroma_me$cabac$nal_hrd$aq_strength$aq_mode$deblock$stats$ratetol$vbv_maxrate$vbv_bufsize$vbv_init$cqm$deadzone_inter$deadzone_intra$aud$level_idc:threads=auto:ssim:psnr $quiet"
		;;
		-2p)
		# Pass one
		# do not use subs for first pass
		echo "$priority_level $MENCODER \"$sourcetype\" -o /dev/null $device $vid $chapters $dvdangle $fps $ofps $videofilters $field_dominance $aspect $sws $aid $audiofilters $channels $ac3drc $acodec \
		-ovc x264 -x264encopts pass=1:$bitrate$turbo$me$me_range$dct_decimate$interlaced$a8x8dct$fast_pskip$trellis$scenecut$chroma_qp_offset$nr$ip_factor$pb_factor$cplx_blur$qblur$qcomp$partitions$mixed_refs$global_header$qp_min$qp_max$qp_step$keyint$keyint_min$psy_rd$frameref$bframes$b_adapt$b_bias$b_pyramid$weight_b$direct_pred$subq$chroma_me$cabac$nal_hrd$aq_strength$aq_mode$deblock$stats$ratetol$vbv_maxrate$vbv_bufsize$vbv_init$cqm$deadzone_inter$deadzone_intra$aud$level_idc:threads=auto:ssim:psnr -passlogfile $PASSLOG $quiet"
		echo ""
		# Pass two
		echo "$priority_level $MENCODER \"$sourcetype\" -o \"$OUTPUT\" $device $vid $chapters $dvdangle $subtitle $vobsubout $fps $ofps $videofilters $field_dominance $aspect $sws $aid $audiofilters $channels $ac3drc $acodec \
		-ovc x264 -x264encopts pass=2:$bitrate$me$me_range$dct_decimate$interlaced$a8x8dct$fast_pskip$trellis$scenecut$chroma_qp_offset$nr$ip_factor$pb_factor$cplx_blur$qblur$qcomp$partitions$mixed_refs$global_header$qp_min$qp_max$qp_step$keyint$keyint_min$psy_rd$frameref$bframes$b_adapt$b_bias$b_pyramid$weight_b$direct_pred$subq$chroma_me$cabac$nal_hrd$aq_strength$aq_mode$deblock$stats$ratetol$vbv_maxrate$vbv_bufsize$vbv_init$cqm$deadzone_inter$deadzone_intra$aud$level_idc:threads=auto:ssim:psnr -passlogfile $PASSLOG $quiet"
		;;
		-3p)
		# Pass one
		# do not use subs for first pass
		echo "$priority_level $MENCODER \"$sourcetype\" -o /dev/null $device $vid $chapters $dvdangle $fps $ofps $videofilters $field_dominance $aspect $sws $aid $audiofilters $channels $ac3drc $acodec \
		-ovc x264 -x264encopts pass=1:$bitrate$turbo$me$me_range$dct_decimate$interlaced$a8x8dct$fast_pskip$trellis$scenecut$chroma_qp_offset$nr$ip_factor$pb_factor$cplx_blur$qblur$qcomp$partitions$mixed_refs$global_header$qp_min$qp_max$qp_step$keyint$keyint_min$psy_rd$frameref$bframes$b_adapt$b_bias$b_pyramid$weight_b$direct_pred$subq$chroma_me$cabac$nal_hrd$aq_strength$aq_mode$deblock$stats$ratetol$vbv_maxrate$vbv_bufsize$vbv_init$cqm$deadzone_inter$deadzone_intra$aud$level_idc:threads=auto:ssim:psnr -passlogfile $PASSLOG $quiet"
		echo ""
		# Pass two - pass=3 is not a typo here!
		# do not use subs for second pass
		echo "$priority_level $MENCODER \"$sourcetype\" -o /dev/null $device $vid $chapters $dvdangle $fps $ofps $videofilters $field_dominance $aspect $sws $aid $audiofilters $channels $ac3drc $acodec \
		-ovc x264 -x264encopts pass=3:$bitrate$me$me_range$dct_decimate$interlaced$a8x8dct$fast_pskip$trellis$scenecut$chroma_qp_offset$nr$ip_factor$pb_factor$cplx_blur$qblur$qcomp$partitions$mixed_refs$global_header$qp_min$qp_max$qp_step$keyint$keyint_min$psy_rd$frameref$bframes$b_adapt$b_bias$b_pyramid$weight_b$direct_pred$subq$chroma_me$cabac$nal_hrd$aq_strength$aq_mode$deblock$stats$ratetol$vbv_maxrate$vbv_bufsize$vbv_init$cqm$deadzone_inter$deadzone_intra$aud$level_idc:threads=auto:ssim:psnr -passlogfile $PASSLOG $quiet"
		echo ""
		# Pass 3
		echo "$priority_level $MENCODER \"$sourcetype\" -o \"$OUTPUT\" $device $vid $chapters $dvdangle $subtitle $vobsubout $fps $ofps $videofilters $field_dominance $aspect $sws $aid $audiofilters $channels $ac3drc $acodec \
		-ovc x264 -x264encopts pass=3:$bitrate$me$me_range$dct_decimate$interlaced$a8x8dct$fast_pskip$trellis$scenecut$chroma_qp_offset$nr$ip_factor$pb_factor$cplx_blur$qblur$qcomp$partitions$mixed_refs$global_header$qp_min$qp_max$qp_step$keyint$keyint_min$psy_rd$frameref$bframes$b_adapt$b_bias$b_pyramid$weight_b$direct_pred$subq$chroma_me$cabac$nal_hrd$aq_strength$aq_mode$deblock$stats$ratetol$vbv_maxrate$vbv_bufsize$vbv_init$cqm$deadzone_inter$deadzone_intra$aud$level_idc:threads=auto:ssim:psnr -passlogfile $PASSLOG $quiet"
		;;
	esac
}

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

H264_1PFQ="$CONFIGDIR/h264enc_1pfq"
H264_2P1="$CONFIGDIR/h264enc_pass_one"
H264_2P2="$CONFIGDIR/h264enc_pass_two"
H264_2P3="$CONFIGDIR/h264enc_pass_three"

case "$source" in
	dir|DIR|Dir)
	BATCH="$H264ENCDIR/batch$$"
	echo "################### START OF COMMANDS ###################" > "$BATCH"
	echo "" >> "$BATCH"
	echo "cd \"$(dirname "$sourcetype")\"" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "for i in *; do" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "test -d $CONFIGDIR || mkdir -p $CONFIGDIR" >> "$BATCH"
	echo "" >> "$BATCH"
	case "$1" in
		-1p|-fq)
		echo "$(mencoder_opts $1 | sed "s|$sourcetype|\$i|g" | sed "s|$OUTPUT|$OUTPUT/\$i.avi|g")" >> "$BATCH"
		echo "" >> "$BATCH"
		;;
		-2p)
		echo "$(mencoder_opts $1 | sed "s|$sourcetype|\$i|g" | sed "s|$OUTPUT|$OUTPUT/\$i.avi|g")" >> "$BATCH"
		echo "" >> "$BATCH"
		;;
		-3p)
		echo "$(mencoder_opts $1 | sed "s|$sourcetype|\$i|g" | sed "s|$OUTPUT|$OUTPUT/\$i.avi|g")" >> "$BATCH"
		echo "" >> "$BATCH"
		;;
	esac
	;;
	file|FILE|File|dvd|DVD|Dvd)
	case "$1" in
		-1p|-fq)
		$(mencoder_opts $1 > $H264_1PFQ)
		;;
		-2p)
		$(mencoder_opts $1 > $CONFIGDIR/h264enc_2pass)
		# Split 2pass file
		# into two files
		cat $CONFIGDIR/h264enc_2pass | head -n1 > $H264_2P1
		cat $CONFIGDIR/h264enc_2pass | tail -n1 > $H264_2P2
		rm -f $CONFIGDIR/h264enc_2pass
		;;
		-3p)
		$(mencoder_opts $1 > $CONFIGDIR/h264enc_3pass)
		# Split 3pass file
		# into three files
		cat $CONFIGDIR/h264enc_3pass | head -n1 > $H264_2P1
		cat $CONFIGDIR/h264enc_3pass | head -n3 | tail -n1 > $H264_2P2
		cat $CONFIGDIR/h264enc_3pass | tail -n1 > $H264_2P3
		rm -f $CONFIGDIR/h264enc_3pass
		;;
	esac
	;;
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
case "$source" in
	dir|DIR|Dir)
	false
	;;
	file|FILE|File|dvd|DVD|Dvd)
	printf "Would you like to inspect the MEncoder options? [y/n]: "
	read inspect
	if [ "$inspect" = "y" -o "$inspect" = "Y" ]; then
		echo ""
		brown "+===========================+"
		brown "| MEncoder encoding options |"
		brown "+===========================+"
		echo ""
		case "$1" in
			-1p|-fq)
			echo $(cat $H264_1PFQ)
			;;
			-2p)
			brown "First pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo $(cat $H264_2P1)
			echo ""
			brown "Second pass options"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo $(cat $H264_2P2)
			;;
			-3p)
			brown "First pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo $(cat $H264_2P1)
			echo ""
			brown "Second pass options"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo $(cat $H264_2P2)
			echo ""
			brown "Third pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo $(cat $H264_2P3)
			;;
		esac
		echo ""
	fi
	;;
esac

# Encode a sample
case "$source" in
	dir|DIR|Dir)
	false
	;;
	file|FILE|File|dvd|DVD|Dvd)
	printf "Would you like to encode a Sample? [y/n]: "
	read sample
	if [ "$sample" = "y" -o "$sample" = "Y" ]; then
		printf "Specify the start position in hour:min:sec [default is 0:02:00]: "
		read sample_startpos
		if [ -z "$sample_startpos" ]; then
			samplepos="-ss 0:02:00"
		else
			samplepos="-ss $sample_startpos"
		fi
		printf "Specify the duration in seconds for the sample [default is 30]: "
		read sample_duration
		if [ -z "$sample_duration" ]; then
			sampledur="-endpos 30"
		else
			sampledur="-endpos $sample_duration"
		fi
		echo ""
		green "-> Encoding sample, please wait..."
		test -e $HOME/sample_$$.avi && mv -f $HOME/sample_$$.avi $HOME/sample_$$.avi.old
		case "$1" in
			-1p|-fq)
			cat $H264_1PFQ | sed -e "s|$MENCODER|$TIME -f %E -o $CONFIGDIR/time $MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > $CONFIGDIR/sampleopts
			. $CONFIGDIR/sampleopts >/dev/null 2>&1
			# Remove subs if any
			for i in "$IDXFILE1" "$SUBFILE1"; do
				test -e "$i" && rm -f "$i"
			done
			if [ -e "$HOME/sample_$$.avi" ]; then
				green "-> Done... Elapsed time: $(cat $CONFIGDIR/time | sed 's/\.[0-9]*//')"
				green "-> Sample: $HOME/sample_$$.avi"
				sleep 1
				green "-> Previewing..."
				sleep 1
				$MPLAYER -nocache "$HOME/sample_$$.avi" >/dev/null 2>&1
			else
				error "-> Failed"
			fi
			for i in sampleopts time; do
				rm -f $CONFIGDIR/$i
			done
			echo ""
			;;
			-2p)
			cat $H264_2P1 | sed "s|$MENCODER|$TIME -f %E -o $CONFIGDIR/time $MENCODER $samplepos $sampledur|" > $CONFIGDIR/sampleopts1
			cat $H264_2P2 | sed -e "s|$MENCODER|$TIME -f %E -o $CONFIGDIR/time $MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > $CONFIGDIR/sampleopts2
			green "-> Running pass one..."
			. $CONFIGDIR/sampleopts1 >/dev/null 2>&1
			green "-> Done... Elapsed time: $(cat $CONFIGDIR/time | sed 's/\.[0-9]*//')"
			echo ""
			green "-> Running pass two..."
			. $CONFIGDIR/sampleopts2 >/dev/null 2>&1
			# Remove subs if any
			for i in "$IDXFILE1" "$SUBFILE1"; do
				test -e "$i" && rm -f "$i"
			done
			if [ -e "$HOME/sample_$$.avi" ]; then
				green "-> Done... Elapsed time: $(cat $CONFIGDIR/time | sed 's/\.[0-9]*//')"
				green "-> Sample: $HOME/sample_$$.avi"
				sleep 1
				green "-> Previewing..."
				sleep 1
				$MPLAYER -nocache "$HOME/sample_$$.avi" >/dev/null 2>&1
			else
				error "-> Failed"
			fi
			for i in sampleopts1 sampleopts2 time h264.log; do
				rm -f $CONFIGDIR/$i
			done
			echo ""
			;;
			-3p)
			cat $H264_2P1 | sed "s|$MENCODER|$TIME -f %E -o $CONFIGDIR/time $MENCODER $samplepos $sampledur|" > $CONFIGDIR/sampleopts1
			cat $H264_2P2 | sed "s|$MENCODER|$TIME -f %E -o $CONFIGDIR/time $MENCODER $samplepos $sampledur|" > $CONFIGDIR/sampleopts2
			cat $H264_2P3 | sed -e "s|$MENCODER|$TIME -f %E -o $CONFIGDIR/time $MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > $CONFIGDIR/sampleopts3
			green "-> Running pass one..."
			. $CONFIGDIR/sampleopts1 >/dev/null 2>&1
			green "-> Done... Elapsed time: $(cat $CONFIGDIR/time | sed 's/\.[0-9]*//')"
			echo ""
			green "-> Running pass two..."
			. $CONFIGDIR/sampleopts2 >/dev/null 2>&1
			green "-> Done... Elapsed time: $(cat $CONFIGDIR/time | sed 's/\.[0-9]*//')"
			echo ""
			green "-> Running pass three..."
			. $CONFIGDIR/sampleopts3 >/dev/null 2>&1
			# Remove subs if any
			for i in "$IDXFILE1" "$SUBFILE1"; do
				test -e "$i" && rm -f "$i"
			done
			if [ -e "$HOME/sample_$$.avi" ]; then
				green "-> Done... Elapsed time: $(cat $CONFIGDIR/time | sed 's/\.[0-9]*//')"
				green "-> Sample: $HOME/sample_$$.avi"
				sleep 1
				green "-> Previewing..."
				sleep 1
				$MPLAYER -nocache "$HOME/sample_$$.avi" >/dev/null 2>&1
			else
				error "-> Failed"
			fi
			for i in sampleopts1 sampleopts2 sampleopts3 time h264.log; do
				rm -f $CONFIGDIR/$i
			done
			echo ""
			;;
		esac
	fi
	;;
esac

# Export the MEncoder parameters to an
# options file. Useful for inspection
# of the parameters or for batch encoding.
case "$source" in
	dir|DIR|Dir)
	false
	;;
	file|FILE|File|dvd|DVD|Dvd)
	printf "Would you like to save the MEncoder options to a file? [y/n]: "
	read saveopts
	if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
		printf "Where to store the options? [default is $HOME/batchfile]: "
		read -e storeopts
		OPTSFILE="$HOME/batchfile"
		CMDSTART="################### START OF COMMANDS ###################"
		DIRTEST="test -d \"$(dirname "$OUTPUT")\" || mkdir -p \"$(dirname "$OUTPUT")\""
		CONFTEST="test -d $CONFIGDIR || mkdir -p $CONFIGDIR"
		FILETEST="test -e \"$OUTPUT\" && mv -f \"$OUTPUT\" \"$OUTPUT.old\""
		# Dump the second and/or third
		# subtitle if selected
		if [ ! -z "$subtitle2" ]; then
			SUB2="$priority_level $MENCODER $sourcetype $device $chapters $ofps $subtitle2 $vobsubout2 $aid -oac pcm -ovc copy -o /dev/null"
		fi
		if [ ! -z "$subtitle3" ]; then
			SUB3="$priority_level $MENCODER $sourcetype $device $chapters $ofps $subtitle3 $vobsubout3 $aid -oac pcm -ovc copy -o /dev/null"
		fi
		case "$1" in
			-1p|-fq)
			if [ -z "$storeopts" ]; then
				echo "$CMDSTART" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo "$DIRTEST" >> "$OPTSFILE"
				echo "$CONFTEST" >> "$OPTSFILE"
				echo "$FILETEST" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo $(cat $H264_1PFQ) >> "$OPTSFILE"
				echo "$SUB2" >> "$OPTSFILE"
				echo "$SUB3" >> "$OPTSFILE"
				echo "sleep 3" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
			else
				if [ -z "$(echo $storeopts | grep '^/')" ]; then
					error "-> You have to provide the full path!"
					rmconf
				else
					test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
					echo "$CMDSTART" >> "$storeopts"
					echo "" >> "$storeopts"
					echo "$DIRTEST" >> "$storeopts"
					echo "$CONFTEST" >> "$storeopts"
					echo "$FILETEST" >> "$storeopts"
					echo "" >> "$storeopts"
					echo $(cat $H264_1PFQ) >> "$storeopts"
					echo "$SUB2" >> "$storeopts"
					echo "$SUB3" >> "$storeopts"
					echo "sleep 3" >> "$storeopts"
					echo "" >> "$storeopts"
				fi
			fi
			;;
			-2p)
			if [ -z "$storeopts" ]; then
				echo "$CMDSTART" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo "$DIRTEST" >> "$OPTSFILE"
				echo "$CONFTEST" >> "$OPTSFILE"
				echo "$FILETEST" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo $(cat $H264_2P1) >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo $(cat $H264_2P2) >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo "$SUB2" >> "$OPTSFILE"
				echo "$SUB3" >> "$OPTSFILE"
				echo "sleep 3" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
			else
				if [ -z "$(echo $storeopts | grep '^/')" ]; then
					error "-> You have to provide the full path!"
					rmconf
				else
					test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
					echo "$CMDSTART" >> "$storeopts"
					echo "" >> "$storeopts"
					echo "$DIRTEST" >> "$storeopts"
					echo "$CONFTEST" >> "$storeopts"
					echo "$FILETEST" >> "$storeopts"
					echo "" >> "$storeopts"
					echo $(cat $H264_2P1) >> "$storeopts"
					echo "" >> "$storeopts"
					echo $(cat $H264_2P2) >> "$storeopts"
					echo "" >> "$storeopts"
					echo "$SUB2" >> "$storeopts"
					echo "$SUB3" >> "$storeopts"
					echo "sleep 3" >> "$storeopts"
					echo "" >> "$storeopts"
				fi
			fi
			;;
			-3p)
			if [ -z "$storeopts" ]; then
				echo "$CMDSTART" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo "$DIRTEST" >> "$OPTSFILE"
				echo "$CONFTEST" >> "$OPTSFILE"
				echo "$FILETEST" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo $(cat $H264_2P1) >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo $(cat $H264_2P2) >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo $(cat $H264_2P3) >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo "$SUB2" >> "$OPTSFILE"
				echo "$SUB3" >> "$OPTSFILE"
				echo "sleep 3" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
			else
				if [ -z "$(echo $storeopts | grep '^/')" ]; then
					error "-> You have to provide the full path!"
					rmconf
				else
					test -d "$(dirname "$storeopts")" || mkdir -p "$(dirname "$storeopts")"
					echo "$CMDSTART" >> "$storeopts"
					echo "" >> "$storeopts"
					echo "$DIRTEST" >> "$storeopts"
					echo "$CONFTEST" >> "$storeopts"
					echo "$FILETEST" >> "$storeopts"
					echo "" >> "$storeopts"
					echo $(cat $H264_2P1) >> "$storeopts"
					echo "" >> "$storeopts"
					echo $(cat $H264_2P2) >> "$storeopts"
					echo "" >> "$storeopts"
					echo $(cat $H264_2P3) >> "$storeopts"
					echo "" >> "$storeopts"
					echo "$SUB2" >> "$storeopts"
					echo "$SUB3" >> "$storeopts"
					echo "sleep 3" >> "$storeopts"
					echo "" >> "$storeopts"
				fi
			fi
			;;
		esac
	fi
	;;
esac

# For neroAAC, AAC+ and Vorbis audio
case "$source" in
	dir|DIR|Dir)
	MENC="$priority_level $MENCODER \"$OUTPUT/\$i.avi\" -nosound -ovc copy -of rawvideo -o $CONFIGDIR/video.h264"
	MPL="$priority_level $MPLAYER \"$OUTPUT/\$i.avi\" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1"
	FIFO="mkfifo $CONFIGDIR/audio.wav"
	NERO="$priority_level $NEROAACENC -ignorelength $neroaacbr -if $CONFIGDIR/audio.wav -of $CONFIGDIR/audio.aac &"
	AACPLUS="$priority_level $AACPLUSENC $CONFIGDIR/audio.wav $CONFIGDIR/audio.aac $aacplusbr &"
	OGG="$priority_level $OGGENC $vorbq $CONFIGDIR/audio.wav -o $CONFIGDIR/audio.ogg &"
	case "$audiocodec" in
		aac+|AAC+|neroaac|neroAAC|vorbis|VORBIS)
		echo "$MENC" >> "$BATCH"
		echo "sleep 3" >> "$BATCH"
		echo "" >> "$BATCH"
		echo "$FIFO" >> "$BATCH"
		case "$audiocodec" in
			aac+|AAC+)
			echo "$AACPLUS" >> "$BATCH"
			echo "$MPL" >> "$BATCH"
			echo "" >> "$BATCH"
			;;
			neroaac|neroAAC)
			echo "$NERO" >> "$BATCH"
			echo "$MPL" >> "$BATCH"
			echo "" >> "$BATCH"
			;;
			vorbis|VORBIS)
			echo "$OGG" >> "$BATCH"
			echo "$MPL" >> "$BATCH"
			echo "" >> "$BATCH"
			;;
		esac
		;;
	esac
	;;
	file|FILE|File|dvd|DVD|Dvd)
	if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
		MENC="$priority_level $MENCODER \"$OUTPUT\" -nosound -ovc copy -of rawvideo -o $CONFIGDIR/video.h264"
		MPL="$priority_level $MPLAYER \"$OUTPUT\" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1"
		FIFO="mkfifo $CONFIGDIR/audio.wav"
		NERO="$priority_level $NEROAACENC -ignorelength $neroaacbr -if $CONFIGDIR/audio.wav -of $CONFIGDIR/audio.aac &"
		AACPLUS="$priority_level $AACPLUSENC $CONFIGDIR/audio.wav $CONFIGDIR/audio.aac $aacplusbr &"
		OGG="$priority_level $OGGENC $vorbq $CONFIGDIR/audio.wav -o $CONFIGDIR/audio.ogg &"
		case "$audiocodec" in
			aac+|AAC+|neroaac|neroAAC|vorbis|VORBIS)
			if [ -z "$storeopts" ]; then
				echo "$MENC" >> "$OPTSFILE"
				echo "sleep 3" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				echo "$FIFO" >> "$OPTSFILE"
				case "$audiocodec" in
					aac+|AAC+)
					echo "$AACPLUS" >> "$OPTSFILE"
					echo "$MPL" >> "$OPTSFILE"
					echo "" >> "$OPTSFILE"
					;;
					neroaac|neroAAC)
					echo "$NERO" >> "$OPTSFILE"
					echo "$MPL" >> "$OPTSFILE"
					echo "" >> "$OPTSFILE"
					;;
					vorbis|VORBIS)
					echo "$OGG" >> "$OPTSFILE"
					echo "$MPL" >> "$OPTSFILE"
					echo "" >> "$OPTSFILE"
					;;
				esac
			else
				echo "$MENC" >> "$storeopts"
				echo "sleep 3" >> "$storeopts"
				echo "$storeopts"
				echo "$FIFO" >> "$storeopts"
				case "$audiocodec" in
					aac+|AAC+)
					echo "$AACPLUS" >> "$storeopts"
					echo "$MPL" >> "$storeopts"
					echo "" >> "$storeopts"
					;;
					neroaac|neroAAC)
					echo "$NERO" >> "$storeopts"
					echo "$MPL" >> "$storeopts"
					echo "" >> "$storeopts"
					;;
					vorbis|VORBIS)
					echo "$OGG" >> "$storeopts"
					echo "$MPL" >> "$storeopts"
					echo "" >> "$storeopts"
					;;
				esac
			fi
			;;
		esac
	fi
	;;
esac

# Ask user if he wants to convert
# from AVI to Matroska container.
case "$audiocodec" in
	mp3|MP3|aac|AAC|aac+|AAC+|neroaac|neroAAC|vorbis|VORBIS|ac3|AC3|pcm|PCM|copy|COPY|nosound|NOSOUND|"")
	printf "Would you like to convert the final encode from AVI to MKV? [y/n]: "
	read avi_mkv
	if [ "$avi_mkv" = "y" -o "$avi_mkv" = "Y" ]; then
		# Check for mkvmerge
		if [ ! -x "$MKVMERGE" ]; then
			avi_to_mkv=no
			echo ""
			green "-> Utility 'mkvmerge' is missing!"
			green "-> Skipping AVI to MKV conversion!"
			echo ""
		else
			avi_to_mkv=yes
			case "$source" in
				dir|DIR|Dir)
				# Global variables
				MKVOUT="\"$OUTPUT/\$i.mkv\""
				case "$audiocodec" in
					aac+|AAC+)
					MKVH264="$CONFIGDIR/video.h264"
					MKVAUD="$CONFIGDIR/audio.aac --aac-is-sbr 1:1"
					RAWFPS="--default-duration 0:\$($MPLAYER \"$OUTPUT/\$i.avi\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')fps"
					;;
					neroaac|neroAAC)
					MKVH264="$CONFIGDIR/video.h264"
					RAWFPS="--default-duration 0:\$($MPLAYER \"$OUTPUT/\$i.avi\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')fps"
					if [ "$aacprof" = "-he" -o "$aacprof" = "-hev2" ]; then
						MKVAUD="$CONFIGDIR/audio.aac --aac-is-sbr 1:1"
					else
						MKVAUD="$CONFIGDIR/audio.aac"
					fi
					;;
					vorbis|VORBIS)
					MKVH264="$CONFIGDIR/video.h264"
					MKVAUD="$CONFIGDIR/audio.ogg"
					RAWFPS="--default-duration 0:\$($MPLAYER \"$OUTPUT/\$i.avi\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')fps"
					;;
					*|"")
					MKVH264="\"$OUTPUT/\$i.avi\""
					;;
				esac
				echo "$priority_level $MKVMERGE $RAWFPS $MKVH264 $MKVAUD -o $MKVOUT" >> "$BATCH"
				echo "" >> "$BATCH"
				;;
				file|FILE|File|dvd|DVD|Dvd)
				# Global variables
				MKVOUT=$(echo "$OUTPUT" | sed 's|\.avi|\.mkv|')
				MKVTEST="test -e \"$MKVOUT\" && mv -f \"$MKVOUT\" \"$MKVOUT.old\""
				case "$audiocodec" in
					aac+|AAC+)
					MKVH264="$CONFIGDIR/video.h264"
					MKVAUD="$CONFIGDIR/audio.aac --aac-is-sbr 1:1"
					RAWFPS="--default-duration 0:\$($MPLAYER \"$OUTPUT\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')fps"
					;;
					neroaac|neroAAC)
					MKVH264="$CONFIGDIR/video.h264"
					RAWFPS="--default-duration 0:\$($MPLAYER \"$OUTPUT\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')fps"
					if [ "$aacprof" = "-he" -o "$aacprof" = "-hev2" ]; then
						MKVAUD="$CONFIGDIR/audio.aac --aac-is-sbr 1:1"
					else
						MKVAUD="$CONFIGDIR/audio.aac"
					fi
					;;
					vorbis|VORBIS)
					MKVH264="$CONFIGDIR/video.h264"
					MKVAUD="$CONFIGDIR/audio.ogg"
					RAWFPS="--default-duration 0:\$($MPLAYER \"$OUTPUT\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')fps"
					;;
					*|"")
					MKVH264="$OUTPUT"
					;;
				esac
				# Chapters for MKV
				if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
					printf "Import chapters information into the MKV container? [y/n]: "
					read mkv_impchap
					if [ "$mkv_impchap" = "y" -o "$mkv_impchap" = "Y" ]; then
						MKVCHAPS="--chapters \"$CHAPTERSFILE\""
					fi
				fi
				# Subtitles for MKV
				case "$source" in
					file|FILE|File)
					if [ "$submethod" = "1" ]; then
						MKVSUB="\"$IDXFILE\""
					fi
					;;
					dvd|DVD|Dvd)
					if [ ! -z "$vobsubout" -o ! -z "$vobsubout2" ]; then
						printf "Import the ripped subtitle(s) into the MKV container? [y/n]: "
						read mkv_impsub
						if [ "$mkv_impsub" = "y" -o "$mkv_impsub" = "Y" ]; then
							if [ -z "$IDXFILE1" -a -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MKVSUB=
							elif [ ! -z "$IDXFILE1" -a -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MKVSUB="\"$IDXFILE1\""
							elif [ -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MKVSUB="\"$IDXFILE2\""
							elif [ -z "$IDXFILE1" -a -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MKVSUB="\"$IDXFILE3\""
							elif [ ! -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MKVSUB="\"$IDXFILE1\" \"$IDXFILE2\""
							elif [ ! -z "$IDXFILE1" -a -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MKVSUB="\"$IDXFILE1\" \"$IDXFILE3\""
							elif [ -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MKVSUB="\"$IDXFILE2\" \"$IDXFILE3\""
							elif [ ! -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MKVSUB="\"$IDXFILE1\" \"$IDXFILE2\" \"$IDXFILE3\""
							fi
						fi
					fi
					;;
				esac
				# Export commands for muxing
				# through the script
				echo "$MKVTEST" >> "$CONFIGDIR/mkvmuxing"
				echo "$priority_level $MKVMERGE $RAWFPS \"$MKVH264\" $MKVAUD $MKVSUB $MKVCHAPS -o \"$MKVOUT\"" >> "$CONFIGDIR/mkvmuxing"
				
				# Export commands to the batch file
				if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
					if [ -z "$storeopts" ]; then
						echo "$MKVTEST" >> "$OPTSFILE"
						echo "$priority_level $MKVMERGE $RAWFPS \"$MKVH264\" $MKVAUD $MKVSUB $MKVCHAPS -o \"$MKVOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					else
						echo "$MKVTEST" >> "$storeopts"
						echo "$priority_level $MKVMERGE $RAWFPS \"$MKVH264\" $MKVAUD $MKVSUB $MKVCHAPS -o \"$MKVOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					fi
				fi
				;;
			esac
		fi
	elif [ "$avi_mkv" = "n" -o "$avi_mkv" = "N" -o -z "$avi_mkv" ]; then
		avi_to_mkv=no
	fi
	;;
	*|"")
	avi_to_mkv=no
	;;
esac

# Ask for AVI -> MP4 conversion
case "$audiocodec" in
	mp3|MP3|aac|AAC|aac+|AAC+|neroaac|neroAAC|vorbis|VORBIS|nosound|NOSOUND|"")
	printf "Would you like to convert the final encode from AVI to MP4? [y/n]: "
	read avi_mp4
	if [ "$avi_mp4" = "y" -o "$avi_mp4" = "Y" ]; then
		if [ ! -x "$MP4BOX" ]; then
			avi_to_mp4=no
			echo ""
			green "-> MP4Box (from gpac) is missing!"
			green "-> Skipping AVI to MP4 conversion!"
			echo ""
		else
			avi_to_mp4=yes
			case "$source" in
				dir|DIR|Dir)
				# Global variables
				MP4OUT="\"$OUTPUT/\$i.mp4\""
				MP4FPS="-fps \$($MPLAYER \"$OUTPUT/\$i.avi\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')"
				VIDEOINPUT="-add $CONFIGDIR/*.h264"
				case "$3" in
					ipc|ipchq|ip|iphq|iph|iphhq)
					MP4SAR="$priority_level $MP4BOX -ipod $MP4OUT"
					;;
				esac
				case "$audiocodec" in
					mp3|MP3)
					MP4VID="$priority_level $MP4BOX -aviraw video \"$OUTPUT/\$i.avi\" -out $CONFIGDIR/h264.h264"
					MP4AUD="$priority_level $MP4BOX -aviraw audio \"$OUTPUT/\$i.avi\" -out $CONFIGDIR/mp3.mp3"
					AUDIOINPUT="-add $CONFIGDIR/*.mp3"
					;;
					aac|AAC|"")
					MP4VID="$priority_level $MP4BOX -aviraw video \"$OUTPUT/\$i.avi\" -out $CONFIGDIR/h264.h264"
					MP4AUD="$priority_level $MP4BOX -aviraw audio \"$OUTPUT/\$i.avi\" -out $CONFIGDIR/aac.raw"
					MVRAW="mv -f $CONFIGDIR/*.raw $CONFIGDIR/audio.aac"
					AUDIOINPUT="-add $CONFIGDIR/*.aac"
					;;
					aac+|AAC+)
					AUDIOINPUT="-add $CONFIGDIR/*.aac -sbr"
					;;
					neroaac|neroAAC)
					if [ "$aacprof" = "-he" -o "$aacprof" = "-hev2" ]; then
						AUDIOINPUT="-add $CONFIGDIR/*.aac -sbr"
					else
						AUDIOINPUT="-add $CONFIGDIR/*.aac"
					fi
					;;
					vorbis|VORBIS)
					AUDIOINPUT="-add $CONFIGDIR/*.ogg"
					;;
					nosound|NOSOUND)
					MP4VID="$priority_level $MP4BOX -aviraw video \"$OUTPUT/\$i.avi\" -out $CONFIGDIR/h264.h264"
					;;
				esac
				echo "$MP4VID" >> "$BATCH"
				echo "$MP4AUD" >> "$BATCH"
				echo "$MVRAW" >> "$BATCH"
				echo "$priority_level $MP4BOX $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT $MP4OUT" >> "$BATCH"
				echo "$MP4SAR" >> "$BATCH"
				echo "" >> "$BATCH"
				;;
				file|FILE|File|dvd|DVD|Dvd)
				# Global variables
				MP4OUT=$(echo "$OUTPUT" | sed 's|\.avi|\.mp4|')
				MP4FPS="-fps \$($MPLAYER \"$OUTPUT\" -identify -nosound -vo null -nocache -frames 1 | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}')"
				MP4TEST="test -e \"$MP4OUT\" && mv -f \"$MP4OUT\" \"$MP4OUT.old\""
				VIDEOINPUT="-add $CONFIGDIR/*.h264"
				case "$3" in
					ipc|ipchq|ip|iphq|iph|iphhq)
					MP4SAR="$priority_level $MP4BOX -ipod \"$MP4OUT\""
					;;
				esac
				case "$audiocodec" in
					mp3|MP3)
					MP4VID="$priority_level $MP4BOX -aviraw video \"$OUTPUT\" -out $CONFIGDIR/h264.h264"
					MP4AUD="$priority_level $MP4BOX -aviraw audio \"$OUTPUT\" -out $CONFIGDIR/mp3.mp3"
					AUDIOINPUT="-add $CONFIGDIR/*.mp3"
					;;
					aac|AAC|"")
					MP4VID="$priority_level $MP4BOX -aviraw video \"$OUTPUT\" -out $CONFIGDIR/h264.h264"
					MP4AUD="$priority_level $MP4BOX -aviraw audio \"$OUTPUT\" -out $CONFIGDIR/aac.raw"
					MVRAW="mv -f $CONFIGDIR/*.raw $CONFIGDIR/audio.aac"
					AUDIOINPUT="-add $CONFIGDIR/*.aac"
					;;
					aac+|AAC+)
					AUDIOINPUT="-add $CONFIGDIR/*.aac -sbr"
					;;
					neroaac|neroAAC)
					if [ "$aacprof" = "-he" -o "$aacprof" = "-hev2" ]; then
						AUDIOINPUT="-add $CONFIGDIR/*.aac -sbr"
					else
						AUDIOINPUT="-add $CONFIGDIR/*.aac"
					fi
					;;
					vorbis|VORBIS)
					AUDIOINPUT="-add $CONFIGDIR/*.ogg"
					;;
					nosound|NOSOUND)
					MP4VID="$priority_level $MP4BOX -aviraw video \"$OUTPUT\" -out $CONFIGDIR/h264.h264"
					;;
				esac
				# Chapters for MP4
				if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
					printf "Import chapters information into the MP4 container? [y/n]: "
					read mp4_impchap
					if [ "$mp4_impchap" = "y" -o "$mp4_impchap" = "Y" ]; then
						MP4CHAPS="-chap \"$CHAPTERSFILE\""
					fi
				fi
				# Subtitles for MP4
				case "$source" in
					file|FILE|File)
					if [ "$submethod" = "1" ]; then
						MP4SUB="-add \"$IDXFILE\""
					else
						MP4SUB=
					fi
					;;
					dvd|DVD|Dvd)
					if [ ! -z "$vobsubout" -o ! -z "$vobsubout2" ]; then
						printf "Import the ripped subtitle(s) into the MP4 container? [y/n]: "
						read mp4_impsub
						if [ "$mp4_impsub" = "y" -o "$mp4_impsub" = "Y" ]; then
							if [ -z "$IDXFILE1" -a -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MP4SUB=
							elif [ ! -z "$IDXFILE1" -a -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MP4SUB="-add \"$IDXFILE1\""
							elif [ -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MP4SUB="-add \"$IDXFILE2\""
							elif [ -z "$IDXFILE1" -a -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MP4SUB="-add \"$IDXFILE3\""
							elif [ ! -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a -z "$IDXFILE3" ]; then
								MP4SUB="-add \"$IDXFILE1\" -add \"$IDXFILE2\""
							elif [ ! -z "$IDXFILE1" -a -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MP4SUB="-add \"$IDXFILE1\" -add \"$IDXFILE3\""
							elif [ -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MP4SUB="-add \"$IDXFILE2\" -add \"$IDXFILE3\""
							elif [ ! -z "$IDXFILE1" -a ! -z "$IDXFILE2" -a ! -z "$IDXFILE3" ]; then
								MP4SUB="-add \"$IDXFILE1\" -add \"$IDXFILE2\" -add \"$IDXFILE3\""
							fi
						fi
					fi
					;;
				esac
				# Export commands for muxing
				# through the script
				echo "$MP4TEST" >> "$CONFIGDIR/mp4muxing"
				echo "$MP4VID" >> "$CONFIGDIR/mp4muxing"
				echo "$MP4AUD" >> "$CONFIGDIR/mp4muxing"
				echo "$MVRAW" >> "$CONFIGDIR/mp4muxing"
				echo "$priority_level $MP4BOX $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT $MP4SUB $MP4CHAPS \"$MP4OUT\"" >> "$CONFIGDIR/mp4muxing"
				echo "$MP4SAR" >> "$CONFIGDIR/mp4muxing"
				
				# Export commands to the batch file
				if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
					if [ -z "$storeopts" ]; then
						echo "$MP4VID" >> "$OPTSFILE"
						echo "$MP4AUD" >> "$OPTSFILE"
						echo "$MVRAW" >> "$OPTSFILE"
						echo "$MP4TEST" >> "$OPTSFILE"
						echo "$priority_level $MP4BOX $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT $MP4SUB $MP4CHAPS \"$MP4OUT\"" >> "$OPTSFILE"
						echo "$MP4SAR" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					else
						echo "$MP4VID" >> "$storeopts"
						echo "$MP4AUD" >> "$storeopts"
						echo "$MVRAW" >> "$storeopts"
						echo "$MP4TEST" >> "$storeopts"
						echo "$priority_level $MP4BOX $MP4FPS -tmp $CONFIGDIR $VIDEOINPUT $AUDIOINPUT $MP4SUB $MP4CHAPS \"$MP4OUT\"" >> "$storeopts"
						echo "$MP4SAR" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					fi
				fi
				;;
			esac
		fi
	elif [ "$avi_mp4" = "n" -o "$avi_mp4" = "N" -o -z "$avi_mp4" ]; then
		avi_to_mp4=no
	fi
	;;
	*)
	avi_to_mp4=no
	;;
esac


# AVI -> TS
case "$source" in
	dir|DIR|Dir)
	false
	;;
	*)
	case "$audiocodec" in
		aac|AAC|mp3|MP3|ac3|AC3|copy|COPY|nosound|NOSOUND|"")
		case "$3" in
			bd40|bdhq40|bd41|bdhq41)
			printf "Would you like to convert the final encode from AVI to Blu-ray? [y/n]: "
			;;
			*)
			printf "Would you like to convert the final encode from AVI to TS? [y/n]: "
			;;
		esac
		read avi_ts
		if [ "$avi_ts" = "y" -o "$avi_ts" = "Y" ]; then
			# Check for tsMuxeR
			if [ ! -x "$TSMUXER" ]; then
				avi_to_ts=no
				echo ""
				green "-> Utility 'tsMuxeR' is missing!"
				green "-> Skipping AVI to TS/Blu-ray conversion!"
				echo ""
			else
				avi_to_ts=yes
				# Global variables
				TSVID="$priority_level $MENCODER \"$OUTPUT\" -nosound -ovc copy -of rawvideo -o $CONFIGDIR/videots.h264"
				case "$audiocodec" in
					aac|AAC|mp3|MP3|ac3|AC3|copy|COPY|"")
					TSAUD="$priority_level $MPLAYER \"$OUTPUT\" -vo null -vc null $channels -dumpaudio -dumpfile $CONFIGDIR/audiots.raw"
					;;
					nosound|NOSOUND)
					tsacodec=nosound
					;;
				esac
				case "$3" in
					bd40|bdhq40|bd41|bdhq41)
					TSOUTPUT=$(echo "$OUTPUT" | sed 's|\.avi|\.bluray|')
					METAOPT="echo \"MUXOPT --no-pcr-on-video-pid --new-audio-pes --blu-ray --auto-chapters=5 --vbr --vbv-len=500\" >> $CONFIGDIR/tsmuxer.meta"
					;;
					*)
					TSOUTPUT=$(echo "$OUTPUT" | sed 's|\.avi|\.ts|')
					METAOPT="echo \"MUXOPT --no-pcr-on-video-pid --new-audio-pes --vbr\" >> $CONFIGDIR/tsmuxer.meta"
					;;
				esac
				TSFPS="$MPLAYER \"$OUTPUT\" -identify -vo null -nosound -frames 1 -nocache 2>/dev/null | grep '^ID_VIDEO_FPS' | tail -1 | awk -F= '{print \$2}' > $CONFIGDIR/tsfps"
				TSTEST="test -e \"$TSOUTPUT\" && mv -f \"$TSOUTPUT\" \"$TSOUTPUT.old\""
				TSMUX="$priority_level $TSMUXER $CONFIGDIR/tsmuxer.meta \"$TSOUTPUT\""
				METAVID="echo \"V_MPEG4/ISO/AVC, $CONFIGDIR/videots.h264, fps=\$(cat $CONFIGDIR/tsfps), insertSEI, contSPS\" >> $CONFIGDIR/tsmuxer.meta"
				case "$audiocodec" in
					aac|AAC|"")
					tsacodec=aac
					METAAUD="echo \"A_AAC, $CONFIGDIR/audiots.raw\" >> $CONFIGDIR/tsmuxer.meta"
					;;
					mp3|MP3)
					tsacodec=mp3
					METAAUD="echo \"A_MP3, $CONFIGDIR/audiots.raw\" >> $CONFIGDIR/tsmuxer.meta"
					;;
					ac3|AC3)
					tsacodec=ac3
					METAAUD="echo \"A_AC3, $CONFIGDIR/audiots.raw\" >> $CONFIGDIR/tsmuxer.meta"
					;;
					copy|COPY)
					printf "Which audio codec are you copying? [AC3/DTS/MP3/AAC - no default!]: "
					read tsaudiocopy
					case "$tsaudiocopy" in
						ac3|AC3)
						tsacodec=ac3
						METAAUD="echo \"A_AC3, $CONFIGDIR/audiots.raw\" >> $CONFIGDIR/tsmuxer.meta"
						;;
						dts|DTS)
						tsacodec=dts
						METAAUD="echo \"A_DTS, $CONFIGDIR/audiots.raw\" >> $CONFIGDIR/tsmuxer.meta"
						;;
						mp3|MP3)
						tsacodec=mp3
						METAAUD="echo \"A_MP3, $CONFIGDIR/audiots.raw\" >> $CONFIGDIR/tsmuxer.meta"
						;;
						aac|AAC)
						tsacodec=aac
						METAAUD="echo \"A_AAC, $CONFIGDIR/audiots.raw\" >> $CONFIGDIR/tsmuxer.meta"
						;;
						*|"")
						avi_to_ts=no
						tsacodec=
						echo ""
						green "-> Audio codec unsupported or not specified!"
						green "-> Skipping AVI to TS/Blu-ray conversion!"
						echo ""
						;;
					esac
					;;
				esac
				case "$tsacodec" in
					aac|mp3|ac3|dts|nosound)
					# Export commands for muxing
					# through the script
					echo "$TSTEST" >> "$CONFIGDIR/tsmuxing"
					echo "$TSFPS" >> "$CONFIGDIR/tsmuxing"
					echo "$TSVID" >> "$CONFIGDIR/tsmuxing"
					echo "$TSAUD" >> "$CONFIGDIR/tsmuxing"
					echo "$METAOPT" >> "$CONFIGDIR/tsmuxing"
					echo "$METAVID" >> "$CONFIGDIR/tsmuxing"
					echo "$METAAUD" >> "$CONFIGDIR/tsmuxing"
					echo "$TSMUX" >> "$CONFIGDIR/tsmuxing"
					case "$3" in
						bd40|bdhq40|bd41|bdhq41)
						# Workaround for bug in Linux version of tsMuxeR 1.7.3(b)
						echo "mv -f \"$TSOUTPUT/BDMV/STREAM\" \"$TSOUTPUT/BDMV/Stream\"" >> "$CONFIGDIR/tsmuxing"
						echo "mv -f \"$TSOUTPUT/BDMV/STREAM\" \"$TSOUTPUT/BDMV/Stream\"" >> "$CONFIGDIR/tsmuxing"
						echo "$TSMUX" >> "$CONFIGDIR/tsmuxing"
						echo "rm -rf \"$TSOUTPUT/BDMV/STREAM\"" >> "$CONFIGDIR/tsmuxing"
						echo "mv -f \"$TSOUTPUT/BDMV/Stream\" \"$TSOUTPUT/BDMV/STREAM\"" >> "$CONFIGDIR/tsmuxing"
						;;
					esac
					# Export muxing commands to
					# the batch file
					if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
						if [ ! -z "$storeopts" ]; then
							echo "$TSFPS" >> "$storeopts"
							echo "$TSVID" >> "$storeopts"
							echo "$TSAUD" >> "$storeopts"
							echo "" >> "$storeopts"
							echo "$METAOPT" >> "$storeopts"
							echo "$METAVID" >> "$storeopts"
							echo "$METAAUD" >> "$storeopts"
							echo "" >> "$storeopts"
							echo "$TSTEST" >> "$storeopts"
							echo "$TSMUX" >> "$storeopts"
							case "$3" in
								bd40|bdhq40|bd41|bdhq41)
								echo "" >> "$storeopts"
								echo "# Workaround for bug in Linux version of tsMuxeR 1.7.3(b)" >> "$storeopts"
								echo "mv -f \"$TSOUTPUT/BDMV/STREAM\" \"$TSOUTPUT/BDMV/Stream\"" >> "$storeopts"
								echo "$TSMUX" >> "$storeopts"
								echo "rm -rf \"$TSOUTPUT/BDMV/STREAM\"" >> "$storeopts"
								echo "mv -f \"$TSOUTPUT/BDMV/Stream\" \"$TSOUTPUT/BDMV/STREAM\"" >> "$sotreopts"
								;;
							esac
							echo "sleep 3" >> "$storeopts"
							echo "" >> "$storeopts"
						else
							echo "$TSFPS" >> "$OPTSFILE"
							echo "$TSVID" >> "$OPTSFILE"
							echo "$TSAUD" >> "$OPTSFILE"
							echo "" >> "$OPTSFILE"
							echo "$METAOPT" >> "$OPTSFILE"
							echo "$METAVID" >> "$OPTSFILE"
							echo "$METAAUD" >> "$OPTSFILE"
							echo "" >> "$OPTSFILE"
							echo "$TSTEST" >> "$OPTSFILE"
							echo "$TSMUX" >> "$OPTSFILE"
							case "$3" in
								bd40|bdhq40|bd41|bdhq41)
								echo "" >> "$OPTSFILE"
								echo "# Workaround for bug in Linux version of tsMuxeR 1.7.3(b)" >> "$OPTSFILE"
								echo "mv -f \"$TSOUTPUT/BDMV/STREAM\" \"$TSOUTPUT/BDMV/Stream\"" >> "$OPTSFILE"
								echo "$TSMUX" >> "$OPTSFILE"
								echo "rm -rf \"$TSOUTPUT/BDMV/STREAM\"" >> "$OPTSFILE"
								echo "mv -f \"$TSOUTPUT/BDMV/Stream\" \"$TSOUTPUT/BDMV/STREAM\"" >> "$OPTSFILE"
								;;
							esac
							echo "sleep 3" >> "$OPTSFILE"
							echo "" >> "$OPTSFILE"
						fi
					fi
					;;
				esac
			fi
		else
			avi_to_ts=no
		fi
		;;
		*) avi_to_ts=no ;;
	esac
	;;
esac

# Ask for AVI -> OGM
# ogmmerge doesn't like raw h264
# video so instead we take it
# directly from the AVI file
case "$audiocodec" in
	mp3|MP3|vorbis|VORBIS|ac3|AC3|pcm|PCM|copy|COPY|nosound|NOSOUND)
	printf "Would you like to convert the final encode from AVI to OGM? [y/n]: "
	read avi_ogm
	if [ "$avi_ogm" = "y" -o "$avi_ogm" = "Y" ]; then
		# Check for ogmmerge
		if [ ! -x "$OGMMERGE" ]; then
			avi_to_ogm=no
			echo ""
			green "-> Utility 'ogmmerge' is missing!"
			green "-> Skipping AVI to OGM conversion!"
		else
			avi_to_ogm=yes
			case "$source" in
				dir|DIR|Dir)
				# Global variables
				OGMOUT="\"$OUTPUT/\$i.ogm\""
				case "$audiocodec" in
					vorbis|VORBIS)
					NOAUDIO="--noaudio"
					OGMAUD="$CONFIGDIR/audio.ogg"
					;;
				esac
				echo "$priority_level $OGMMERGE $NOAUDIO \"$OUTPUT/\$i.avi\" $OGMAUD -o $OGMOUT" >> "$BATCH"
				echo "" >> "$BATCH"
				;;
				file|FILE|File|dvd|DVD|Dvd)
				# Global variables
				OGMOUT=$(echo "$OUTPUT" | sed 's|\.avi|\.ogm|')
				OGMTEST="test -e \"$OGMOUT\" && mv -f \"$OGMOUT\" \"$OGMOUT.old\""
				case "$audiocodec" in
					vorbis|VORBIS)
					NOAUDIO="--noaudio"
					OGMAUD="$CONFIGDIR/audio.ogg"
					;;
				esac
				# Chapters for OGM
				if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
					printf "Import chapters information into the OGM container? [y/n]: "
					read ogm_impchap
					if [ "$ogm_impchap" = "y" -o "$ogm_impchap" = "Y" ]; then
						OGMCHAPS="-c \"$CHAPTERSFILE\""
					fi
				fi
				# Export commands for muxing
				# through the script
				echo "$OGMTEST" >> "$CONFIGDIR/ogmmuxing"
				echo "$priority_level $OGMMERGE $NOAUDIO \"$OUTPUT\" $OGMAUD $OGMCHAPS -o \"$OGMOUT\"" >> "$CONFIGDIR/ogmmuxing"
				
				# Export commands to the batch file
				if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
					if [ -z "$storeopts" ]; then
						echo "$OGMTEST" >> "$OPTSFILE"
						echo "$priority_level $OGMMERGE $NOAUDIO \"$OUTPUT\" $OGMAUD $OGMCHAPS -o \"$OGMOUT\"" >> "$OPTSFILE"
						echo "sleep 3" >> "$OPTSFILE"
						echo "" >> "$OPTSFILE"
					else
						echo "$OGMTEST" >> "$storeopts"
						echo "$priority_level $OGMMERGE $NOAUDIO \"$OUTPUT\" $OGMAUD $OGMCHAPS -o \"$OGMOUT\"" >> "$storeopts"
						echo "sleep 3" >> "$storeopts"
						echo "" >> "$storeopts"
					fi
				fi
				;;
			esac
		fi
	elif [ "$avi_ogm" = "n" -o "$avi_ogm" = "N" -o -z "$avi_ogm" ]; then
		avi_to_ogm=no
	fi
	;;
	*|"")
	avi_to_ogm=no
	;;
esac

# Footers for batch files
case "$source" in
	dir|DIR|Dir)
	echo "rm -rf $CONFIGDIR" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "done" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "#################### END OF COMMANDS ####################" >> "$BATCH"
	;;
esac

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

echo ""
case "$source" in
	dir|DIR|Dir)
	green "-> Starting to batch encode $type in '$(dirname "$sourcetype")'"
	display_quality_preset_func $3 $4
	green "-> Using '$OUTPUT' as output directory for all $type"
	green "-> Batch file located in '$BATCH'"
	case "$1" in
		-1p)
		green "-> Using 1-pass mode for all $type"
		;;
		-fq)
		green "-> Using fixed-quant mode for all $type"
		;;
		-2p)
		green "-> Using 2-pass mode for all $type"
		;;
		-3p)
		green "-> Using 3-pass mode for all $type"
		;;
	esac
	;;
	file|FILE|File|dvd|DVD|Dvd)
	case "$1" in
		-1p)
		green "-> Starting to encode the $type in 1-pass mode"
		display_quality_preset_func $3 $4
		green "-> Will use '$OUTPUT' as output file"
		;;
		-fq)
		green "-> Starting to encode the $type in fixed-quant mode"
		display_quality_preset_func $3 $4
		green "-> Will use '$OUTPUT' as output file"
		;;
		-2p)
		green "-> Starting to encode the $type in 2-pass mode"
		display_quality_preset_func $3 $4
		green "-> Will use '/dev/null' as output for the first pass"
		green "-> Will use '$OUTPUT' as output file for the second pass"
		;;
		-3p)
		green "-> Starting to encode the $type in 3-pass mode"
		display_quality_preset_func $3 $4
		green "-> Will use '/dev/null' as output for the first & second pass"
		green "-> Will use '$OUTPUT' as output file for the third pass"
		;;
	esac
	;;
esac
echo ""

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

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

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

mencoder_exit() {
	if [ $? != 0 ]; then
		error "-> MEncoder has exited with a none-zero value!"
		error "-> Exiting in function: mencoder_exit()"
		rmconf
	fi
}

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

# Start encoding
case "$source" in
	dir|DIR|Dir)
	if [ -f "$BATCH" ]; then
		cp -f $BATCH $HOME
		. $BATCH
		rm -f $BATCH
		echo ""
		brown "-> Have a nice day ^_^"
		echo ""
		exit 0
	else
		error "-> File '$H264ENCDIR/batch$$' is missing!"
		error "-> Exiting..."
		rmconf
	fi
	;;
	file|FILE|File|dvd|DVD|Dvd)
	case "$1" in
		-1p|-fq)
		. $H264_1PFQ
		mencoder_exit
		;;
		-2p)
		. $H264_2P1
		mencoder_exit
		echo ""
		brown "=============================================================="
		echo ""
		color blue && printf "Starting the second pass of the encoding process in: " && counter
		color normal && echo ""
		. $H264_2P2
		mencoder_exit
		;;
		-3p)
		# Here's how it works...
		# 1-pass -> collects statistics and stores them to a file
		# 2-pass -> reads those statistics and bases ratecontrol on them
		# 3-pass -> simultaniously reads statistics, overwrites them
		#           and encodes the content
		. $H264_2P1
		mencoder_exit
		echo ""
		brown "=============================================================="
		echo ""
		color blue && printf "Starting the second pass of the encoding process in: " && counter
		color normal && echo ""
		. $H264_2P2
		mencoder_exit
		echo ""
		brown "=============================================================="
		echo ""
		color blue && printf "Starting the third pass of the encoding process in: " && counter
		color normal && echo ""
		. $H264_2P3
		mencoder_exit
		;;
	esac
	;;
esac

# Dump the second subtitle
# if selected
if [ ! -z "$subtitle2" ]; then
	echo ""
	green "-> Dumping the second subtitle, please wait..."
	sleep 2
	$priority_level $MENCODER $sourcetype $device $chapters $ofps $subtitle2 $aid -ovc copy -oac pcm -vobsubout "$(echo "$OUTPUT" | sed 's|\.avi|_sub2|')" -vobsuboutindex 1 -o /dev/null >/dev/null 2>&1
	if [ -e "$IDXFILE2" ]; then
		green "-> Done"
	else
	error "-> Failed!"
	fi
fi

# Dump the third subtitle
# if selected
if [ ! -z "$subtitle3" ]; then
	echo ""
	green "-> Dumping the third subtitle, please wait..."
	sleep 2
	$priority_level $MENCODER $sourcetype $device $chapters $ofps $subtitle3 $aid -ovc copy -oac pcm -vobsubout "$(echo "$OUTPUT" | sed 's|\.avi|_sub3|')" -vobsuboutindex 2 -o /dev/null >/dev/null 2>&1
	if [ -e "$IDXFILE3" ]; then
		green "-> Done"
	else
		error "-> Failed!"
	fi
fi

# Extract audio and video and then
# encode audio to neroAAC or Vorbis.
if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" -o "$avi_to_ogm" = "yes" ]; then
	case "$audiocodec" in
		aac+|AAC+|neroaac|neroAAC|vorbis|VORBIS)
		echo ""
		if [ "$avi_to_mp4" = "yes" -o "$avi_to_mkv" = "yes" ]; then
			green "-> Dumping video from the AVI file, please wait..."
			sleep 2
			$priority_level $MENCODER "$OUTPUT" -nosound -ovc copy -of rawvideo -o $CONFIGDIR/video.h264 >/dev/null 2>&1
			if [ -e "$CONFIGDIR/video.h264" ]; then
				green "-> Done"
			else
				error "-> Failed!"
			fi
			echo ""
		fi
		# Use a named pipe
		mkfifo $CONFIGDIR/audio.wav
		case "$audiocodec" in
			aac+|AAC+)
			green "-> Encoding audio with 'aacplusenc' to AAC+, please wait..."
			sleep 2
			$priority_level $AACPLUSENC $CONFIGDIR/audio.wav $CONFIGDIR/audio.aac $aacplusbr >/dev/null 2>&1 &
			$priority_level $MPLAYER "$OUTPUT" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1
			if [ -e "$CONFIGDIR/audio.aac" ]; then
				green "-> Done"
			else
				error "-> Failed!"
			fi
			;;
			neroaac|neroAAC)
			green "-> Encoding audio with 'neroAacEnc' to AAC(+), please wait..."
			sleep 2
			$priority_level $NEROAACENC -ignorelength $neroaacbr -if $CONFIGDIR/audio.wav -of $CONFIGDIR/audio.aac >/dev/null 2>&1 &
			$priority_level $MPLAYER "$OUTPUT" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1
			if [ -e "$CONFIGDIR/audio.aac" ]; then
				green "-> Done"
			else
				error "-> Failed!"
			fi
			;;
			vorbis|VORBIS)
			green "-> Encoding audio with 'oggenc' to Vorbis, please wait..."
			sleep 2
			$priority_level $OGGENC $vorbq $CONFIGDIR/audio.wav -o $CONFIGDIR/audio.ogg >/dev/null 2>&1 &
			$priority_level $MPLAYER "$OUTPUT" -vc null -vo null -nocache $channels -ao pcm:fast:file=$CONFIGDIR/audio.wav >/dev/null 2>&1
			if [ -e "$CONFIGDIR/audio.ogg" ]; then
				green "-> Done"
			else
				error "-> Failed!"
			fi
			;;
		esac
		rm -f $CONFIGDIR/audio.wav
		;;
	esac
fi


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

# AVI -> MKV conversion
if [ "$avi_to_mkv" = "yes" ]; then
	echo ""
	case "$audiocodec" in
		aac+|AAC+|neroaac|neroAAC|vorbis|VORBIS)
		green "-> Muxing audio and video into the MKV container, please wait..."
		;;
		*|"")
		green "-> Converting AVI file to the MKV container, please wait..."
		;;
	esac
	sleep 3
	if [ -f "$CONFIGDIR/mkvmuxing" ]; then
		. $CONFIGDIR/mkvmuxing >/dev/null 2>&1
		if [ -e "$MKVOUT" ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$CONFIGDIR/mkvmuxing' is missing!"
		error "-> Skipping AVI to MKV conversion!"
	fi
fi

# AVI -> MP4 conversion
if [ "$avi_to_mp4" = "yes" ]; then
	echo ""
	case "$audiocodec" in
		mp3|MP3|aac|AAC|nosound|NOSOUND|"")
		green "-> Converting AVI file to the MP4 container, please wait..."
		;;
		aac+|AAC+|neroaac|neroAAC|vorbis|VORBIS)
		green "-> Muxing audio and video into the MP4 container, please wait..."
		;;
	esac
	sleep 3
	if [ -f "$CONFIGDIR/mp4muxing" ]; then
		. $CONFIGDIR/mp4muxing >/dev/null 2>&1
		if [ -e "$MP4OUT" ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$CONFIGDIR/mp4muxing' is missing!"
		error "-> Skipping AVI to MP4 conversion!"
	fi
fi

# AVI -> TS conversion
if [ "$avi_to_ts" = "yes" ]; then
	echo ""
	case "$3" in
		bd40|bdhq40|bd41|bdhq41)
		green "-> Converting AVI file to a Blu-ray disc structure, please wait..."
		;;
		*)
		green "-> Converting AVI file to the TS container, please wait..."
		;;
	esac
	sleep 3
	if [ -f "$CONFIGDIR/tsmuxing" ]; then
		. $CONFIGDIR/tsmuxing >/dev/null 2>&1
		if [ -e "$TSOUTPUT" ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$CONFIGDIR/tsmuxing' is missing!"
		error "-> Skipping AVI to TS/Blu-ray conversion!"
	fi
fi

# AVI -> OGM conversion
if [ "$avi_to_ogm" = "yes" ]; then
	echo ""
	green "-> Converting AVI file to the OGM container, please wait..."
	sleep 3
	if [ -f "$CONFIGDIR/ogmmuxing" ]; then
		. $CONFIGDIR/ogmmuxing >/dev/null 2>&1
		if [ -e "$OGMOUT" ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$CONFIGDIR/ogmmuxing' is missing!"
		error "-> Skipping AVI to OGM conversion!"
	fi
fi

rm -rf $CONFIGDIR

# Report final file size
FSIZE_AVI=$(echo "scale=3; $(stat -c %s "$OUTPUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')
echo ""
green "-> AVI file size: $FSIZE_AVI MB"
if [ "$avi_to_mkv" = "yes" ]; then
	if [ -e "$MKVOUT" ]; then
		FSIZE_MKV=$(echo "scale=3; $(stat -c %s "$MKVOUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')
		green "-> MKV file size: $FSIZE_MKV MB"
	fi
fi

if [ "$avi_to_ts" = "yes" ]; then
	if [ -e "$TSOUTPUT" ]; then
		case "$3" in
			bd40|bdhq40|bd41|bdhq41)
			green "-> Blu-ray disc structure created in: $TSOUTPUT"
			;;
			*)
			FSIZE_TS=$(echo "scale=3; $(stat -c %s "$TSOUTPUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')
			green "-> TS file size: $FSIZE_TS MB"
			;;
		esac
	fi
fi

if [ "$avi_to_mp4" = "yes" ]; then
	if [ -e "$MP4OUT" ]; then
		FSIZE_MP4=$(echo "scale=3; $(stat -c %s "$MP4OUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')
		green "-> MP4 file size: $FSIZE_MP4 MB"
	fi
fi

if [ "$avi_to_ogm" = "yes" ]; then
	if [ -e "$OGMOUT" ]; then
		FSIZE_OGM=$(echo "scale=3; $(stat -c %s "$OGMOUT" 2>/dev/null)/1048576" | $BC -l | sed 's|^\.|0\.|')
		green "-> OGM file size: $FSIZE_OGM MB"
	fi
fi

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

exit 0
