#!/bin/bash
# $Id: divxenc, v 1.6.4, 2011/03/29, gn Exp $
# UUID: da4d1234-f789-11dc-a12a-7be96f0815e5
#
# Encode DVDs/video files to the FMP4/DIVX video format
# using MEncoder from MPlayer
#
# Copyright (C) 2008-2011 - Grozdan Nikolov
#
# divxenc 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.
#
# divxenc is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY ; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program ; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA

shopt -u expand_aliases
export PATH=$PATH:/usr/local/bin
version=1.6.4
configversion=16

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

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

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

# Create config dir
DIVXENCDIR=$HOME/.divxenc
test -d $DIVXENCDIR || mkdir -p $DIVXENCDIR

# In case divxenc did not remove its unique temp
# directories, remove them after 5 days
rm -rf $(find "$DIVXENCDIR" -name 'job*' -ctime +4 -type d) >/dev/null 2>&1

# Generate config file
genconfig_func() {
cat<<EOF>>$DIVXENCDIR/config
############## Configuration file for divxenc ##############
#
# Version: $configversion - do not modify or remove this line !!!
#
# This file is used by the divxenc script and contains the
# paths to 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! They will be ignored. Everything after
# a # sign is a comment.
#
# The EDITOR variable is used to set the preferred text editor for
# editing the config file through the terminal. It defaults to the
# nano text editor.
#
# The ALLOW_* variables can be used to enable or disable specific
# audio/video filters and containers. Setting a variable to 'n' will
# skip asking questions about the specific filter/container.
#
# The DEFOUTPUT variable can be used to provide a custom output directory
# for your encodes. If left empty, divxenc defaults to your home
# directory for output. If set, divxenc checks for it and will create
# the directory if it's not present. The DEFOUTPUT variable can be
# overwritten on the command line, meaning that if it's set but the
# user provides a path on the command line, that path will be used
# instead.
#
# The TEMPDIR variable below can be used to change the location
# of the temporary directory used by divxenc. If unset, divxenc
# will default to /home/username/.divxenc/job<PID>
# If used, you must provide the full path to a directory. If the
# directory is missing, divxenc will create it.
#
# The MPLAYEROPTS variable can be used to set other mplayer options.
# Be careful which options you use as they may introduce problems
# when using the script.
#
# The PRIORITY variable is used to set a 'nice' value for the encoding
# process. The values one can use are between -20 and 19 where -20
# will give the highest possible priority and 19 the least favorable
# one. Please note that only root can set/use a negative nice value.
# Regular users can only use/set values 0 to 19. If the variable is
# empty, then the default nice value of 0 is used. If the variable
# contains a negative value but the script is ran with normal user
# privileges, divxenc will print a notice and exit.
#
# The DVD_DEVICE and CDROM_DEVICE variables can be used to specify a
# preferred device to encode from. Note that only block devices are
# supported in these variables. CDROM_DEVICE is used for (S)VCD encoding
#
# divxenc can also send mails if configured to do so. There are four
# variables that need to be set in the mail settings below:
# MAILNOTIFY    # Enable/disable sending mail with y or n
# EMAIL         # The recepient's email address
# MAILSUBJ      # The mail's subject
# MAILMSG       # The actual mail message
#
# There is no need to add date/time to your email message as this is
# being done automatically.
#
# divxenc uses the 'mail' program which reads the mail settings from
# /home/username/.mailrc. If there's no such file present or it is
# configured incorrectly, mail sending will fail. A gmail example
# settings for .mailrc can look like this:
#
# set smtp-use-starttls
# set smtp=smtp://smtp.gmail.com:587
# set smtp-auth=login
# set smtp-auth-user=your-email@gmail.com
# set smtp-auth-password=your-password
#

EDITOR="nano"

# Video filters
ALLOW_VID_DEINTERLACE="y"
ALLOW_VID_INTERLACE="y"
ALLOW_VID_DEBLOCK="y"
ALLOW_VID_DELOGO="y"
ALLOW_VID_DENOISE="y"
ALLOW_VID_NOISE="y"
ALLOW_VID_DEBAND="y"
ALLOW_VID_UNSHARP="y"
ALLOW_VID_BRIGHTNESS="y"
ALLOW_VID_EQUALIZER="y"
ALLOW_VID_AUTOCROP="n"
ALLOW_VID_FPS_CONVERSION="y"
ALLOW_VID_SCALER_TUNING="n"
ALLOW_VID_DSIZE="y"
ALLOW_VID_EXPAND="y"
ALLOW_VID_COLORSPACE="n"
ALLOW_VID_ASPECT="y"

# Audio filters
ALLOW_AUD_CHANNELS="y"
ALLOW_AUD_RESAMPLE="y"
ALLOW_AUD_EQUALIZER="y"
ALLOW_AUD_NORMALIZE="y"
ALLOW_AUD_VOLUME="y"
ALLOW_AUD_PAN="y"

# Containers
ALLOW_MKV_MUXING="y"
ALLOW_MP4_MUXING="y"
ALLOW_OGM_MUXING="y"

# Misc
ALLOW_SAMPLE_ENCODING="y"
ALLOW_SCAN_MULTIPLE_VIDSTREAMS="y"
ALLOW_SCAN_MULTIPLE_AUDSTREAMS="y"

# Script/mplayer settings
DEFOUTPUT=""
TEMPDIR=""
PRIORITY="10"
MPLAYEROPTS="-noconfig all -loop 1"
DVD_DEVICE=""
CDROM_DEVICE=""

# Mail settings
MAILNOTIFY="n"
EMAIL=""
MAILSUBJ="[divxenc]: Encoding finished"
MAILMSG="This is a notification mail from the divxenc script to inform you that encoding has finished."

# Paths to executables
MPLAYER="$(which mplayer 2>/dev/null)"
MENCODER="$(which mencoder 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)"

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

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

if [ -f $DIVXENCDIR/config ]; then
	cver=$(grep '^# Version' $DIVXENCDIR/config | awk '{print $3}')
	if [[ $cver -lt $configversion ]]; then
		mv -f $DIVXENCDIR/config $DIVXENCDIR/config.old
		genconfig_func
		echo ""
		error "Important notice! The configuration file of divxenc located in"
		error "'$DIVXENCDIR/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 divxenc!"
		error "If no changes are made, just restart divxenc to get rid of"
		error "this notice."
		echo ""
		exit 1
	else
		source $DIVXENCDIR/config
	fi
else
	genconfig_func
	source $DIVXENCDIR/config
fi

send_email_func() {
	if [ -x "$MAIL" -a "$MAILNOTIFY" = "y" -a ! -z "$EMAIL" -a ! -z "$MAILSUBJ" -a ! -z "$MAILMSG" ]; then
		case "$1" in
			exp)
			echo "test -f $HOME/.mailrc && echo -e \"$MAILMSG\n\nEncoding finished on \$(date)\" | $MAIL -s \"$MAILSUBJ\" \"$EMAIL\""
			echo
			;;
			*)
			test -f $HOME/.mailrc && echo -e "$MAILMSG\n\nEncoding finished on $(date)" | $MAIL -s "$MAILSUBJ" "$EMAIL"
			;;
		esac
	fi
}

# Make temp dir
if [ -z "$TEMPDIR" ]; then
	TEMPDIR="$DIVXENCDIR/job$$"
	test -d "$TEMPDIR" || mkdir -p "$TEMPDIR"
else
	TEMPDIR="$TEMPDIR/job$$"
	if [ ! -d "$TEMPDIR" ]; then
		mkdir -p "$TEMPDIR" 2>/dev/null
		if [ $? != 0 ]; then
			error "-> Could not create custom temp dir: $TEMPDIR"
			exit 1
		fi
	fi
fi

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

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

# Delete temp directory
# on user error/exit
rmtemp() {
	rm -rf "$TEMPDIR" $DIVXENCDIR/batch$$
	exit 1
}

# Get devices
get_devices_func() {
	case "$1" in
		dvd)
		DEVTYPE="DVD"
		DEVSYM="/dev/dvd*"
		DEVOPT="-dvd-device"
		CONFIGDEV="$DVD_DEVICE"
		DEFAULTDEV="/dev/dvd"
		;;
		vcd)
		DEVTYPE="CD-ROM"
		DEVSYM="/dev/cdrom* /dev/cdrw*"
		DEVOPT="-cdrom-device"
		CONFIGDEV="$CDROM_DEVICE"
		DEFAULTDEV="/dev/cdrom"
		;;
	esac
	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 $DEVTYPE device(s)!"
	fi
	for i in $DEVSYM; do
		if [ -L $i ]; then
			green "-> Found symbolic link to $DEVTYPE device: $(ls -l $i | grep -o '/dev.*')"
		fi
	done
	if [ ! -z "$CONFIGDEV" ]; then
		if [ ! -b "$CONFIGDEV" ]; then
			error "-> Invalid device '$CONFIGDEV' in the config file!"
			echo
			rmtemp
		fi
		green "-> Using device '$CONFIGDEV' specified in the config file"
		device="$DEVOPT $CONFIGDEV"
	else
		echo
		printf "Specify the $DEVTYPE Device [default is $DEFAULTDEV]: "
		read -e dev
		if [ -z "$dev" -a ! -b "$DEFAULTDEV" ]; then
			error "-> No such block device: $DEFAULTDEV"
			rmtemp
		else
			if [ -z "$dev" ]; then
				device="$DEVOPT $DEFAULTDEV"
			else
				if [ ! -b "$dev" ]; then
					error "-> No such block device: $dev"
					rmtemp
				else
					device="$DEVOPT $dev"
				fi
			fi
		fi
	fi
}

case "$1" in
	"")
	echo "Usage: divxenc <options>"
	echo "Quick start: divxenc <passmode> -p <preset>"
	echo "Use 'divxenc -help' for more information"
	rmtemp
	;;
	-v)
	echo "divxenc $version"
	rmtemp
	;;
	-help)
	echo ""
	brown "+=======================================================+"
	brown "|     divxenc - the interactive shell script ripper     |"
	brown "+=======================================================+"
	echo ""
	echo "divxenc is a small script which uses the encoding utility"
	echo "MEncoder from MPlayer to encode a DVD or a video file to"
	echo "the high-quality MPEG-4 codec called FMP4/DIVX."
	echo "Note: this script supports only MPlayer/MEncoder 1.0rc2 or higher!"
	echo "For more information, read the man page of divxenc (man divxenc)"
	echo "or visit its Web site at http://divxenc.sourceforge.net"
	echo ""
	brown "Options"
	brown "~~~~~~~"
	echo " $(green "-1p")         Encode in one pass mode"
	echo ""
	echo " $(green "-2p")         Encode in two pass mode"
	echo ""
	echo " $(green "-3p")         Encode in three pass mode"
	echo ""
	echo " $(green "-fq")         Encode in fixed-quant mode"
	echo ""
	echo " $(green "<passmode> -p <preset>")"
	echo ""
	echo "             Use a predefined DivX quality preset, where <passmode> is the"
	echo "             desired encoding mode (-1p, -2p, -3p or -fq) and <preset> is the"
	echo "             desired quality preset to use (see below). Presets are supported"
	echo "             by all encoding modes. You can choose from 9 different presets:"
	echo ""
	echo "                   cp ---> Load a custom preset file (see example below)"
	echo "                   nq ---> Normal Quality preset"
	echo "                   hq ---> High Quality preset"
	echo "                   vhq --> Very High Quality preset (recommended)"
	echo "                   ehq --> Extreme High Quality preset (recommended)"
	echo "                   uhq --> Ultra High Quality preset (recommended)"
	echo "                   ihq --> Insane High Quality preset"
	echo "                   hwp --> Stand-alone HW compatible preset"
	echo "                   ps3 --> Sony PlayStation 3 preset"
	echo "                   ipod -> Apple iPod preset"
	echo ""
	echo "             Example of presets usage: divxenc -2p -p ehq"
	echo ""
	echo "             The above example will encode the DVD or input video file"
	echo "             in 2-pass mode using the Extreme High Quality (EHQ) preset"
	echo ""
	echo "             Load a custom preset from a file:"
	echo "             divxenc -2p -p cp /path/to/file/preset.cfg"
	echo ""
	echo "             Please have a look at the 'preset.cfg' file inside the"
	echo "             divxenc 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 divxenc package."
	echo ""
	echo " $(green "-b /path/to/file/batchfile")"
	echo ""
	echo "            Load a batch file generated by *this* script. This option"
	echo "            can be useful for testing or debugging the encoding parameters"
	echo "            and for batch encoding."
	echo ""
	echo " $(green "-e")         Edit the config file from within the terminal. This option defaults"
	echo "            to using the 'nano' text editor but one can manually set his"
	echo "            preferred editor in the EDITOR variable of the config file. The"
	echo "            config file is located in $DIVXENCDIR"
	echo ""
	echo " $(green "-r")         Reset configuration file. As of version 1.1.7, divxenc 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. It is also used for resetting the"
	echo "            config file in case the user has installed a required program"
	echo "            AFTER divxenc has generated its config file. If this is the case,"
	echo "            the config file will not contain the path to the newly installed"
	echo "            program so one has to reset the file in order to find it. This is"
	echo "            because the config file is generated/updated only once: if it's not"
	echo "            available on the user's system and during config version updates."
	echo "            The configuration file is located in $DIVXENCDIR/config"
	echo ""
	echo " $(green "-sc")        Perform a sanity check. This will check for the programs"
	echo "            required for the correct operation of this script and it"
	echo "            will print the status in a list. It will also display"
	echo "            which audio codecs are supported by MEncoder."
	echo ""
	echo " $(green "-scan")      Scan the DVD disc/video file/VCD 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 " $(green "-iso")       Create an ISO image of the DVD disc. Note that this option"
	echo "            does not do any stripping of specific titles, audio languages and/or"
	echo "            subtitles. It dumps the DVD content 1:1 to an ISO image."
	echo ""
	echo " $(green "-spr")       Calculate the Storage and Pixel Aspect Ratios (SAR/PAR) for"
	echo "            various resolutions."
	echo ""
	echo " $(green "-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 " $(green "-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 " $(green "-v")          Display version of this script and exit"
	echo ""
	echo " $(green "-help")       Display this help screen and exit"
	echo ""
	echo "TIP: if you don't want to use an option, instead of always answering"
	echo "with 'n', just press Enter."
	echo ""
	echo "For bug reporting, suggestions, comments, questions or if this script"
	echo "was useful to you, send me an e-mail at <neutrino8@gmail.com>"
	echo ""
	rmtemp
	;;
	-bpp|-bpb|-spr)
	# Bits per pixel/block, SAR and PAR calculation
	if [ ! -x "$BC" ]; then
		error "-> Checking for 'bc'... FAILED!"
		rmtemp
	fi
	case "$1" in
		-bpp)
		echo ""
		brown "+============================+"
		brown "| Bits Per Pixel Calculation |"
		brown "+============================+"
		echo ""
		;;
		-bpb)
		echo ""
		brown "+============================+"
		brown "| Bits Per Block Calculation |"
		brown "+============================+"
		echo ""
		;;
		-spr)
		echo
		brown "+==================================================+"
		brown "| Storage/Pixel Aspect Ratio (SAR/PAR) Calculation |"
		brown "+==================================================+"
		echo
		;;
	esac
	cal0() {
		echo "scale=0; $1" | $BC -l | sed 's|^\.|0\.|'
	}
	cal4() {
		echo "scale=4; $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 resolution [default is 720x576]: "
	read O_RES
	if [ -z "$O_RES" ]; then
		RES=720x576
		R_ASP=$(cal4 "720/576")
	else
		RES=$O_RES
		R_ASP=$(cal4 $(echo $O_RES | tr '[:alpha:]' '/'))
	fi
	case "$1" in
		-bpp|-bpb)
		printf "Provide the original unscaled but cropped resolution [WxH]: "
		read U_RES
		if [ -z "$U_RES" ]; then
			error "-> Cropped resolution value is required!"
			rmtemp
		fi
		;;
	esac
	printf "Provide the aspect ratio [16/9, 4/3, 1.3333, 1.7778... - default is 16/9]: "
	read AR
	if [ -z "$AR" ]; then
		A_RAT=16/9
	else
		A_RAT=$AR
	fi
	case "$1" in
		-bpp|-bpb)
		printf "Provide the video bitrate: "
		read V_BTR
		if [ -z "$V_BTR" ]; then
			error "-> Video bitrate is required!"
			rmtemp
		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=$(cal4 "$A_RAT")
		S_WID=$(cal0 "$U_WID*$E_RAT/$R_ASP")
		S_HEI=$U_HEI
		P_AR=$(cal4 "$S_WID/$S_HEI")
		;;
		-spr)
		U_WID=$(echo $RES | awk -Fx '{print $1}')
		U_HEI=$(echo $RES | awk -Fx '{print $2}')
		E_RAT=$(cal4 "$A_RAT")
		S_WID=$(cal0 "$U_WID*$E_RAT/$R_ASP")
		S_HEI=$U_HEI
		P_AR=$(cal4 "$S_WID/$S_HEI")
		;;
	esac
	echo
	case "$1" in
		-bpp)
		for ((WID=$U_WID; WID>=320; WID=WID-16)); do
			R_H=$(cal4 "$WID/$P_AR/16")
			HEI=$((16*$(round "$R_H")))
			BPP=$(cal4 "1000*$V_BTR/($WID*$HEI*$M_FPS)")
			BITRATE=$(cal0 "($WID*$HEI*$M_FPS*$BPP)/1000")
			PIX=$(($WID*$HEI))
			echo "Resolution: $(green "${WID}x$HEI") -- Total Pixels: $(green "$PIX") -- BPP: $(green $BPP) -- Bitrate based on BPP: $(green "$BITRATE kbps")"
		done
		;;
		-bpb)
		for ((WID=$U_WID; WID>=320; WID=WID-16)); do
			R_H=$(cal4 "$WID/$P_AR/16")
			HEI=$((16*$(round "$R_H")))
			BPB=$(cal4 "$V_BTR*1000/($M_FPS*($WID*$HEI)/(16*16))")
			PIX=$(($WID*$HEI))
			echo "Resolution: $(green "${WID}x$HEI") -- Total Pixels: $(green "$PIX") -- BPB: $(green $BPB)"
		done
		;;
		-spr)
		for ((WID=$U_WID; WID>=320; WID=WID-16)); do
			R_H=$(cal4 "$WID/$P_AR/16")
			HEI=$((16*$(round "$R_H")))
			SAR=$(cal4 "$WID/$HEI")
			PAR=$(cal4 "$E_RAT/$SAR")
			PIX=$(($WID*$HEI))
			echo "Resolution: $(green "${WID}x$HEI") -- Total Pixels: $(green "$PIX") -- SAR: $(green "$SAR:1") -- PAR: $(green "$PAR:1")"
		done
		;;
	esac
	echo
	rmtemp
	;;
	-b)
	if [ -z "$2" ]; then
		error "-> Option '-b' requires an input file!"
		error "-> Use: divxenc -help"
		rmtemp
	fi
	if [ ! -f "$2" ]; then
		error "-> No such file: '$2'"
		rmtemp
	fi
	source "$2"
	rmtemp
	;;
	-e)
	CFGFILE="$DIVXENCDIR/config"
	if [ ! -f "$CFGFILE" ]; then
		error "-> config file '$CFGFILE' does not exist!"
		error "-> Run: 'divxenc -r' to create it!"
		rmtemp
	fi
	if [ -z "$EDITOR" ]; then
		error "-> Variable 'EDITOR' in the config file is empty!"
		error "-> Please manually set your editor in the config file!"
		rmtemp
	fi
	if [ ! -x "$(which $EDITOR)" ]; then
		error "-> Specified text editor '$EDITOR' does not exist!"
		error "-> Either install it or manually set a different"
		error "   one in the config file!"
		rmtemp
	fi
	$EDITOR $CFGFILE
	rmtemp
	;;
	-r)
	green "-> Resetting the config file values"
	rm -f $DIVXENCDIR/config
	genconfig_func
	rmtemp
	;;
	-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 'lavc')" ]; then
			echo "-> FMP4/DivX video support in MEncoder........ $(error NO)"
		else
			echo "-> FMP4/DivX 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)"
		else
			echo "-> AC3 (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 "$FLAC" ]; then
		echo "-> Checking for 'flac'........................ $(green OK)"
	else
		echo "-> Checking for 'flac'........................ $(error "FAILED! [no support for FLAC 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
	echo
	echo "If you have installed a required program but the script"
	echo "can't find it, run 'divxenc -r' to reset the config file."
	echo
	rmtemp
	;;
	-scan)
	echo ""
	printf "Would you like to scan a video file or a DVD? [file/vcd/dvd]: "
	read scantype
	case "$scantype" in
		file|vcd)
		if [ ! -x "$BC" -o ! -x "$MPLAYER" ]; then
			error "-> bc or mplayer missing!"
			rmtemp
		fi
		case "$scantype" in
			file)
			printf "Provide the input video file: "
			read -e infile
			if [ -z "$infile" ]; then
				error "-> No input specified!"
				rmtemp
			elif [ ! -e "$infile" ]; then
				error "-> No such file: '$infile'"
				rmtemp
			fi
			echo
			green "-> Scanning the file..."
			;;
			vcd)
			get_devices_func vcd
			vcdurl="vcd://2"
			echo
			green "-> Scanning the VCD..."
			;;
		esac
		INFO="$TEMPDIR/info$$"
		$MPLAYER "$infile" $vcdurl $device $MPLAYEROPTS -identify -vo null -channels 6 -nocache -frames 1 2>/dev/null > "$INFO"
		echo ""
		echo "MPlayer Demuxer:   $(grep '^ID_DEMUXER' "$INFO" | tail -n 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 -n 1 | awk '{print $3}') ($(($(grep '^VIDEO:' "$INFO" | tail -n 1 | awk '{print $3}' | sed 's|x|*|'))) pixels)"
		echo "Video Aspect:      $(grep '^ID_VIDEO_ASPECT' "$INFO" | tail -n 1 | awk -F= '{print $2}'):1"
		echo "Video SAR:         $(echo "scale=4; $(grep '^VIDEO:' "$INFO" | tail -n 1 | awk '{print $3}' | sed 's|x|/|')" | $BC -l | sed 's|^\.|0\.|'):1"
		echo "Video PAR:         $(echo "scale=4; $(grep '^ID_VIDEO_ASPECT' "$INFO" | tail -n 1 | awk -F= '{print $2}')/($(grep '^VIDEO:' "$INFO" | tail -n 1 | awk '{print $3}' | sed 's|x|/|'))" | $BC -l | sed 's|^\.|0\.|'):1"
		echo "Video Length:      $(grep '^ID_LENGTH' "$INFO" | awk -F= '{print $2}') seconds or $(echo "scale=1; $(grep '^ID_LENGTH' "$INFO" | awk -F= '{print $2}')/60" | $BC -l | sed 's/^\./0\./') minutes (May not be accurate)"
		echo "Number Of Frames:  $(echo "scale=0; $(grep '^ID_LENGTH' "$INFO" | awk -F= '{print $2}') * $(grep '^ID_VIDEO_FPS' "$INFO" | awk -F= '{print $2}')" | $BC -l | awk -F. '{print $1}') (May not be accurate)"
		echo ""
		echo "Audio Codec:       $(grep '^ID_AUDIO_CODEC' "$INFO" | tail -n 1 | awk -F= '{print $2}')"
		echo "Audio Bitrate:     $(($(grep '^ID_AUDIO_BITRATE' "$INFO" | tail -n 1 | awk -F= '{print $2}')/1000)) kbps"
		echo "Audio Sample Rate: $(grep '^ID_AUDIO_RATE' "$INFO" | tail -n 1 | awk -F= '{print $2}') Hz"
		echo "Audio Channels:    $(grep '^ID_AUDIO_NCH' "$INFO" | tail -n 1 | awk -F= '{print $2}')"
		echo ""
		rmtemp
		;;
		dvd)
		# Scan the DVD disc and display
		# info about it, titles, chapters,
		# audio streams, subs, cells, etc...
		if [ ! -x "$LSDVD" -o ! -x "$MPLAYER" -o ! -x "$(which less 2>/dev/null)" ]; then
			error "-> 'lsdvd', 'mplayer' or 'less' missing!"
			rmtemp
		fi
		get_devices_func dvd
		echo
		green "-> Unlocking the DVD disc..."
		GET_TITLES="$($MPLAYER dvd://1 $device $MPLAYEROPTS -nosound -nocache -vo null -frames 1 2>/dev/null | grep -m1 'titles')"
		TITLE="$(echo $GET_TITLES | awk '{print $3}')"
		green "-> $GET_TITLES"
		green "-> $($LSDVD $(echo $device | awk '{print $2}') 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) rmtemp ;;
			""|*)
			error "-> Option unknown or not specified!"
			rmtemp
			;;
		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 $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			1) $LSDVD $title -d -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			2) $LSDVD $title -n -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			3) $LSDVD $title -c -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			4) $LSDVD $title -s -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			5) $LSDVD $title -P -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			6) $LSDVD $title -v -Oh $(echo $device | awk '{print $2}') 2>/dev/null | less ;;
			7) $LSDVD $title -x -Oh $(echo $device | awk '{print $2}') 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!"
				rmtemp
				;;
			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!"
				rmtemp
				;;
			esac
			DT="$($LSDVD $(echo $device | awk '{print $2}') 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="$HOME/$DISC_TITLE-$titlenum-audiostreams.$ext" ;;
					1) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-cells.$ext" ;;
					2) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-angles.$ext" ;;
					3) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-chapters.$ext" ;;
					4) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-subtitles.$ext" ;;
					5) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-palette.$ext" ;;
					6) EXPORT_FILE="$HOME/$DISC_TITLE-$titlenum-title+video.$ext" ;;
					7|all) EXPORT_FILE="$HOME/$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 $(echo $device | awk '{print $2}') 2>/dev/null > $EXPORT_FILE
				;;
				perl)
				store_func $opt
				info_func
				$LSDVD $title $info -Op $(echo $device | awk '{print $2}') 2>/dev/null > $EXPORT_FILE
				;;
				python)
				store_func $opt
				info_func
				$LSDVD $title $info -Oy $(echo $device | awk '{print $2}') 2>/dev/null > $EXPORT_FILE
				;;
				ruby)
				store_func $opt
				info_func
				$LSDVD $title $info -Or $(echo $device | awk '{print $2}') 2>/dev/null > $EXPORT_FILE
				;;
				xml)
				store_func $opt
				info_func
				$LSDVD $title $info -Ox $(echo $device | awk '{print $2}') 2>/dev/null > $EXPORT_FILE
				;;
			esac
			;;
		esac
		rmtemp
		;;
		*|"")
		error "-> You didn't specify the type!"
		rmtemp
		;;
	esac
	;;
	-iso)
	if [ ! -x "$BC" -o ! -x "$DD" -o ! -x "$MPLAYER" -o ! -x "$LSDVD" ]; then
		error "-> bc, dd, mplayer or lsdvd missing!"
		rmtemp
	fi
	interrupt_iso_func() {
		echo ""
		error "-> Exiting..."
		sleep 1
		rm -f "$OUTPUT" 2>/dev/null
		rmtemp
	}
	trap 'interrupt_iso_func' SIGHUP SIGTSTP SIGINT SIGQUIT SIGKILL SIGABRT SIGFPE SIGSEGV SIGTERM SIGPIPE SIGIO
	check_space_func() {
		HDSPACE="$(df -m "$(dirname "$OUTPUT")" | tail -n 1 | sed -r 's/^.*\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+[0-9]+%.*/\1/')"
		if [ $HDSPACE -lt 9216 ]; then
			echo ""
			error "-> You are running out of disk space in '$(dirname "$OUTPUT")'"
			error "-> Space left over: $HDSPACE MiB ($(echo "scale=3; $HDSPACE/1024" | $BC -l | sed 's|^\.|0\.|') GiB)"
			error "-> Please provide a different output directory!"
			echo ""
			rmtemp
		fi
	}
	echo ""
	brown "+=======================+"
	brown "| DVD ISO Image Dumping |"
	brown "+=======================+"
	get_devices_func dvd
	echo
	green "-> Unlocking the DVD disc..."
	$MPLAYER dvd://1 $device $MPLAYEROPTS -vo null -nosound -nocache -frames 1 >/dev/null 2>&1
	green "-> Scanning for DVD title name..."
	TITLE="$($LSDVD $(echo $device | awk '{print $2}') 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!"
			rmtemp
		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 MiB ($(echo "scale=3; $HDSPACE/1024" | $BC -l) GiB)"
	green "-> Dumping disc content to ISO image, please wait..."
	green "-> This can take a while..."
	echo ""
	if [ -x "$PV" ]; then
		$PV "$(echo $device | awk '{print $2}')" > "$OUTPUT"
	else
		$DD if="$(echo $device | awk '{print $2}')" bs=2048 conv=noerror,sync of="$OUTPUT" 2>/dev/null
	fi
	echo "-> Done"
	echo ""
	rmtemp
	;;
	-[1-3]p|-fq)
	case "$2" in
		-p)
		case "$3" in
			nq|hq|vhq|ehq|uhq|ihq|hwp|ps3|ipod) true ;;
			cp)
			if [ -z "$4" ]; then
				error "-> You have to load a custom preset file!"
				error "-> Use: divxenc $1 -p cp /path/to/file/preset.cfg"
				rmtemp
			fi
			if [ ! -f "$4" ]; then
				error "-> No such file: '$4'"
				rmtemp
			fi
			;;
			"")
			error "-> No preset specified!"
			error "-> Use: 'divxenc -help'"
			rmtemp
			;;
			*)
			error "-> Unknown preset: '$3'"
			error "-> Use: 'divxenc -help'"
			rmtemp
			;;
		esac
		;;
		"")
		error "-> No preset specified!"
		error "-> Use: 'divxenc -help'"
		rmtemp
		;;
		*)
		error "-> Unknown option: '$2'"
		error "-> Use: 'divxenc -help' for more info"
		rmtemp
		;;
	esac
	;;
	*)
	error "-> Unknown option: '$1'"
	error "-> Use: 'divxenc -help' for more info"
	rmtemp
	;;
esac

if [ "$3" = "ipod" ]; then
	if [ "$1" = "-fq" ]; then
		error "-> Fixed-quant encodings not supported for the iPod preset!"
		rmtemp
	fi
fi

# Check priority value and exit if we
# detect it's a negative one but user
# is running the script with regular
# privileges

if [ ! -z "$PRIORITY" ]; then
	if [ ! -z "$(echo $PRIORITY | grep '^\-')" -a "$UID" != "0" ]; then
		echo
		error "-> The encoding priority value in the config file is"
		error "   set to $PRIORITY but you are executing divxenc as regular"
		error "   user which does not have the ability to set/use such"
		error "   a value. Please modify the PRIORITY variable in the"
		error "   config file and set it to something between 0 and 19!"
		echo
		rmtemp
	fi
fi

# Informant function for displaying
# the selected quality preset
display_quality_preset_func() {
	case "$1" in
		cp)	green "-> Using custom preset file: '$2'" ;;
		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" ;;
		hwp)	green "-> Using \"Stand-alone HW compatible\" preset" ;;
		ps3)	green "-> Using \"Sony PlayStation 3\" preset" ;;
		ipod)	green "-> Using \"Apple iPod\" preset " ;;
	esac
}

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

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

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

if [ -z "$($MENCODER -ovc help 2>/dev/null | awk '{print $1}' | grep 'lavc')" ]; then
	error "-> Checking for FMP4/DivX support in MEncoder... FAILED!"
	rmtemp
fi

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

###############################################################
#### 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()"
		rmtemp
		;;
	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" $MPLAYEROPTS $device $vid -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > "$TEMPDIR/sourcefps"
	SOURCEFPS=$(grep '^ID_VIDEO_FPS' "$TEMPDIR/sourcefps" | tail -n 1 | awk -F= '{print $2}')
	rm -f "$TEMPDIR/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
}

# Deinterlace 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 FMP4/DivX
			# and add the ilpack filter to correctly
			# align chroma
			ildctme=":ildct:ilme"
			ilpack="ilpack=1,"
			# 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,"
			fi
		else
			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 --> Fast Yadif Deinterlacer"
				echo "9 --> Yadif & Linear Blend"
				echo "10 -> Yadif & Linear Interpolation"
				echo "11 -> Yadif & Cubic Interpolation"
				echo "12 -> Yadif & Median deint"
				echo "13 -> Yadif & FFmpeg deint"
				echo "14 -> Yadif & FIR Lowpass 5"
				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" ;;
					9) deintfilter="yadif=0,pp=lb,framestep=2,"; field_dominance="-field-dominance -1" ;;
					10) deintfilter="yadif=0,pp=li,framestep=2,"; field_dominance="-field-dominance -1" ;;
					11) deintfilter="yadif=0,pp=ci,framestep=2,"; field_dominance="-field-dominance -1" ;;
					12) deintfilter="yadif=0,pp=md,framestep=2,"; field_dominance="-field-dominance -1" ;;
					13) deintfilter="yadif=0,pp=fd,framestep=2,"; field_dominance="-field-dominance -1" ;;
					14) deintfilter="yadif=0,pp=l5,framestep=2,"; field_dominance="-field-dominance -1" ;;
					*)
					error "-> Unknown option: '$dfilter'"
					error "-> Exiting in function: video_deinterlace_func()"
					rmtemp
					;;
				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 ""
					rmtemp
					;;
					*)
					green "-> Detected $SOURCEFPS FPS"
					error "-> Only 50/59.940/60 FPS are supported!"
					error "-> Exiting in function: video_deinterlace_func()"
					echo ""
					rmtemp
					;;
				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 --> Fast Yadif Deinterlacer"
				echo "9 --> Yadif & Linear Blend"
				echo "10 -> Yadif & Linear Interpolation"
				echo "11 -> Yadif & Cubic Interpolation"
				echo "12 -> Yadif & Median deint"
				echo "13 -> Yadif & FFmpeg deint"
				echo "14 -> Yadif & FIR Lowpass 5"
				echo "15 -> Yadif & Fast Mcdeint (top fields)"
				echo "16 -> Yadif & Fast Mcdeint (bottom fields)"
				echo "17 -> Fast Yadif & Fast Mcdeint (top fields)"
				echo "18 -> Fast Yadif & Fast Mcdeint (bottom fields)"
				echo "19 -> Yadif & Medium Mcdeint (top fields)"
				echo "20 -> Yadif & Medium Mcdeint (bottom fields)"
				echo "21 -> Fast Yadif & Medium Mcdeint (top fields)"
				echo "22 -> Fast Yadif & Medium Mcdeint (bottom fields)"
				echo "23 -> Yadif & Slow Mcdeint (top fields)"
				echo "24 -> Yadif & Slow Mcdeint (bottom fields)"
				echo "25 -> Fast Yadif & Slow Mcdeint (top fields)"
				echo "26 -> Fast Yadif & Slow Mcdeint (bottom fields)"
				echo "27 -> Yadif & Slowest Mcdeint (top fields)"
				echo "28 -> Yadif & Slowest Mcdeint (bottom fields)"
				echo "29 -> Fast Yadif & Slowest Mcdeint (top fields)"
				echo "30 -> Fast Yadif & Slowest Mcdeint (bottom fields)"
				echo "31 -> Tfields"
				echo "32 -> Tfields & Fast Mcdeint (top fields)"
				echo "33 -> Tfields & Fast Mcdeint (bottom fields)"
				echo "34 -> Tfields & Medium Mcdeint (top fields)"
				echo "35 -> Tfields & Medium Mcdeint (bottom fields)"
				echo "36 -> Tfields & Slow Mcdeint (top fields)"
				echo "37 -> Tfields & Slow Mcdeint (bottom fields)"
				echo "38 -> Tfields & Slowest Mcdeint (top fields)"
				echo "39 -> 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=0,pp=lb," field_dominance="-field-dominance -1" ;;
					10) deintfilter="yadif=0,pp=li," field_dominance="-field-dominance -1" ;;
					11) deintfilter="yadif=0,pp=ci," field_dominance="-field-dominance -1" ;;
					12) deintfilter="yadif=0,pp=md," field_dominance="-field-dominance -1" ;;
					13) deintfilter="yadif=0,pp=fd," field_dominance="-field-dominance -1" ;;
					14) deintfilter="yadif=0,pp=l5," field_dominance="-field-dominance -1" ;;
					15) deintfilter="yadif=1,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					16) deintfilter="yadif=1,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					17) deintfilter="yadif=3,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					18) deintfilter="yadif=3,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					19) deintfilter="yadif=1,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					20) deintfilter="yadif=1,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					21) deintfilter="yadif=3,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					22) deintfilter="yadif=3,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					23) deintfilter="yadif=1,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					24) deintfilter="yadif=1,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					25) deintfilter="yadif=3,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					26) deintfilter="yadif=3,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					27) deintfilter="yadif=1,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					28) deintfilter="yadif=1,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					29) deintfilter="yadif=3,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					30) deintfilter="yadif=3,mcdeint=3:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					31) deintfilter="tfields=4,framestep=2,"; field_dominance="-field-dominance -1" ;;
					32) deintfilter="tfields=4,mcdeint=0:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					33) deintfilter="tfields=4,mcdeint=0:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					34) deintfilter="tfields=4,mcdeint=1:0:10,framestep=2,"; field_dominance="-field-dominance 0" ;;
					35) deintfilter="tfields=4,mcdeint=1:1:10,framestep=2,"; field_dominance="-field-dominance 1" ;;
					36) deintfilter="tfields=4,mcdeint=2:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					37) deintfilter="tfields=4,mcdeint=2:1:10,framestep=2,"; field_dominance="-field-dominance 1"; quiet="2>/dev/null" ;;
					38) deintfilter="tfields=4,mcdeint=3:0:10,framestep=2,"; field_dominance="-field-dominance 0"; quiet="2>/dev/null" ;;
					39) 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()"
					rmtemp
					;;
				esac
				;;
				2)
				quiet="2>/dev/null"
				echo ""
				brown "Available Deinterlacing Filters @ Double FPS"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "0 --> Yadif Deinterlacer"
				echo "1 --> Fast Yadif Deinterlacer"
				echo "2 --> Yadif & Fast Mcdeint (top fields)"
				echo "3 --> Yadif & Fast Mcdeint (bottom fields)"
				echo "4 --> Fast Yadif & Fast Mcdeint (top fields)"
				echo "5 --> Fast Yadif & Fast Mcdeint (bottom fields)"
				echo "6 --> Yadif & Medium Mcdeint (top fields)"
				echo "7 --> Yadif & Medium Mcdeint (bottom fields)"
				echo "8 --> Fast Yadif & Medium Mcdeint (top fields)"
				echo "9 --> Fast Yadif & Medium Mcdeint (bottom fields)"
				echo "10 -> Yadif & Slow Mcdeint (top fields)"
				echo "11 -> Yadif & Slow Mcdeint (bottom fields)"
				echo "12 -> Fast Yadif & Slow Mcdeint (top fields)"
				echo "13 -> Fast Yadif & Slow Mcdeint (bottom fields)"
				echo "14 -> Yadif & Slowest Mcdeint (top fields)"
				echo "15 -> Yadif & Slowest Mcdeint (bottom fields)"
				echo "16 -> Fast Yadif & Slowest Mcdeint (top fields)"
				echo "17 -> Fast Yadif & 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()"
					rmtemp
					;;
				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)
					green "-> Detected $SOURCEFPS FPS (Film)"
					calc_fps_func
					echo ""
					deintfps="48"
					deintofps="48"
					;;
					25.000|25.00)
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Film/Video)"
					calc_fps_func
					echo ""
					deintfps="50"
					deintofps="50"
					;;
					50.000|50.00)
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Double)"
					calc_fps_func
					echo ""
					deintfps="100"
					deintofps="100"
					;;
					100.000|100.00)
					green "-> Detected $SOURCEFPS FPS (PAL/SECAM Quad)"
					calc_fps_func
					echo ""
					deintfps="200"
					deintofps="200"
					;;
					23.976|23.97)
					green "-> Detected $SOURCEFPS FPS (NTSC Film)"
					calc_fps_func
					green "-> Note: NTSC FPS detection is not 100% reliable!"
					echo ""
					deintfps="48000/1001"
					deintofps="48000/1001"
					;;
					29.970|29.97)
					set_manual=yes
					green "-> Detected $SOURCEFPS FPS (NTSC Video)"
					calc_fps_func
					echo ""
					deintfps="60000/1001"
					deintofps="60000/1001"
					;;
					30.000|30.00)
					green "-> Detected $SOURCEFPS FPS (NTSC Video)"
					calc_fps_func
					echo ""
					deintfps="60"
					deintofps="60"
					;;
					59.940|59.94)
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					echo ""
					deintfps="120000/1001"
					deintofps="120000/1001"
					;;
					60.000|60.00)
					green "-> Detected $SOURCEFPS FPS (NTSC Double)"
					calc_fps_func
					echo ""
					deintfps="120"
					deintofps="120"
					;;
					119.880|119.88)
					green "-> Detected $SOURCEFPS FPS (NTSC Quad)"
					calc_fps_func
					echo ""
					deintfps="240000/1001"
					deintofps="240000/1001"
					;;
					""|*)
					green "-> Could not detect a supported frame rate!"
					green "-> You have to set it manually!"
					deint_custom_fps_func
					;;
				esac
				# Offer the user an option to set the
				# fps manually as detection of NTSC
				# is not very reliable! Damn the NTSC
				# crap!
				if [ "$set_manual" = "yes" ]; then
					printf "Continue (c) with the current setting or set FPS manually (m)? [c/m]: "
					read cfpsm
					case "$cfpsm" in
						c|C) true ;;
						m|M) deint_custom_fps_func ;;
						""|*)
						error "-> Option unknown or not specified!"
						error "-> Exiting in function: video_deinterlace_func()"
						rmtemp
						;;
					esac
				fi
				;;
				3)
				false
				;;
				*)
				error "-> Unknown deinterlacing method: '$deintmethod'"
				error "-> Exiting in function: video_deinterlace_func()"
				rmtemp
				;;
			esac
		fi
	fi
}

# Video interlacing
video_interlace_func() {
	if [ -z "$deintfilter" -a "$ildctme" != ":ildct:ilme" ]; then
		printf "Would you like to Interlace the encoding? [y/N]: "
		read intenc
		if [ "$intenc" = "y" -o "$intenc" = "Y" ]; then
			ildctme=":ildct:ilme"
			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) false ;;
				*)
				error "-> Unknown interlace option: '$intmeth'"
				rmtemp
				;;
			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
					rmtemp
					;;
					*)
					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 ""
					rmtemp
					;;
				esac
				;;
			esac
		fi
	fi
}

# Postprocessing
video_delogo_func() {
	printf "Would you like to Delogo the $type? [y/N]: "
	read db
	if [ "$db" = "y" -o "$db" = "Y" ]; then
		HANDLE="$TEMPDIR/fifofile"
		wd=10
		hd=10
		xd=10
		yd=10
		wv=25
		hv=25
		xv=1
		yv=1
		mkfifo $HANDLE
		$MPLAYER -quiet -slave -input file="$HANDLE" -vf rectangle="$wv":"$hv":"$xv":"$yv" "$infile" >/dev/null 2>&1 &
		while [ 0 ]; do
			echo ""
			brown "Delogo Video Filter"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo "Suppresses a TV station logo by a simple" 
			echo "interpolation of the surrounding pixels." 
			echo "Just set a rectangle covering the logo"
			echo "and watch it disappear (and sometimes" 
			echo "something even uglier appear - your mileage"
			echo "may vary)."
			echo "Specify the positon and size:"
			echo ""
			echo "0 -> Change X-Pos."
			echo "1 -> Change Y-Pos."
			echo "2 -> Change Width"
			echo "3 -> Change Height"
			echo "4 -> Finish"
			echo ""
			printf "Select a Delogo function: "
			read delogoval
			case "$delogoval" in
				0)
				while [ 0 ]; do
					clear
					echo ""
					brown "Delogo Video Filter - X-Position"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change X-Pos=$xv  [default is $xd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$xd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					xd=$v
					let xv=$xv+$v
					echo "change_rectangle 2 $v" >> $HANDLE
				done
				;;
				1)
				while [ 0 ]; do
					clear
					echo ""
					brown "Delogo Video Filter - Y-Position"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change Y-Pos=$yv  [default is $yd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$yd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					yd=$v
					let yv=$yv+$v
					echo "change_rectangle 3 $v" >> $HANDLE	
				done
				;;
				2)
				while [ 0 ]; do
					clear
					echo ""
					brown "Delogo Video Filter - Width"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change Width=$wv  [default is $wd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$wd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					wd=$v
					let wv=$wv+$v
					echo "change_rectangle 0 $v" >> $HANDLE
				done
				;;
				3)
				while [ 0 ]; do
					clear
					echo ""
					brown "Delogo Video Filter - Height"
					brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
					printf "Change Height=$hv  [default is $hd, q to finish]: "
					read v
					if [ -z "$v" ]; then
						v=$hd
					elif [ "$v" = "q" -o "$v" = "Q" ]; then
						break;
					fi
					hd=$v
					let hv=$hv+$v
					echo "change_rectangle 1 $v" >> $HANDLE
				done
				;;
				4)
				break;
				;;
			esac
		done
		echo "quit" >> $HANDLE
		delogofilter="delogo=$xv:$yv:$wv:$hv:1,"
	fi
}

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 the postprocessing filters" 
		echo ""
		printf "Select a Deblock/Dering filter [default is 0]: "
		read dbfilter
		case "$dbfilter" in
			0|"")
			printf "Specify the Quality level [0-6 - default is 3]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="spp=3,"
			else
				deblockfilter="spp=$dbqlevel,"
			fi
			;;
			1)
			printf "Specify the Quality level [0-8 - default is 2]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="uspp=2,"
			else
				deblockfilter="uspp=$dbqlevel,"
			fi
			;;
			2)
			printf "Specify the Quality level [0-6 - default is 4]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="fspp=4,"
			else
				deblockfilter="fspp=$dbqlevel,"
			fi
			;;
			3)
			printf "Specify the Quality Quantization parameter [0-31 - default is 3]: "
			read dbqlevel
			if [ -z "$dbqlevel" ]; then
				deblockfilter="pp7=3,"
			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
				deblockfilter="pp=ha:164:7:c/va:c/dr:c,"
			else
				deblockfilter="pp=ha:$dfv:c/va:c/dr:c,"
			fi
			;;
			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
				deblockfilter="pp=ha:164:7:c/va:c,"
			else
				deblockfilter="pp=ha:$dfv:c/va:c,"
			fi
			;;
			6)
			deblockfilter="pp=dr:c,"
			;;
			7) false ;;
			*)
			error "-> Unknown deblock/dering option: '$dbfilter'"
			error "-> Exiting in function: video_deblock_func()"
			rmtemp
			;;
		esac
	fi
}

# Denoising
video_denoise_func() {
	printf "Would you like to Denoise the $type? [y/N]: "
	read denoise
	if [ "$denoise" = "y" -o "$denoise" = "Y" ]; then
		echo ""
		brown "3D Denoiser                     HQ 3D Denoiser"
		brown "~~~~~~~~~~~                     ~~~~~~~~~~~~~~"
		echo "0 --> denoise3d: weak           5 --> hqdn3d: weak"
		echo "1 --> denoise3d: medium         6 --> hqdn3d: medium"
		echo "2 --> denoise3d: strong         7 --> hqdn3d: strong"
		echo "3 --> denoise3d: extra strong   8 --> hqdn3d: extra strong"
		echo "4 --> denoise3d: user defined   9 --> hqdn3d: user defined"
		echo ""
		brown "Overcomplete Wavelet Denoiser   Temporal Denoiser"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~   ~~~~~~~~~~~~~~~~~"
		echo "10 -> ow: weak                  15 -> tn: weak"
		echo "11 -> ow: medium                16 -> tn: medium"
		echo "12 -> ow: strong                17 -> tn: strong"
		echo "13 -> ow: extra strong          18 -> tn: extra strong"
		echo "14 -> ow: user defined          19 -> tn: user defined"
		echo ""
		echo "                20 -> Skip denoising"
		echo ""
		printf "Select a Denoise filter and strength [default is 6]: "
		read dnfilt
		case "$dnfilt" 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
			;;
			5) denoisefilter="hqdn3d=3:2:5," ;;
			6|"") denoisefilter="hqdn3d=4:3:6," ;;
			7) denoisefilter="hqdn3d=7:6:9," ;;
			8) denoisefilter="hqdn3d=10:9:12," ;;
			9)
			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
			;;
			10) denoisefilter="ow=3:1.2:1.2," ;;
			11) denoisefilter="ow=6:1.2:1.2," ;;
			12) denoisefilter="ow=9:1.2:1.2," ;;
			13) denoisefilter="ow=12:1.2:1.2," ;;
			14)
			printf "Specify the Denoise values [default is 5:1.2:1.2]: "
			read dnvalues
			if [ -z "$dnvalues" ]; then
				denoisefilter="ow=5:1.2:1.2,"
			else
				denoisefilter="ow=$dnvalues,"
			fi
			;;
			15) denoisefilter="pp=tn:32:64:128:c," ;;
			16) denoisefilter="pp=tn:64:128:256:c," ;;
			17) denoisefilter="pp=tn:128:256:512:c," ;;
			18) denoisefilter="pp=tn:256:512:1024:c," ;;
			19)
			printf "Specify the Denoise values [default is 64:128:256]: "
			read dnvalues
			if [ -z "$dnvalues" ]; then
				denoisefilter="pp=tn:64:128:256:c,"
			else
				denoisefilter="pp=tn:$dnvalues:c,"
			fi
			;;
			20) false ;;
			*)
			error "-> Unknown denoise option: '$dnfilt'"
			error "-> Exiting in function: video_denoise_func()"
			rmtemp
			;;
		esac
	fi
}

# Noise filter
video_noise_func() {
	if [ -z "$denoisefilter" ]; then
		printf "Would you like to add Noise to the $type? [y/N]: "
		read noise
		if [ "$noise" = "y" -o "$noise" = "Y" ]; then
			echo
			brown "Noise Types"
			brown "~~~~~~~~~~~"
			echo "u -> Uniform noise"
			echo "t -> Temporal noise"
			echo "a -> Averaged temporal noise"
			echo "h -> High quality"
			echo "p -> Mix random noise with a (semi)regular pattern"
			echo
			echo "Example of filter's usage: 8ha:2t"
			echo
			echo "The first value sets the Luma amount and noise type(s)"
			echo "while the second one does so for Chroma. The Luma/Chroma"
			echo "ranges are between 0 and 100 with 0 completely disabling"
			echo "filtering on the Luma and/or Chroma planes. Mixing different"
			echo "types of noise is possible as shown in the above example."
			echo
			printf "Specify the Noise filter parameters [press 'Enter' to skip]: "
			read noiseparam
			if [ ! -z "$noiseparam" ]; then
				noisefilter=",noise=$noiseparam"
			fi
		fi
	fi
}

# Debanding filter
video_deband_func() {
	printf "Would you like to Deband the $type? [y/N]: "
	read deband
	if [ "$deband" = "y" -o "$deband" = "Y" ]; then
		printf "Specify the Deband filter strength and radius [default is 1.2:16]: "
		read debandparam
		if [ -z "$debandparam" ]; then
			debandfilter="gradfun=1.2:16,"
		else
			debandfilter="gradfun=$debandparam,"
		fi
	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()"
			rmtemp
			;;
		esac
	fi
}

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

# Software EQ filter. Mutually
# exclusive with the above one
video_equalizer_func() {
	if [ -z "$brightnessfilter" ]; then
		printf "Would you like to use the Software Equalizer filter? [y/N]: "
		read softeq
		if [ "$softeq" = "y" -o "$softeq" = "Y" ]; then
			echo
			brown "Video Software Equalizer Filter"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "The eq2 software equalizer filter operates just like"
			echo "hardware equalizers. In addition to simple brightness"
			echo "and contrast adjustments, it also allows for gamma and"
			echo "saturation corrections. If you're not familiar with"
			echo "its parameters, I suggest consulting the man page of"
			echo "MPlayer and look for the eq2 filter."
			echo ""
			echo "The format is as follows:"
			echo "gamma:contrast:brightness:saturation:rg:gg:bg:weight"
			echo
			printf "Specify the eq2 values [default is filter defaults]: "
			read eq2
			if [ -z "$eq2" ]; then
				eq2filter=",eq2"
			else
				eq2filter=",eq2=$eq2"
			fi
		fi
	fi
}

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

# Subtitles
get_subtitles_func() {
	echo ""
	green "-> Scanning for subtitles..."
	$MPLAYER "$sourcetype" $MPLAYEROPTS $device -nosound -vo null -frames 1 -nocache 2>/dev/null > "$TEMPDIR/subs"
	SUBS=$(grep '^subtitle' "$TEMPDIR/subs")
	rm -f "$TEMPDIR/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_align_func() {
	echo
	brown "Subtitle Alignment"
	brown "~~~~~~~~~~~~~~~~~~"
	echo "0 -> Original position"
	echo "1 -> Align at top (original behavior)"
	echo "2 -> Align at center"
	echo "3 -> Align at bottom"
	echo
	printf "Select the Subtitle alignment [default is 1]: "
	read subalign
	case "$subalign" in
		0)	spualign="-spualign -1" ;;
		1|"")	spualign="-spualign 0" ;;
		2)	spualign="-spualign 1" ;;
		3)	spualign="-spualign 2" ;;
		*)
		error "-> Unknown option: '$subalign'"
		error "-> Exiting in function: video_subtitles_align_func()"
		rmtemp
		;;
	esac
}

video_subtitles_codepage_func() {
	printf "Specify a Codepage for the subtitle [press 'Enter' to skip]: "
	read subcodepage
	if [ ! -z "$subcodepage" ]; then
		subcp="-subcp $subcodepage"
	fi
}

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|dir|vcd)
			echo ""
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "0 -> Hardcode the given subtitle into the video"
			echo "1 -> Import subtitle(s) into the MKV/MP4/OGM containers"
			echo "2 -> Skip subtitle inclusion"
			echo ""
			printf "Select the Subtitle Method [default is 0]: "
			read submethod
			case "$submethod" in
				0|"")
				printf "Provide the subtitle file [press 'Enter' to skip]: "
				read -e subfile
				if [ ! -z "$subfile" ]; then
					if [ ! -f "$subfile" ]; then
						echo
						green "-> No such file: '$subfile'"
						green "-> Skipping subtitle"
						echo
					else
						video_subtitles_codepage_func
						case "${subfile##*.}" in
							idx|IDX|sub|SUB)
							video_subtitles_align_func
							;;
						esac
						subtitle[1]="-sub \"$subfile\" -subfont-autoscale 1 $spualign $subcp"
					fi
				fi
				;;
				1)
				for i in {1..3}; do
					printf "Provide the subtitle file (sub $i) [press 'Enter' to skip]: "
					read -e subfile[$i]
					if [ ! -z "${subfile[$i]}" ]; then
						if [ ! -f "${subfile[$i]}" ]; then
							echo
							green "-> No such file: '${subfile[$i]}'"
							green "-> Skipping subtitle $i"
							echo
						else
							EXTSUB[$i]="${subfile[$i]}"
						fi
					fi
				done
				;;
				2)
				nosub="-nosub"
				;;
				*)
				error "-> Unknown option: '$submethod'"
				error "-> Exiting in function: video_subtitles_func()"
				rmtemp
				;;
			esac
			;;
			dvd)
			echo ""
			brown "Subtitle Methods"
			brown "~~~~~~~~~~~~~~~~"
			echo "0 -> Hardcode a DVD subtitle into the movie"
			echo
			echo "1 -> Hardcode an external subtitle into the movie"
			echo
			echo "2 -> Dump DVD subtitle(s) to file(s) on disk"
			echo "     and optionally import them into MKV/MP4"
			echo
			echo "3 -> Import external subtitle(s) into MKV/MP4/OGM"
			echo
			echo "4 -> Skip subtitle inclusion"
			echo ""
			printf "Select the Subtitle Method [default is 2]: "
			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
					echo
					green "-> You have to specify the Subtitle ID number, not the language code!"
					green "-> Skipping subtitle"
					echo
				else
					if [ ! -z "$subid" ]; then
						video_subtitles_align_func
						subtitle[1]="-sid $subid -spuaa 4 -spugauss 0.7 $spualign"
					fi
				fi
				;;
				1)
				printf "Provide the subtitle file [press 'Enter' to skip]: "
				read -e exthcsub
				if [ ! -z "$exthcsub" ]; then
					if [ ! -e "$exthcsub" ]; then
						echo
						error "-> No such file: '$exthcsub'"
						error "-> Skipping..."
						echo
					else
						video_subtitles_codepage_func
						case "${exthcsub##*.}" in
							idx|IDX|sub|SUB)
							video_subtitles_align_func
							;;
						esac
						subtitle[1]="-sub \"$exthcsub\" -subfont-autoscale 1 $spualign $subcp"
					fi
				fi
				;;
				2|"")
				# First subtitle gets dumped during
				# encoding time, second one after
				# encoding has finished
				get_subtitles_func
				for i in {1..3}; do
					printf "Specify the Subtitle ID number (sub $i) [press 'Enter' to skip]: "
					read subid[$i]
					if [ ! -z "$(echo ${subid[$i]} | grep '[a-zA-Z]')" ]; then
						echo
						green "-> You have to specify the Subtitle ID number, not the language code!"
						green "-> Skipping subtitle $i"
						echo
					else
						if [ ! -z "${subid[$i]}" ]; then
							subtitle[$i]="-sid ${subid[$i]}"
							vobsubout[$i]="-vobsubout \"${OUTPUT%.*}_sub$i\" -vobsuboutindex $(($i-1))"
							IDXFILE[$i]="${OUTPUT%.*}_sub$i.idx"
							SUBFILE[$i]="${OUTPUT%.*}_sub$i.sub"
						fi
					fi
				done
				;;
				3)
				for i in {1..3}; do
					printf "Provide the subtitle file (sub $i) [press 'Enter' to skip]: "
					read -e extsub[$i]
					if [ ! -z "${extsub[$i]}" ]; then
						if [ ! -e "${extsub[$i]}" ]; then
							echo
							error "-> No such file: '${extsub[$i]}'"
							error "-> Skipping..."
							echo
						else
							EXTSUB[$i]="${extsub[$i]}"
						fi
					fi
				done
				;;
				4)
				nosub="-nosub"
				;;
				*)
				error "-> Unknown subtitle method option: '$submethod'"
				error "-> Exiting in function: video_subtitles_func()"
				rmtemp
				;;
			esac
			;;
		esac
	else
		nosub="-nosub"
	fi
}

# Video cropping
video_crop_func() {
	case "$source" in
		dir)
		echo
		error "-> Cropping in directory batch encoding mode is not"
		error "   recommended unless you know what you're doing!"
		;;
	esac
	printf "Specify the Crop rounding value [4/8/16 - default is 16]: "
	read cropround
	if [ -z "$cropround" ]; then
		cropdetect="cropdetect=24:16"
	else
		cropdetect="cropdetect=24:$cropround"
	fi
	echo
	green "-> Detecting crop values with 'cropdetect'..."
	$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -identify -vo null -ao null -frames 1 -nocache 2>/dev/null > "$TEMPDIR/cropdetect"
	VLENGTH=$(grep "^ID_LENGTH" "$TEMPDIR/cropdetect" | cut -f '2' -d '=' | cut -f '1' -d '.')
	case "$source" in
		dvd|vcd)
		if [ ! -z "$($MPLAYER -vc help 2>/dev/null | grep 'libmpeg2')" ]; then
			MPEGVC="-vc mpeg12"
		fi
		CROPOPTS="-frames 30 -sstep $(($VLENGTH/30)) $MPEGVC" ;;
		*) CROPOPTS="-frames 500 -ss $(($VLENGTH/2))" ;;
	esac
	GETCROP=$($MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -vf $cropdetect -ao null -nocache -vo null $CROPOPTS 2>/dev/null | tr '\r' '\n' | grep "crop=" | tail -n 1 | awk '{print $9}' | sed 's/crop=//g; s/).//g')
	rm -f "$TEMPDIR/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
	CROPDETERMINED="n"
	while [ "$CROPDETERMINED" != "y" ]; do
		if [ -z "$cropvalues" ]; then
			printf "Specify the crop values [default is $GETCROP]: "
		else
			printf "Specify the crop values [last try: "$cropvalues"]: "
		fi
		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" $MPLAYEROPTS $device $vid -vf rectangle=$crop_preview -nocache -nosound -ss $startpos >/dev/null 2>&1 & PID=$!; sleep 15; kill -KILL $PID;
				$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid -vf rectangle=$crop_preview -nocache -ao null -ss $startpos -endpos 15 >/dev/null 2>&1
			fi
		fi
		printf "Are you satisfied with the crop area? [y/N]: "
		read CROPDETERMINED
	done
}

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

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

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

set_output_filename_func() {
	case "$source" in
		file|vcd)
		printf "Provide a name for the Output File [default is DivX-$$]: "
		read -e outfile
		if [ -z "$outfile" ]; then
			OUTPUT="DivX-$$"
		else
			OUTPUT="$outfile"
		fi
		;;
		dvd)
		green "-> Scanning for DVD title name..."
		GET_TITLE=$($LSDVD $(echo $device | awk '{print $2}') 2>/dev/null | grep '^Disc Title:' | sed -e 's|Disc Title: ||' -e 's|_| |g')
		if [ ! -z "$GET_TITLE" ]; then
			SET_TITLE="$GET_TITLE"
		else
			SET_TITLE="DivX-$$"
		fi
		echo
		printf "Provide a name for the Output File [default is $SET_TITLE]: "
		read -e outfile
		if [ -z "$outfile" ]; then
			OUTPUT="$SET_TITLE"
		else
			OUTPUT="$outfile"
		fi
		;;
	esac
	test_write_func() {
		TESTFILE="$DEFPATH/.testfile$$"
		touch "$TESTFILE" 2>/dev/null
		if [ $? != 0 ]; then
			echo
			error "-> Output directory '$DEFPATH' is not writable!"
			error "-> Exiting in sub-function: test_write_func()"
			echo
			rmtemp
		else
			rm -f "$TESTFILE" 2>/dev/null
		fi
	}
	if [ ! -z "$DEFOUTPUT" ]; then
		if [ ! -z "$(echo "$OUTPUT" | grep '^/')" ]; then
			if [ ! -d "$(dirname "$OUTPUT")" ]; then
				mkdir -p "$(dirname "$OUTPUT")" 2>/dev/null
				if [ $? != 0 ]; then
					echo
					error "-> Could not create output dir '$(dirname "$OUTPUT")'"
					error "-> Maybe a permissions problem?"
					error "-> Exiting in function: set_output_filename_func()"
					echo
					rmtemp
				else
					DEFPATH="$(dirname "$OUTPUT")"
				fi
			else
				DEFPATH="$(dirname "$OUTPUT")"
				test_write_func
			fi
		else
			if [ ! -d "$DEFOUTPUT" ]; then
				mkdir -p "$DEFOUTPUT" 2>/dev/null
				if [ $? != 0 ]; then
					echo
					error "-> Could not create default output dir '$DEFOUTPUT'"
					error "-> Defaulting to '$HOME'"
					echo
					DEFPATH="$HOME"
				else
					DEFPATH="$DEFOUTPUT"
				fi
			else
				DEFPATH="$DEFOUTPUT"
				test_write_func
			fi
		fi
	else
		if [ ! -z "$(echo "$OUTPUT" | grep '^/')" ]; then
			if [ ! -d "$(dirname "$OUTPUT")" ]; then
				mkdir -p "$(dirname "$OUTPUT")" 2>/dev/null
				if [ $? != 0 ]; then
					echo
					error "-> Could not create output dir '$(dirname "$OUTPUT")'"
					error "-> Defaulting to '$HOME'"
					echo
					DEFPATH="$HOME"
				else
					DEFPATH="$(dirname "$OUTPUT")"
				fi
			else
				DEFPATH="$(dirname "$OUTPUT")"
				test_write_func
			fi
		else
			DEFPATH="$HOME"
		fi
	fi
	OUTPUT="$DEFPATH/$(basename "${OUTPUT%.*}.avi")"
}

backup_file_func() {
	case "$1" in
		files|chaps)
		case "$1" in
			files)
			EXTFILE="$OUTPUT"
			;;
			chaps)
			EXTFILE="$CHAPTERSFILE"
			;;
		esac
		if [ -e "$EXTFILE" ]; then
			counter=1
			while [ -e "$EXTFILE.$counter.old" ]; do
				counter=$(($counter+1))
			done
			BKOUT="$EXTFILE.$counter.old"
			echo
			green "-> Renaming exisiting file to '$(basename "$BKOUT")'"
			case "$1" in
				files)
				case "$source" in
					file|dir|vcd) echo ;;
				esac
				;;
				chaps)
				echo
				;;
			esac
			mv -f "$EXTFILE" "$BKOUT"
		fi
		;;
		subs)
		if [ ! -z "${vobsubout[*]}" ]; then
			for i in {1..3}; do
				if [ -e "${IDXFILE[$i]}" -o -e "${SUBFILE[$i]}" ]; then
					echo
					break
				fi
			done
		fi
		counter=1
		for i in {1..3}; do
			while [ -e "${IDXFILE[$i]}.$counter.old" -o -e "${SUBFILE[$i]}.$counter.old" ]; do
				counter=$(($counter+1))
			done
			if [ -e "${IDXFILE[$i]}" ]; then
				green "-> Renaming existing file to '$(basename "${IDXFILE[$i]}.$counter.old")'"
				mv -f "${IDXFILE[$i]}" "${IDXFILE[$i]}.$counter.old"
			fi
			if [ -e "${SUBFILE[$i]}" ]; then
				green "-> Renaming existing file to '$(basename "${SUBFILE[$i]}.$counter.old")'"
				mv -f "${SUBFILE[$i]}" "${SUBFILE[$i]}.$counter.old"
			fi
		done
		;;
	esac
}

check_diskspace_func() {
	HDOUT="$(df -m "$(dirname "$OUTPUT")" | tail -n 1 | sed -r 's/^.*\s+[0-9]+\s+[0-9]+\s+([0-9]+)\s+[0-9]+%.*/\1/')"
	HDCONF="$(df -m "$TEMPDIR" | tail -n 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 divxenc!"
		echo ""
		echo "This could be a problem if you want to convert"
		echo "the final encode to Matroska, OGM or to the MP4"
		echo "container. It is recommended to free up some disk"
		echo "space or provide a different destination output"
		echo "directory before continuing with the encoding"
		echo "process if you intend to do some of the above"
		echo "tasks!"
		echo ""
		error "Space left over in '$(dirname "$OUTPUT")': $HDOUT MiB"
		error "Space left over in '$TEMPDIR': $HDCONF MiB"
		echo ""
		printf "#### Press 'Enter' to continue, CTRL+C to exit ####"
		read continue_encoding
		case "$source" in
			file|dir) echo ;;
		esac
	fi
}

video_filters_func() {
	if [ "$vfilters" = "y" -o "$vfilters" = "Y" ]; then
		echo
		brown "+==================================+"
		brown "| Pre/Postprocessing Video Filters |"
		brown "+==================================+"
		echo
		test "$ALLOW_VID_DEINTERLACE" = "y" && video_deinterlace_func
		test "$ALLOW_VID_INTERLACE" = "y" && video_interlace_func
		test "$ALLOW_VID_DEBLOCK" = "y" && video_deblock_func
		test "$ALLOW_VID_DELOGO" = "y" && video_delogo_func
		test "$ALLOW_VID_DENOISE" = "y" && video_denoise_func
		test "$ALLOW_VID_NOISE" = "y" && video_noise_func
		test "$ALLOW_VID_DEBAND" = "y" && video_deband_func
		test "$ALLOW_VID_UNSHARP" = "y" && video_unsharp_func
		test "$ALLOW_VID_BRIGHTNESS" = "y" && video_brightness_func
		test "$ALLOW_VID_EQUALIZER" = "y" && video_equalizer_func
	fi
	if [ "$ALLOW_VID_AUTOCROP" = "y" ]; then
		case "$source" in
			file|dvd|vcd)
			video_crop_func
			;;
		esac
	else
		printf "Would you like to Crop the $type? [y/N]: "
		read cropping
		if [ "$cropping" = "y" -o "$cropping" = "Y" ]; then
			video_crop_func
		fi
	fi
}

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

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

printf "Select the Input type [file/dir/dvd/vcd]: "
read source
case "$source" in
	file)
	type="Video file"
	printf "Provide the Input Video File: "
	read -e infile
	if [ ! -f "$infile" ]; then
		error "-> No such file: '$infile'"
		rmtemp
	fi
	set_output_filename_func
	check_diskspace_func
	sourcetype="$infile"
	if [ "$sourcetype" = "$OUTPUT" ]; then
		error "-> You cannot use the same file name for the input and output file!"
		rmtemp
	fi
	backup_file_func files
	# Scan to see if input file has
	# more than one video stream
	if [ "$ALLOW_SCAN_MULTIPLE_VIDSTREAMS" = "y" ]; then
		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" $MPLAYEROPTS -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > "$TEMPDIR/videostreams"
			if [ $(grep '^ID_VIDEO_ID' "$TEMPDIR/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' "$TEMPDIR/videostreams"); do
					echo "$(echo "Video stream: $(echo $i | awk -F= '{print $2}')")"
				done
				echo ""
				VIDSTREAM=$(grep '^ID_VIDEO_ID' "$TEMPDIR/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 "$TEMPDIR/videostreams"
		fi
	fi
	printf "Would you like to use Pre/Postprocessing video filters? [y/N]: "
	read vfilters
	video_filters_func
	video_subtitles_func
	;;
	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'"
		rmtemp
	fi
	sourcetype="$infile"
	test -d "$DEFOUTPUT" && DEFBATCHDIR="$DEFOUTPUT" || DEFBATCHDIR="$HOME"
	printf "Where to store the encodings? [default is $DEFBATCHDIR/divxenc_$$]: "
	read -e outdir
	if [ -z "$outdir" ]; then
		OUTPUTDIR="$DEFBATCHDIR/divxenc_$$"
		if [ ! -d "$OUTPUTDIR" ]; then
			mkdir -p "$OUTPUTDIR" 2>/dev/null
			if [ $? != 0 ]; then
				error "-> Failed to create the output directory!"
				error "-> Maybe a permissions problem?"
				rmtemp
			fi
		fi
	else
		if [ "$(dirname "$sourcetype")" = "$outdir" ]; then
			error "-> You can't use the input directory as output directory!"
			rmtemp
		fi
		OUTPUTDIR="$outdir"
		if [ ! -d "$OUTPUTDIR" ]; then
			mkdir -p "$OUTPUTDIR" 2>/dev/null
			if [ $? != 0 ]; then
				error "-> Failed to create the output directory!"
				error "-> Maybe a permissions problem?"
				rmtemp
			fi
		fi
	fi
	OUTPUT="$OUTPUTDIR/\${i%.*}.avi"
	printf "Would you like to use Pre/Postprocessing video filters? [y/N]: "
	read vfilters
	video_filters_func
	video_subtitles_func
	;;
	dvd)
	type="DVD"
	if [ ! -x "$LSDVD" ]; then
		error "-> Checking for lsdvd... FAILED!"
		rmtemp
	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!"
			rmtemp
		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_devices_func dvd
		check_spaces_func
		;;
		1)
		printf "Provide the DVD ISO image: "
		read -e dvdiso
		if [ -z "$dvdiso" -o ! -e "$dvdiso" ]; then
			error "-> ISO image not specified or does not exist!"
			rmtemp
		else
			device="-dvd-device $dvdiso"
		fi
		check_spaces_func
		;;
		2)
		printf "Provide the DVD VIDEO_TS directory: "
		read -e dvdvt
		if [ -z "$dvdvt" -o ! -d "$dvdvt" ]; then
			error "-> Directory not specified or does not exist!"
			rmtemp
		else
			device="-dvd-device $dvdvt"
		fi
		check_spaces_func
		;;
		*)
		error "-> Unknown option: '$dvdsource'"
		rmtemp
		;;
	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 $MPLAYEROPTS -nosound -vo null -frames 1 -nocache >/dev/null 2>&1
	set_output_filename_func
	check_diskspace_func
	backup_file_func files
	echo ""
	green "-> Scanning for DVD titles..."
	$LSDVD $(echo $device | awk '{print $2}') 2>/dev/null > "$TEMPDIR/dvdtitles"
	ALLTITLES=$(grep '^Title' "$TEMPDIR/dvdtitles" | awk '{print $1,$2,$5,$6,$3,$4}' | sed 's|,| -|g' | cut -f '1' -d '.' | awk '{print $1,$2,$3,$7,$8,$6,$4,$5}')
	DVDTITLE=$(grep 'Longest' "$TEMPDIR/dvdtitles" | awk '{print $3}' | sed 's/^0//')
	TOTAL_TITLES=$(grep '^Title' "$TEMPDIR/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 "$TEMPDIR/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!"
		rmtemp
	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 $MPLAYEROPTS -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="-dvdangle $dvd_angle"
		fi
	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 $MPLAYEROPTS -nosound -vo null -frames 1 -identify -nocache 2>/dev/null > "$TEMPDIR/chapters"
		if [ ! -z "$(grep '^CHAPTERS' "$TEMPDIR/chapters")" ]; then
			echo ""
			grep '^CHAPTERS' "$TEMPDIR/chapters" | sed -e 's/CHAPTERS: //' -e 's/,/ /g' > "$TEMPDIR/getchaps"
			for i in $(cat "$TEMPDIR/getchaps"); do
				echo "Chapter: $i - Start position: " >> "$TEMPDIR/lschaps"
			done
			nl "$TEMPDIR/lschaps" | awk '{print $2,$1,$4,$5,$6,$3}'
		else
			green "-> Could not detect any chapters in this DVD title!"
		fi
		rm -f "$TEMPDIR/*"
		echo
		echo "Example: to encode only chapter 2, type: 2-2"
		echo "Example: to encode from chapter 5 until the end of the DVD, type: 5"
		echo "Example: to encode from chapter 1 until the end of 3, type: 1-3"
		echo
		printf "Which chapter(s) to encode from this DVD title? [press 'Enter' to skip]: "
		read chapenc
		if [ ! -z "$chapenc" ]; then
			chapters="-chapter $chapenc"
			# Overwirte output name and
			# append chapter info to it
			if [ ! -z "$(echo $chapenc | grep '-')" ]; then
				CHAP1="$(echo $chapenc | awk -F- '{print $1}')"
				CHAP2="$(echo $chapenc | awk -F- '{print $2}')"
				if [ "$CHAP1" -eq "$CHAP2" ]; then
					OUTPUT="${OUTPUT%.*} - chapter $CHAP1.avi"
				else
					OUTPUT="${OUTPUT%.*} - chapter $chapenc.avi"
				fi
			else
				OUTPUT="${OUTPUT%.*} - chapter $chapenc.avi"
			fi
			backup_file_func files
		fi
	fi
	# Export chapters information to a file.
	# This can be used to import chapters
	# info when muxing into MKV. It requires
	# ogmtools' dvdxchap.
	if [ -x "$DVDXCHAP" ]; then
		printf "Export DVD chapters information to a file on disk? [y/N]: "
		read chapexp
		if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
			CHAPTERSFILE="${OUTPUT%.*}.chaps"
			backup_file_func chaps
			$DVDXCHAP -t $(echo $sourcetype | sed 's|dvd://||') $(echo $device | awk '{print $2}') 2>/dev/null | grep '^CHAPTER' > "$CHAPTERSFILE"
		fi
	fi
	printf "Would you like to use Pre/Postprocessing video filters? [y/N]: "
	read vfilters
	video_filters_func
	video_subtitles_func
	backup_file_func subs
	;;
	vcd)
	type="VCD"
	get_devices_func vcd
	echo
	green "-> Scanning for VCD tracks..."
	$MPLAYER vcd:// $device $MPLAYEROPTS -identify -vo null -frames 1 -ao null -nocache 2>/dev/null > "$TEMPDIR/vcdtracks"
	VCDTRACKS=$(grep '^ID_VCD_TRACK_.*' "$TEMPDIR/vcdtracks")
	rm -f "$TEMPDIR/vcdtracks"
	if [ ! -z "$VCDTRACKS" ]; then
		echo
		for i in $VCDTRACKS; do
			echo "Track: $(echo $i | sed -e 's|[A-Z]||g' -e 's|_||g' -e 's|=| - Length: |g')"
		done
	else
		green "-> Could not detect any VCD tracks!"
	fi
	echo
	printf "Specify the VCD track for encoding [default is 2]: "
	read vcdtrack
	if [ -z "$vcdtrack" ]; then
		sourcetype="vcd://2"
	else
		sourcetype="vcd://$vcdtrack"
	fi
	set_output_filename_func
	check_diskspace_func
	backup_file_func files
	printf "Would you like to use Pre/Postprocessing video filters? [y/N]: "
	read vfilters
	video_filters_func
	video_subtitles_func
	;;
	*|"")
	error "-> You have to specify the input type (file/dir/dvd/vcd)"
	rmtemp
	;;
esac

# Mutually exclusive with bobbing and interlacing
# as FPS is already detected and set in the functions
if [ -z "$intfilter" -a -z "$deintfps" ]; then
	detect_fps_func() {
		case "$1" in
			other)	scanopts="-vo null -ao null -identify -frames 1 -nocache" ;;
			ntsc)	scanopts="-vo null -nosound -identify -nocache -benchmark" ;;
		esac
		$MPLAYER "$sourcetype" $MPLAYEROPTS $device $vid $scanopts 2>/dev/null > "$TEMPDIR/fps"
		GETFPS=$(grep '^ID_VIDEO_FPS' "$TEMPDIR/fps" | tail -n 1 | awk -F= '{print $2}')
		GETLENGTH=$(grep '^ID_LENGTH' "$TEMPDIR/fps" | awk -F= '{print $2}')
	}
	
	echo
	case "$source" in
		dvd)
		# Try to detect NTSC type. Currently a fast
		# dumb solution and one that also can't
		# distinguish between true hard telecine
		# and interlacing but it works for soft
		# telecine and mixed progressive/telecine
		# content which is more common
		detect_fps_func other
		case "$GETFPS" in
			29.970|29.97)
			green "-> Detecting NTSC type and FPS value"
			green "-> Scanning can take a while..."
			detect_fps_func ntsc
			TC=$(grep 'demux_mpg' "$TEMPDIR/fps" | wc -l)
			case "$TC" in
				0)
				GETFPS="29.970"
				green "-> Detected 0 'demux_mpg' frame rate switchings"
				green "-> $type appears to be Progressive or Hard Telecined (may need IVTC!)"
				;;
				1)
				GETFPS="23.976"
				green "-> Detected 1 'demux_mpg' frame rate switching"
				green "-> $type appears to be Soft Telecined (needs FPS force to 23.976!)"
				;;
				*)
				GETFPS="23.976"
				green "-> Detected $TC 'demux_mpg' frame rate switchings"
				green "-> $type appears to be Mixed Progressive and Telecine (needs IVTC!)"
				;;
			esac
			;;
			*)
			green "-> Detecting FPS value..."
			green "-> Detected $GETFPS FPS"
			;;
		esac
		;;
		*)
		green "-> Detecting FPS value..."
		detect_fps_func other
		green "-> Detected $GETFPS FPS"
		;;
	esac
	green "-> Number of frames: $(echo "scale=0; $GETLENGTH * $GETFPS" | $BC -l | awk -F. '{print $1}')"
	rm -f "$TEMPDIR/fps"
	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"
				rmtemp
			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"
					rmtemp
				fi
				ofps="-ofps $frame_rate"
			fi
			;;
			13) false ;;
			*)
			error "-> Unknown frame rate option: '$frf'"
			rmtemp
			;;
		esac
	else
		setfps="no"
	fi
else
	GETFPS="25"
	setfps="yes"
fi

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

if [ "$ALLOW_VID_FPS_CONVERSION" = "y" ]; then
	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 "$ildctme" != ":ildct:ilme" ]; 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'"; rmtemp ;;
						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'"; rmtemp ;;
						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'"; rmtemp ;;
					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'"; rmtemp ;;
						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'"; rmtemp ;;
						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'"; rmtemp ;;
						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!"; rmtemp ;;
				esac
			fi
		fi
		;;
	esac
fi

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

case "$GETFPS" in
	23.976|29.970|23.97|29.97|30.000|30.00|"")
	if [ "$setfps" = "no" -a "$ildctme" != ":ildct:ilme" -a -z "$deintfilter" -a -z "$frc" ]; then
		printf "Apply a Telecine/3:2 Pulldown/IVTC/Pullup process? [y/N]: "
		read tpp
		if [ "$tpp" = "y" -o "$tpp" = "Y" ]; then
			echo ""
			brown "Telecine/3:2 Pulldown/IVTC/Pullup"
			brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
			echo "0 -> Inverse Telecine: 29.970 -> 23.976 fps"
			echo "1 -> Inverse Telecine: 59.940 -> 23.976 fps (filmdint/framestep)"
			echo "2 -> Inverse Telecine: 59.940 -> 23.976 fps (tinterlace/filmdint)"
			echo "3 -> Hard Telecine:    23.976 -> 29.970 fps"
			echo "4 -> Skip the Telecine/Pullup process"
			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'"
					rmtemp
					;;
				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"
				;;
				1)
				fps="-fps 60000/1001"
				ofps="-ofps 24000/1001"
				ivtcfilter="filmdint=fast=0,framestep=2,"
				echo
				green "-> Setting input/output frame rate to 59.940 / 23.976 FPS"
				green "-> Using '$(echo $ivtcfilter | sed 's/,$//')' video filter(s)"
				;;
				2)
				fps="-fps 60000/1001"
				ofps="-ofps 24000/1001"
				ivtcfilter="tinterlace=4,filmdint=fast=0,"
				echo
				green "-> Setting input/output frame rate to 59.940 / 23.976 FPS"
				green "-> Using '$(echo $ivtcfilter | sed 's/,$//')' video filter(s)"
				;;
				3)
				# Both fps and ofps *must* be
				# 30000/1001 or we will loose
				# A/V sync due to limitations
				# in the filter layer of MEncoder
				fps="-fps 30000/1001"
				ofps="-ofps 30000/1001"
				telecinefilter=",telecine"
				ildctme=":ildct:ilme"
				echo ""
				green "-> Setting input/output frame rate to 29.970 FPS"
				green "-> Using '$(echo $telecinefilter | sed 's/^,//')' video filter(s)"
				;;
				4) false ;;
				*)
				error "-> Unknown IVTC/Pulldown option: '$telproc'"
				rmtemp
				;;
			esac
		fi
	fi
	;;
esac

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

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

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

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

get_resolution_func() {
	$MPLAYER "$sourcetype" $device $vid $MPLAYEROPTS -identify -vo null -nosound -frames 1 -nocache 2>/dev/null > "$TEMPDIR/resolution"
	RATIO=$(grep '^ID_VIDEO_ASPECT' "$TEMPDIR/resolution" | tail -n 1 | awk -F= '{print $2}')
}

ratio_and_pixels_func() {
	SAR=$(echo "scale=4; $(echo $GETRES | sed 's|x|/|')" | $BC -l | sed 's|^\.|0\.|')
	PAR=$(echo "scale=4; $RATIO/$SAR" | $BC -l | sed 's|^\.|0\.|')
	PIXELS=$(($(echo $GETRES | sed 's|x|*|')))
	echo
	green "-> Detected Aspect Ratio (AR): $RATIO:1"
	green "-> Storage Aspect Ratio (SAR): $SAR:1"
	green "-> Pixel Aspect Ratio (PAR): $PAR:1"
	green "-> Total pixels: $PIXELS"
}

echo
if [ ! -z "$cropfilter" ]; then
	restype="Cropped"
	green "-> Detecting cropped resolution..."
	get_resolution_func
	GETRES=$(echo $cropfilter | sed 's|crop=||; s|,||; s|:|x|' | awk -F: '{print $1}')
else
	restype="Original"
	green "-> Detecting original resolution..."
	get_resolution_func
	GETRES=$(grep '^VIDEO:' "$TEMPDIR/resolution" | tail -n 1 | awk '{print $3}' | sed 's|,$||')
fi

if [ ! -z "$GETRES" ]; then
	green "-> $restype resolution is: $GETRES"
	ratio_and_pixels_func
else
	error "-> Failed to detect the $restype resolution!"
	error "-> You have to provide it yourself!"
	GETRES="??"
fi
if [ "$3" = "ipod" ]; then
	green "-> Valid iPod resolution: up to 640x480"
fi
rm -f "$TEMPDIR/resolution"
echo

printf "Specify the desired Resolution [default is $GETRES]: "
read vres
if [ -z "$vres" -a "$GETRES" = "??" ]; then
	error "-> You have to specify the resolution!"
	exit 1
fi

case "$vres" in
	$GETRES|"")
	if [ ! -z "$ilpack" ]; then
		scale="${ilpack}scale=::1"
	fi
	;;
	*)
	scale="${ilpack}scale=$(echo $vres | tr '[:alpha:]' ':')"
	# Interlace parameters for the scaler
	if [ "$ildctme" = ":ildct:ilme" -a -z "$intfilter" -a -z "$telecinefilter" ]; then
		isws=":1"
	else
		isws=":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|${ilpack}scale=||" | awk -F: '{print $1}')/16" | $BC -l | awk -F. '{print $2}')
	HMOD16=$(echo "scale=3; $(echo $scale | sed "s|${ilpack}scale=||" | awk -F: '{print $2}')/16" | $BC -l | awk -F. '{print $2}')
	if [ "$WMOD16" != "000" -o "$HMOD16" != "000" ]; then
		error "-> Warning: width and/or height not divisible by 16!"
		error "-> Compression will suffer!"
		echo ""
	fi
	GETSAR=$(echo "scale=4; $(echo $scale | sed "s|${ilpack}scale=||; s|:|/|")" | $BC -l | sed 's|^\.|0\.|')
	green "-> Storage Aspect Ratio (SAR): $GETSAR:1"
	green "-> Pixel Aspect Ratio (PAR): $(echo "scale=4; $RATIO/$GETSAR" | $BC -l | sed 's|^\.|0\.|'):1"
	green "-> Total pixels: $(($(echo $scale | sed "s|${ilpack}scale=||; s|:|*|")))"
	echo
	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
	if [ "$ALLOW_VID_SCALER_TUNING" = "y" ]; then
		case $(echo "$sws" | awk '{print $2}') in
			2|10)
			printf "Would you like to tune the Software Scaler? [y/N]: "
			read sstune
			if [ "$sstune" = "y" -o "$sstune" = "Y" ]; then
				echo ""
				brown "Software Scaler Parameters"
				brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
				echo "Here you can tune some parameters of"
				echo "the Bicubic/Natural Bicubic Spline"
				echo "software scalers. The first value"
				echo "represents the amount of blurring while"
				echo "the second value represents the amount"
				echo "of ringing. The higher the values, the"
				echo "more blurring/ringing you'll get."
				echo ""
				echo "Below are some frequently used settings"
				echo "Format is as follows: blurring:ringing"
				echo ""
				echo "0 -> 0.00:0.60 -> Default"
				echo "1 -> 0.00:0.75 -> VirtualDub's \"Precise Bicubic\""
				echo "2 -> 0.00:0.50 -> Catmull-Rom Spline"
				echo "3 -> 0.33:0.33 -> Mitchell-Netravali Spline"
				echo "4 -> 1.00:0.00 -> Cubic B-Spline"
				echo "5 -> User defined"
				echo "6 -> Skip the scaler parameters"
				echo ""
				printf "Specify the Software Scaler Parameters [default is 0.00:0.60]: "
				read ssparam
				case "$ssparam" in
					0|"") swsparam="::0.00:0.60" ;;
					1) swsparam="::0.00:0.75" ;;
					2) swsparam="::0.00:0.50" ;;
					3) swsparam="::0.33:0.33" ;;
					4) swsparam="::1.00:0.00" ;;
					5)
					printf "Specify the Software Scaler Parameters [default is 0.00:0.60]: "
					read ssp
					if [ -z "$ssp" ]; then
						swsparam="::0.00:0.60"
					else
						swsparam="::$ssp"
					fi
					;;
					6) false ;;
					*)
					error "-> Unknown software scaler parameters option: '$ssparam'"
					rmtemp
					;;
				esac
			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="::$ssparam"
				fi
			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="::$ssparam"
				fi
			fi
			;;
		esac
	fi
	;;
esac

if [ "$ALLOW_VID_DSIZE" = "y" ]; then
	if [ ! -z "$scale" ]; then
		printf "Specify the Display size/aspect [press 'Enter' to skip]: "
		read dsize
		if [ ! -z "$dsize" ]; then
			dsizefilter="dsize=$dsize,"
		fi
	fi
fi

if [ "$ALLOW_VID_EXPAND" = "y" ]; then
	printf "Specify the Expand filter parameters [press 'Enter' to skip]: "
	read exp_param
	if [ ! -z "$exp_param" ]; then
		if [ ! -z "$scale" ]; then
			printf "Place the filter (b) before or (a) after the scale filter? [b/a - default is b]: "
			read expandpos
			if [ -z "$expandpos" -o "$expandpos" = "b" ]; then
				expandfilter_bfr="expand=$exp_param,"
			elif [ "$expandpos" = "a" ]; then
				expandfilter_afr=",expand=$exp_param"
			fi
		else
			expandfilter_bfr="expand=$exp_param,"
		fi
	fi
fi

# Do a colorspace conversion?
if [ "$ALLOW_VID_COLORSPACE" = "y" ]; then
	if [ ! -z "$scale" ]; then
		if [ -z "$fpsfilter" -a -z "$intfilter" -a -z "$telecinefilter" -a -z "$ildctme" ]; then
			video_colorspace_func
		fi
	fi
fi

# Aspect ratio
if [ "$ALLOW_VID_ASPECT" = "y" ]; then
	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 ratio..."
		if [ ! -z "$RATIO" ]; then
			green "-> Detected: $RATIO"
			V_ASPECT="$RATIO"
		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.7778... - default is $V_ASPECT]: "
		read asra
		if [ -z "$asra" ]; then
			aspect="-aspect $V_ASPECT"
		else
			aspect="-aspect $asra"
		fi
	fi
fi

#################################################
################ DivX Settings ##################
#################################################


echo ""
brown "+=================================+"
brown "| FMP4/DivX Encoder Configuration |"
brown "+=================================+"
echo ""

case "$1" in 
	-[1-3]p)
	printf "Specify the desired Video Bitrate in kbps [default is 1200]: "
	read vb
	if [ -z "$vb" ]; then
		vbitrate="vbitrate=1200"
	else
		vbitrate="vbitrate=$vb"
	fi
	if [ "$3" = "ipod" ]; then
		if [[ $(echo $vbitrate | awk -F= '{print $2}') -gt 2500 ]]; then
			echo
			error "-> Apple iPod video bitrate may not exceed 2500 kbps!"
			echo
			rmtemp
		fi
	fi
	bits_per_pixel_func
	bits_per_block_func
	;;
	-fq)
	printf "Specify the desired Quantizer [1-31 - default is 3]: "
	read quant
	if [ -z "$quant" ]; then
		vbitrate="vqscale=3"
	else
		vbitrate="vqscale=$quant"
	fi
	echo ""
	;;
esac

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

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

display_quality_preset_func $3 $4
case "$3" in
	cp)	source "$4" ;;
	nq)	divxparams=":vmax_b_frames=0:vme=4:mbd=1:lumi_mask=0.05:dark_mask=0.01:naq:dia=1:last_pred=0:vlelim=-4:vcelim=9:autoaspect$ildctme$threads"; ffourcc="-ffourcc DX50" ;;
	hq)	divxparams=":vmax_b_frames=2:vme=4:mbd=2:v4mv:dia=2:trell:last_pred=0:vlelim=-4:vcelim=9:autoaspect$ildctme$threads"; ffourcc="-ffourcc DX50" ;;
	vhq)	divxparams=":vmax_b_frames=2:vme=4:mbd=2:v4mv:bidir_refine=1:cmp=2:subcmp=2:dia=2:trell:cbp:mv0:last_pred=2:preme=1:vlelim=-4:vcelim=9:autoaspect$ildctme$threads"; ffourcc="-ffourcc DX50" ;;
	ehq)	divxparams=":vmax_b_frames=2:vme=4:mbd=2:v4mv:bidir_refine=2:cmp=2:subcmp=2:dia=-1:trell:cbp:mv0:last_pred=4:preme=1:vlelim=-4:vcelim=9:autoaspect$ildctme$threads"; ffourcc="-ffourcc DX50" ;;
	uhq)	divxparams=":vmax_b_frames=2:vme=4:mbd=2:v4mv:bidir_refine=3:precmp=2:cmp=2:subcmp=2:dia=-1:trell:cbp:mv0:last_pred=6:preme=2:qns=1:vlelim=-4:vcelim=9:autoaspect$ildctme$threads"; ffourcc="-ffourcc DX50" ;;
	ihq)	divxparams=":vmax_b_frames=2:vme=4:mbd=2:v4mv:bidir_refine=4:precmp=6:cmp=6:subcmp=6:dia=-1:trell:cbp:mv0:last_pred=8:preme=2:qns=2:vlelim=-4:vcelim=9:autoaspect$ildctme$threads"; ffourcc="-ffourcc DX50" ;;
	hwp)	divxparams=":vmax_b_frames=2:vme=4:mbd=2:bidir_refine=1:cmp=2:subcmp=2:dia=-1:trell:cbp:mv0:last_pred=2:preme=1:autoaspect$ildctme$threads"; noodml="-noodml"; ffourcc="-ffourcc DX50" ;;
	ps3)	divxparams=":vmax_b_frames=0:vme=4:mbd=2:cmp=2:subcmp=2:dia=-1:trell:cbp:mv0:preme=1:autoaspect$ildctme$threads"; noodml="-noodml"; ffourcc="-ffourcc DX50" ;;
	ipod)	divxparams=":vmax_b_frames=0:vme=4:mbd=2:cmp=2:subcmp=2:dia=-1:trell:cbp:mv0:preme=1:autoaspect$ildctme$threads"; noodml="-noodml"; ffourcc="-ffourcc DX50" ;;
esac
echo

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

# Set priority (nice value) of the whole
# encoding process
if [ ! -z "$PRIORITY" ]; then
	priority_level="nice -n $PRIORITY"
else
	printf "Would you like to set the encoder Priority Level? [y/N]: "
	read priolevel
	if [ "$priolevel" = "y" -o "$priolevel" = "Y" ]; then
		if [ $UID != 0 ]; then
			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 ""
				green "-> You do not have the privilege to set a negative 'nice' value!"
				green "-> Continuing with default 'nice' value of 0"
				;;
			esac
		else
			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"
				;;
			esac
		fi
	fi
fi

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

echo
brown "+=====================+"
brown "| Audio Configuration |"
brown "+=====================+"
case "$source" in
	dir|vcd)
	echo
	TRACKID[1]=yes
	;;
	dvd)
	echo
	TRACKID[1]=yes
	green "-> Scanning for audio streams..."
	$MPLAYER $sourcetype $device $MPLAYEROPTS -nosound -vo null -frames 1 -nocache 2>/dev/null > "$TEMPDIR/audiostreams"
	STREAMS=$(grep "^audio stream" "$TEMPDIR/audiostreams")
	if [ ! -z "$STREAMS" ]; then
		echo
		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/dts/DTS/g' -e 's/lpcm/LPCM/g' -e 's/pcm/PCM/g'
	else
		green "-> Could not detect any audio streams!"
	fi
	echo
	printf "Track 1: 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!"
		rmtemp
	fi
	if [ -z "$dac" ]; then
		aid[1]="-aid 128"
	else
		aid[1]="-aid $dac"
	fi
	for i in {2..3}; do
		printf "Track $i: Specify the DVD Audio Stream ID [press 'Enter' to skip]: "
		read dac[$i]
		if [ ! -z "$(echo ${dac[$i]} | grep '[a-zA-Z]')" ]; then
			error "-> You have to specify the 'ID' number, not the language code!"
			rmtemp
		fi
		if [ ! -z "${dac[$i]}" ]; then
			TRACKID[$i]=yes
			aid[$i]="-aid ${dac[$i]}"
		fi
	done
	for i in {1..3}; do
		if [ "${TRACKID[$i]}" = "yes" ]; then
			GETLANG[$i]="$(grep "$(echo ${aid[$i]} | awk '{print $2}')" "$TEMPDIR/audiostreams" \
			| grep -o 'language.*' | awk '{print $2}')"
			if [ ! -z "${GETLANG[$i]}" ]; then
				if [ "${GETLANG[$i]}" = "unknown" ]; then
					AUDLANG[$i]="und"
				else
					AUDLANG[$i]="${GETLANG[$i]}"
				fi
			else
				AUDLANG[$i]="und"
			fi
		fi
	done
	rm -f "$TEMPDIR/audiostreams"
	;;
	file)
	TRACKID[1]=yes
	if [ "$ALLOW_SCAN_MULTIPLE_AUDSTREAMS" = "y" ]; then
		echo
		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" $MPLAYEROPTS -nosound -vo null -identify -frames 1 -nocache 2>/dev/null > "$TEMPDIR/audiostreams"
			if [ $(grep "^ID_AUDIO_ID" "$TEMPDIR/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" "$TEMPDIR/audiostreams"); do
					echo "$(echo "Audio stream: $(echo $i | awk -F= '{print $2}')")"
				done
				echo ""
				AID=$(grep "^ID_AUDIO_ID" "$TEMPDIR/audiostreams" | awk -F= '{print $2}')
				printf "Track 1: Specify the Audio Stream number [default is $(echo $AID | awk '{print $1}')]: "
				read dac
				if [ -z "$dac" ]; then
					aid[1]="-aid $(echo $AID | awk '{print $1}')"
				else
					aid[1]="-aid $dac"
				fi
			fi
			rm -f "$TEMPDIR/audiostreams"
		fi
	fi
	;;
esac

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

mp3_audio_func() {
	printf "Track $i: Specify the MP3 Audio Encoding Mode [ABR/CBR/VBR/PRESET - default is ABR]: "
	read mp3mode[$i]
	case "${mp3mode[$i]}" in
		a*|A*|"")
		printf "Track $i: Specify the MP3 Average Bitrate [default is 140]: "
		read ab[$i]
		if [ -z "${ab[$i]}" ]; then
			abitrate[$i]="abr:br=140"
		else
			abitrate[$i]="abr:br=${ab[$i]}"
		fi
		;;
		c*|C*)
		echo
		brown "Track $i: 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 "Track $i: Select the MP3 Audio Bitrate [default is 8]: "
		read ab[$i]
		case "${ab[$i]}" in
			0) abitrate[$i]="cbr:br=32" ;;
			1) abitrate[$i]="cbr:br=40" ;;
			2) abitrate[$i]="cbr:br=48" ;;
			3) abitrate[$i]="cbr:br=56" ;;
			4) abitrate[$i]="cbr:br=64" ;;
			5) abitrate[$i]="cbr:br=80" ;;
			6) abitrate[$i]="cbr:br=96" ;;
			7) abitrate[$i]="cbr:br=112" ;;
			8|"") abitrate[$i]="cbr:br=128" ;;
			9) abitrate[$i]="cbr:br=160" ;;
			10) abitrate[$i]="cbr:br=192" ;;
			11) abitrate[$i]="cbr:br=224" ;;
			12) abitrate[$i]="cbr:br=256" ;;
			13) abitrate[$i]="cbr:br=320" ;;
			*)
			error "-> Unknown option: '${ab[$i]}'"
			error "-> Exiting in function: mp3_audio_func()"
			rmtemp ;;
		esac
		;;
		v*|V*)
		printf "Track $i: Specify the desired MP3 Audio Quality [0-9 - default is 3]: "
		read ab[$i]
		if [ -z "${ab[$i]}" ]; then
			abitrate[$i]="q=3"
		else
			abitrate[$i]="q=${ab[$i]}"
		fi
		;;
		p*|P*)
		echo
		brown "Track $i: MP3 Presets"
		brown "~~~~~~~~~~~~~~~~~~~~"
		echo "0 -> Medium (VBR: 150-180 kbps)"
		echo "1 -> Standard (VBR: 170-210 kbps)"
		echo "2 -> Extreme (VBR: 200-240 kbps)"
		echo "3 -> Insane (CBR: 320 kbps)"
		echo
		printf "Track $i: Select an MP3 preset [default is 0]: "
		read mp3preset[$i]
		case "${mp3preset[$i]}" in
			0|"") abitrate[$i]="preset=medium" ;;
			1) abitrate[$i]="preset=standard" ;;
			2) abitrate[$i]="preset=extreme" ;;
			3) abitrate[$i]="preset=insane" ;;
			*)
			error "-> Unknown MP3 preset!"
			error "-> Exiting in function: mp3_audio_func()"
			rmtemp
			;;
		esac
		;;
		*)
		error "-> Unknown MP3 encoding mode: '${mp3mode[$i]}'"
		error "-> Exiting in function: mp3_audio_func()"
		rmtemp
		;;
	esac
	printf "Track $i: Specify the MP3 Algorithmic Quality [0-9 - default is 4]: "
	read aq[$i]
	if [ -z "${aq[$i]}" ]; then
		aquality[$i]=":aq=4"
	else
		aquality[$i]=":aq=${aq[$i]}"
	fi
	printf "Track $i: Specify the MP3 Audio Input Gain [0.0-10.0 - default is 2.2]: "
	read aig[$i]
	if [ -z "${aig[$i]}" ]; then
		again[$i]=":vol=2.2"
	else
		again[$i]=":vol=${aig[$i]}"
	fi
	echo ""
	brown "Track $i: MP3 Channel Modes"
	brown "~~~~~~~~~~~~~~~~~~~~~~~~~~"
	echo "0 -> Stereo"
	echo "1 -> Joint-Stereo"
	echo "2 -> Dual Channel"
	echo "3 -> Mono"
	echo ""
	printf "Track $i: Select the MP3 Channel Mode [default is 1]: "
	read mp3chan[$i]
	case "${mp3chan[$i]}" in
		0) mp3channel[$i]=":mode=0" ;;
		1|"") mp3channel[$i]=":mode=1" ;;
		2) mp3channel[$i]=":mode=2" ;;
		3) mp3channel[$i]=":mode=3" ;;
		*)
		error "-> Unknown MP3 channel option: '${mp3chan[$i]}'"
		error "-> Exiting in function: mp3_audio_func()"
		rmtemp
		;;
	esac
	acodec[$i]="-oac mp3lame -lameopts ${abitrate[$i]}${aquality[$i]}${again[$i]}${mp3channel[$i]}"
}

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

aac_audio_func() {
	case "$1" in
		ipod)
		printf "Track $i: Specify the AAC Average Audio Bitrate [default is 128]: "
		read abitrate[$i]
		if [ -z "${abitrate[$i]}" ]; then
			br[$i]=":br=128"
		else
			if [[ ${abitrate[$i]} -gt 160 ]]; then
				echo
				green "-> Track $i: iPod bitrate may not exceed 160 kbps!"
				green "-> Track $i: Falling back to default of 128 kbps"
				echo
				br[$i]=":br=128"
			else
				br[$i]=":br=${abitrate[$i]}"
			fi
		fi
		;;
		*)
		printf "Track $i: Specify the AAC encoding mode [ABR/VBR - default is ABR]: "
		read aacmode[$i]
		case "${aacmode[$i]}" in
			a*|A*|"")
			printf "Track $i: Specify the AAC Average Bitrate [default is 110]: "
			read abitrate[$i]
			if [ -z "${abitrate[$i]}" ]; then
				br[$i]=":br=110"
			else
				br[$i]=":br=${abitrate[$i]}"
			fi
			;;
			v*|V*)
			SKIPBTRCALC=yes
			printf "Track $i: Specify the AAC Quality value [1-1000 - default is 250]: "
			read abitrate[$i]
			if [ -z "${abitrate[$i]}" ]; then
				br[$i]=":quality=250"
			else
				br[$i]=":quality=${abitrate[$i]}"
			fi
			;;
			*)
			error "-> Unknown AAC encoding mode: '${aacmode[$i]}'"
			error "-> Exiting in function: aac_audio_func()"
			rmtemp
			;;
		esac
		;;
	esac
	printf "Track $i: Enable AAC Temporal Noise Shaping? [y/N]: "
	read tempns[$i]
	if [ "${tempns[$i]}" = "y" -o "${tempns[$i]}" = "Y" ]; then
		tns[$i]=":tns"
	fi
	acodec[$i]="-oac faac -faacopts mpeg=4:object=2${br[$i]}${tns[$i]}"
}

neroaac_audio_func() {
	acodec[$i]="-oac pcm"
	case "$1" in
		ipod)
		aacprof[$i]="-lc"
		AACTYPE[$i]=LC-AAC
		printf "Track $i: Specify the AAC Audio Bitrate in kbps [default is 128]: "
		read ab[$i]
		if [ -z "${ab[$i]}" ]; then
			neroaacbr[$i]="-br 128000 ${aacprof[$i]}"
		else
			if [[ ${ab[$i]} -gt 160 ]]; then
				echo
				green "-> Track $i: iPod audio bitrate may not exceed 160 kbps!"
				green "-> Track $i: Falling back to 128 kbps"
				echo
				neroaacbr[$i]="-br 128000 ${aacprof[$i]}"
			else
				neroaacbr[$i]="-br $((${ab[$i]}*1000)) ${aacprof[$i]}"
			fi
		fi
		printf "Track $i: Use 2-pass AAC encoding instead of 1-pass? [y/N]: "
		read nero2p[$i]
		if [ "${nero2p[$i]}" = "y" -o "${nero2p[$i]}" = "Y" ]; then
			neroaacbr[$i]="${neroaacbr[$i]} -2pass"
		fi
		;;
		*)
		printf "Track $i: Which AAC Profile to use? [LC/HE/HEv2 - default is LC]: "
		read aac_profile[$i]
		case "${aac_profile[$i]}" in
			LC|lc|"")	aacprof[$i]="-lc"; AACTYPE[$i]=LC-AAC ;;
			HE|he)		aacprof[$i]="-he"; AACTYPE[$i]=HE-AACv1 ;;
			HEv2|hev2)	aacprof[$i]="-hev2"; AACTYPE[$i]=HE-AACv2 ;;
			*)
			error "-> Unknown AAC profile!"
			error "-> Exiting in function: neroaac_audio_func()"
			rmtemp
			;;
		esac
		printf "Track $i: Specify the AAC Encoding Mode [ABR/CBR/VBR - default is ABR]: "
		read aacmode[$i]
		case "${aacmode[$i]}" in
			a*|A*|"")
			case "${aacprof[$i]}" in
				-lc)	defaacbr[$i]="96" ;;
				-he)	defaacbr[$i]="55" ;;
				-hev2)	defaacbr[$i]="25" ;;
			esac
			printf "Track $i: Specify the AAC Average Bitrate in kbps [default is ${defaacbr[$i]}]: "
			read ab[$i]
			if [ -z "${ab[$i]}" ]; then
				neroaacbr[$i]="-br $((${defaacbr[$i]}*1000)) ${aacprof[$i]}"
			else
				neroaacbr[$i]="-br $((${ab[$i]}*1000)) ${aacprof[$i]}"
			fi
			;;
			c*|C*)
			echo
			brown "Track $i: 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 "Track $i: Select the AAC Audio Bitrate [default is 6]: "
			read ab[$i]
			case "${ab[$i]}" in
				0) neroaacbr[$i]="-cbr 32000 ${aacprof[$i]}" ;;
				1) neroaacbr[$i]="-cbr 40000 ${aacprof[$i]}" ;;
				2) neroaacbr[$i]="-cbr 48000 ${aacprof[$i]}" ;;
				3) neroaacbr[$i]="-cbr 56000 ${aacprof[$i]}" ;;
				4) neroaacbr[$i]="-cbr 64000 ${aacprof[$i]}" ;;
				5) neroaacbr[$i]="-cbr 80000 ${aacprof[$i]}" ;;
				6|"") neroaacbr[$i]="-cbr 96000 ${aacprof[$i]}" ;;
				7) neroaacbr[$i]="-cbr 112000 ${aacprof[$i]}" ;;
				8) neroaacbr[$i]="-cbr 128000 ${aacprof[$i]}" ;;
				9) neroaacbr[$i]="-cbr 160000 ${aacprof[$i]}" ;;
				10) neroaacbr[$i]="-cbr 192000 ${aacprof[$i]}" ;;
				11) neroaacbr[$i]="-cbr 224000 ${aacprof[$i]}" ;;
				12) neroaacbr[$i]="-cbr 256000 ${aacprof[$i]}" ;;
				13) neroaacbr[$i]="-cbr 320000 ${aacprof[$i]}" ;;
				*)
				error "-> Unknown option: '${ab[$i]}'"
				error "-> Exiting in function: neroaac_audio_func()"
				rmtemp
				;;
			esac
			;;
			v*|V*)
			SKIPBTRCALC=yes
			case "${aacprof[$i]}" in
				-lc)	defaacbr[$i]="0.35" ;;
				-he)	defaacbr[$i]="0.22" ;;
				-hev2)	defaacbr[$i]="0.11" ;;
			esac
			printf "Track $i: Specify the AAC Quality value [0.0-1.0 - default is ${defaacbr[$i]}]: "
			read ab[$i]
			if [ -z "${ab[$i]}" ]; then
				neroaacbr[$i]="-q ${defaacbr[$i]} ${aacprof[$i]}"
			else
				neroaacbr[$i]="-q ${ab[$i]} ${aacprof[$i]}"
			fi
			;;
			*)
			error "-> Unknown option: '${aacmode[$i]}'"
			error "-> Exiting in function: neroaac_audio_func()"
			rmtemp
			;;
		esac
		case "${aacmode[$i]}" in
			a*|A*|c*|C*|"")
			printf "Track $i: Use 2-pass AAC encoding instead of 1-pass? [y/N]: "
			read nero2p[$i]
			if [ "${nero2p[$i]}" = "y" -o "${nero2p[$i]}" = "Y" ]; then
				neroaacbr[$i]="${neroaacbr[$i]} -2pass"
			fi
			;;
		esac
		;;
	esac
}

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

vorbis_audio_func() {
	acodec[$i]="-oac pcm"
	printf "Track $i: Select the Vorbis encoding mode [ABR/VBR - default is VBR]: "
	read vorbmode[$i]
	case "${vorbmode[$i]}" in
		a*|A*)
		printf "Track $i: Specify the Vorbis nominal bitrate in kbps [default is 112]: "
		read ab[$i]
		if [ -z "${ab[$i]}" ]; then
			vorbq[$i]="-b 112"
		else
			vorbq[$i]="-b ${ab[$i]}"
		fi
		;;
		v*|V*|"")
		printf "Track $i: Specify the Vorbis audio quality [-1-10 - default is 3]: "
		read ab[$i]
		if [ -z "${ab[$i]}" ]; then
			vorbq[$i]="-q 3"
		else
			if [ ! -z "$(echo ${ab[$i]} | grep '\.')" ]; then
				echo
				green "-> Track $i: Floating point values are not supported yet!"
				green "-> Track $i: Rounding value to $(echo ${ab[$i]} | awk -F. '{print $1}')"
				echo
				vorbq[$i]="-q $(echo ${ab[$i]} | awk -F. '{print $1}')"
			else
				vorbq[$i]="-q ${ab[$i]}"
			fi
		fi
		;;
		*)
		error "-> Unknown option: '${vorbmode[$i]}'"
		error "-> Exiting in function: vorbis_audio_func()"
		rmtemp
		;;
	esac
}

flac_audio_func() {
	acodec[$i]="-oac pcm"
	printf "Track $i: Specify the FLAC Audio compression [0(low)-8(high) - default is 5]: "
	read ab[$i]
	if [ -z "${ab[$i]}" ]; then
		flacq[$i]="-5"
	else
		flacq[$i]="-${ab[$i]}"
	fi
}

# Check availability of the
# selected audio codec
check_audio_codec_func() {
	case "${audiocodec[$i]}" in
		ac3)
		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()"
			rmtemp
		fi
		;;
		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()"
			rmtemp
		fi
		;;
		aac+)
		if [ ! -x "$AACPLUSENC" ]; then
			error "-> 'aacplusenc' is missing from your system!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmtemp
		fi
		;;
		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()"
			rmtemp
		fi
		;;
		neroaac)
		if [ ! -x "$NEROAACENC" ]; then
			error "-> 'neroAacEnc' is missing from your system!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmtemp
		fi
		;;
		vorbis)
		if [ ! -x "$OGGENC" ]; then
			error "-> 'oggenc' is missing from your system!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmtemp
		fi
		;;
		flac)
		if [ ! -x "$FLAC" ]; then
			error "-> 'flac' is missing from your system!"
			error "-> Exiting in function: check_audio_codec_func()"
			rmtemp
		fi
		;;
		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()"
			rmtemp
		fi
		;;
		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()"
			rmtemp
		fi
		;;
	esac
}

########################################################
############# Audio Filters Functions ##################
########################################################

# Resample function
audio_resample_filters_func() {
	echo
	brown "Track $i: 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 "Track $i: Select a Resample filter [default is 7]: "
	read rsmpfilter[$i]
	case "${rsmpfilter[$i]}" in
		0) resample[$i]="resample=${hertz[$i]}:1:0 -srate ${hertz[$i]}" ;;
		1) resample[$i]="resample=${hertz[$i]}:0:0 -srate ${hertz[$i]}" ;;
		2) resample[$i]="resample=${hertz[$i]}:1:1 -srate ${hertz[$i]}" ;;
		3) resample[$i]="resample=${hertz[$i]}:0:1 -srate ${hertz[$i]}" ;;
		4) resample[$i]="resample=${hertz[$i]}:1:2 -srate ${hertz[$i]}" ;;
		5) resample[$i]="resample=${hertz[$i]}:0:2 -srate ${hertz[$i]}" ;;
		6) resample[$i]="lavcresample=${hertz[$i]}:16:0 -srate ${hertz[$i]}" ;;
		7|"") resample[$i]="lavcresample=${hertz[$i]}:16:1 -srate ${hertz[$i]}" ;;
		8) skiprsmp=yes ;;
		*)
		error "-> Unknown option: '${rsmpfilter[$i]}'"
		error "-> Exiting in function: audio_resample_filters_func()"
		rmtemp
		;;
	esac
}

audio_resample_func() {
	printf "Track $i: Would you like to Resample the Audio? [y/N]: "
	read rsmp[$i]
	if [ "${rsmp[$i]}" = "y" -o "${rsmp[$i]}" = "Y" ]; then
		case "$source" in
			file|dvd|vcd)
			echo
			green "-> Track $i: Detecting audio sample rate..."
			AUDSAMPLE[$i]=$($MPLAYER "$sourcetype" $MPLAYEROPTS $device ${aid[$i]} -identify -vo null -vc null -ao null -frames 0 -nocache 2>/dev/null \
			| grep '^ID_AUDIO_RATE' | tail -n 1 | awk -F= '{print $2}')
			if [ ! -z "${AUDSAMPLE[$i]}" ]; then
				green "-> Track $i: Detected: ${AUDSAMPLE[$i]} Hz ($(echo "scale=1; ${AUDSAMPLE[$i]} / 1000" | $BC -l) kHz)"
			else
				green "-> Track $i: could not detect the sample rate!"
			fi
			;;
		esac
		echo
		brown "Track $i: Available Sample Frequencies"
		brown "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"
		case "${audiocodec[$i]}" in
			pcm|vorbis)
			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 "Track $i: Select a Sample frequency [default is 7]: "
			read freq[$i]
			case "${freq[$i]}" in
				0) hertz[$i]="8000" ;;
				1) hertz[$i]="11025" ;;
				2) hertz[$i]="12000" ;;
				3) hertz[$i]="16000" ;;
				4) hertz[$i]="22050" ;;
				5) hertz[$i]="24000" ;;
				6) hertz[$i]="32000" ;;
				7|"") hertz[$i]="44100" ;;
				8) hertz[$i]="48000" ;;
				*)
				error "-> Unknown option: '${freq[$i]}'"
				error "-> Exiting in function: audio_resample_func()"
				rmtemp
				;;
			esac
			;;
			aac+|ac3|mp3|"")
			echo "0 -> 32000 Hz (32 kHz)"
			echo "1 -> 44100 Hz (44.1 kHz)"
			echo "2 -> 48000 Hz (48 kHz)"
			echo ""
			printf "Track $i: Select a Sample frequency [default is 1]: "
			read freq[$i]
			case "${freq[$i]}" in
				0) hertz[$i]="32000" ;;
				1|"") hertz[$i]="44100" ;;
				2) hertz[$i]="48000" ;;
				*)
				error "-> Unknown option: '${freq[$i]}'"
				error "-> Exiting in function: audio_resample_func()"
				rmtemp
				;;
			esac
			;;
			aac|neroaac|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 "9 --> 64000 Hz (64 kHz)"
			echo "10 -> 88200 Hz (88.2 kHz)"
			echo "11 -> 96000 Hz (96 kHz)"
			echo ""
			printf "Track $i: Select a Sample frequency [default is 7]: "
			read freq[$i]
			case "${freq[$i]}" in
				0) hertz[$i]="8000" ;;
				1) hertz[$i]="11025" ;;
				2) hertz[$i]="12000" ;;
				3) hertz[$i]="16000" ;;
				4) hertz[$i]="22050" ;;
				5) hertz[$i]="24000" ;;
				6) hertz[$i]="32000" ;;
				7|"") hertz[$i]="44100" ;;
				8) hertz[$i]="48000" ;;
				9) hertz[$i]="64000" ;;
				10) hertz[$i]="88200" ;;
				11) hertz[$i]="96000" ;;
				*)
				error "-> Unknown option: '${freq[$i]}'"
				error "-> Exiting in function: audio_resample_func()"
				rmtemp
				;;
			esac
			;;
		esac
		case "$source" in
			dir)
			audio_resample_filters_func
			;;
			*)
			if [ "${AUDSAMPLE[$i]}" = "${hertz[$i]}" ]; then
				echo
				green "-> Track $i: Detected sample rate equals selected one!"
				green "-> Track $i: ${AUDSAMPLE[$i]} Hz <=> ${hertz[$i]} Hz"
				green "-> Track $i: Skipping resampling"
				echo
				resample[$i]=
			else
				audio_resample_filters_func
			fi
			;;
		esac
	fi
}

# Audio EQ
audio_equalizer_func() {
	printf "Track $i: Would you like to use the Audio Equalizer? [y/n]: "
	read audioeq[$i]
	if [ "${audioeq[$i]}" = "y" -o "${audioeq[$i]}" = "Y" ]; then
		printf "Track $i: Specify the Audio Equalizer parameters [press 'Enter' to skip]: "
		read audeqparams[$i]
		if [ ! -z "${audeqparams[$i]}" ]; then
			audeq[$i]="equalizer=${audeqparams[$i]},"
		fi
	fi
}

# Volume normalization
audio_volnorm_func() {
	printf "Track $i: Would you like to Normalize the Audio volume? [y/N]: "
	read norm[$i]
	if [ "${norm[$i]}" = "y" -o "${norm[$i]}" = "Y" ]; then
		volnorm[$i]="volnorm=2,"
	fi
}

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

# Audio panning
audio_pan_func() {
	printf "Track $i: Would you like to Pan the Audio? [y/N]: "
	read audpan[$i]
	if [ "${audpan[$i]}" = "y" -o "${audpan[$i]}" = "Y" ]; then
		printf "Track $i: Specify the panning filter values [press 'Enter' to skip]: "
		read panval[$i]
		if [ ! -z "${panval[$i]}" ]; then
			pan[$i]="pan=${panval[$i]},"
		fi
	fi
}

# Audio channel routing/removing/adding filter
audio_channels_func() {
	printf "Track $i: Would you like to add/remove/route Audio channels? [y/N]: "
	read audroute[$i]
	if [ "${audroute[$i]}" = "y" -o "${audroute[$i]}" = "Y" ]; then
		printf "Track $i: Specify the Audio channels filter parameters [press 'Enter' to skip]: "
		read audchanparams[$i]
		if [ ! -z "${audchanparams[$i]}" ]; then
			audchannels[$i]="channels=${audchanparams[$i]},"
		fi
	fi
}

# Audio channels decode function
audio_channels_decode_func() {
	case "${audiocodec[$i]}" in
		ac3|aac|neroaac|vorbis|flac|pcm)
		printf "Track $i: Would you like to decode/output more than 2 Audio Channels? [y/N]: "
		read chan[$i]
		if [ "${chan[$i]}" = "y" -o "${chan[$i]}" = "Y" ]; then
			printf "Track $i: How many channels to decode/output? [2/4/6/8 - default is 2]: "
			read chanuse[$i]
			if [ -z "${chanuse[$i]}" ]; then
				channels[$i]="-channels 2"
			else
				channels[$i]="-channels ${chanuse[$i]}"
			fi
			if [ "${aacprof[$i]}" = "-hev2" ]; then
				if [ "$(echo ${channels[$i]} | awk '{print $2}')" != "2" ]; then
					echo
					green "-> HE-AACv2 only supports stereo!"
					green "-> Forcing stereo output decoding"
					echo
					channels[$i]="-channels 2"
				fi
			fi
		fi
		;;
		copy)
		case "$source" in
			dvd)	copychans[$i]="6" ;;
			*)	copychans[$i]="2" ;;
		esac
		printf "Track $i: How many channels to copy? [2/4/6/8 - default is ${copychans[$i]}]: "
		read chancopy[$i]
		if [ -z "${chancopy[$i]}" ]; then
			channels[$i]="-channels ${copychans[$i]}"
		else
			channels[$i]="-channels ${chancopy[$i]}"
		fi
		;;
	esac
}

neroaac_hev2_func() {
	if [ "${aacprof[$i]}" = "-hev2" ]; then
		if [ -z "${channels[$i]}" ]; then
			channels[$i]="-channels 2"
		fi
	fi
}

# Global function for calling
# the above audio filters
audio_filters_func() {
	aud_filters_func() {
		case "${audiocodec[$i]}" in
			mp3|"")
			test "$ALLOW_AUD_CHANNELS" = "y" && audio_channels_func
			test "$ALLOW_AUD_PAN" = "y" && audio_pan_func
			test "$ALLOW_AUD_EQUALIZER" = "y" && audio_equalizer_func
			;;
			*)
			test "$ALLOW_AUD_CHANNELS" = "y" && audio_channels_func
			test "$ALLOW_AUD_PAN" = "y" && audio_pan_func
			test "$ALLOW_AUD_EQUALIZER" = "y" && audio_equalizer_func
			test "$ALLOW_AUD_NORMALIZE" = "y" && audio_volnorm_func
			test "$ALLOW_AUD_VOLUME" = "y" && audio_volume_func
			;;
		esac
	}
	if [ "$ALLOW_AUD_CHANNELS" = "y" -o "$ALLOW_AUD_PAN" = "y" -o "$ALLOW_AUD_NORMALIZE" = "y" \
	-o "$ALLOW_AUD_VOLUME" = "y" -o "$ALLOW_AUD_RESAMPLE" = "y" -o "$ALLOW_AUD_EQUALIZER" = "y" ]; then
		printf "Track $i: Would you like to use Audio filters [y/N]: "
		read use_audfilters[$i]
		if [ "${use_audfilters[$i]}" = "y" -o "${use_audfilters[$i]}" = "Y" ]; then
			case "$1" in
				ipod)
				# Resampling is skipped here. See the
				# audio_filters_var_func function below
				# for resampling for this preset
				aud_filters_func
				;;
				*)
				aud_filters_func
				test "$ALLOW_AUD_RESAMPLE" = "y" && audio_resample_func
				;;
			esac
		fi
	fi
}

audio_filters_var_func() {
	case "$1" in
		ipod)
		afilters[$i]="${volnorm[$i]}${volume[$i]}${pan[$i]}${audchannels[$i]}${audeq[$i]},lavcresample=48000:16:1 -srate 48000"
		channels[$i]="-channels 2"
		;;
		*)
		afilters[$i]="${volnorm[$i]}${volume[$i]}${pan[$i]}${audchannels[$i]}${audeq[$i]}${resample[$i]}"
		;;
	esac
}

audio_stream_copy_func() {
	case "$source" in
		dir)
		case "${audiocodec[1]}" in
			copy|COPY)
			echo
			error "-> Audio stream copy is not recommended with"
			error "   directory batch encoding if you are going"
			error "   to remux the encodes to MKV/MP4/OGM"
			echo
			;;
		esac
		;;
	esac
}

track_echo_func() {
	if [ "${TRACKID[2]}" = "yes" -o "${TRACKID[3]}" = "yes" ]; then
		echo
	fi
}

select_audio_codec_func() {
	for i in {1..3}; do
		if [ "${TRACKID[$i]}" = "yes" ]; then
			case "$1" in
				ipod)
				echo
				printf "Track $i: Select the Audio Codec [AAC/neroAAC/COPY/NOSOUND - default is AAC]: "
				;;
				*)
				printf "Track $i: Select the Audio Codec [default is MP3]: "
				;;
			esac
			read audiocodec[$i]
			audiocodec[$i]="$(echo ${audiocodec[$i]} | tr '[:upper:]' '[:lower:]')"
			check_audio_codec_func
			audio_stream_copy_func
		fi
	done
	track_echo_func
}

# Call the audio functions above.
# Order is important here and the
# correct way to call the functions
# is as follows:
#
# *_audio_func
# audio_channels_decode_func
# audio_filters_func
# audio_filters_var_func
# track_echo_func
case "$3" in
	ipod)
	select_audio_codec_func $3
	for i in {1..3}; do
		if [ "${TRACKID[$i]}" = "yes" ]; then
			case "${audiocodec[$i]}" in
				aac|"")
				audiocodec[$i]=aac
				aac_audio_func $3
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				neroaac)
				neroaac_audio_func $3
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				copy)
				acodec[$i]="-oac copy"
				channels[$i]="-channels 2"
				;;
				nosound)
				acodec[$i]="-nosound"
				;;
			esac
		fi
	done
	;;
	*)
	echo
	brown "Available Audio Codecs"
	brown "~~~~~~~~~~~~~~~~~~~~~~"
	echo "MP3 -----> Container support: AVI, MKV, MP4, OGM"
	echo "AC3 -----> Container support: AVI, MKV, MP4, OGM"
	echo "AAC -----> Container support: AVI, MKV, MP4"
	echo "AAC+ ----> Container support: MP4, MKV"
	echo "neroAAC -> Container support: MP4, MKV"
	echo "VORBIS --> Container support: MP4, MKV, OGM"
	echo "FLAC ----> Container support: MKV"
	echo "PCM -----> Container support: AVI, MKV, OGM"
	echo "COPY ----> Container support: Depends on audio codec"
	echo "NOSOUND -> Container support: AVI, MKV, MP4, OGM"
	echo
	select_audio_codec_func $3
	for i in {1..3}; do
		if [ "${TRACKID[$i]}" = "yes" ]; then
			case "${audiocodec[$i]}" in
				mp3|"")
				mp3_audio_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				ac3)
				ac3_audio_func
				audio_channels_decode_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				aac)
				aac_audio_func
				audio_channels_decode_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				aac+)
				aacplus_audio_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				neroaac)
				neroaac_audio_func
				audio_channels_decode_func
				neroaac_hev2_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				vorbis)
				vorbis_audio_func
				audio_channels_decode_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				flac)
				flac_audio_func
				audio_channels_decode_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				;;
				pcm)
				for t in {2..3}; do
					if [ "${TRACKID[$t]}" = "yes" ]; then
						error "-> Track $t: PCM audio not supported yet!"
						rmtemp
					fi
				done
				audio_channels_decode_func
				audio_filters_func $3
				audio_filters_var_func $3
				track_echo_func
				acodec[$i]="-oac pcm"
				;;
				copy)
				audio_channels_decode_func
				track_echo_func
				acodec[$i]="-oac copy"
				;;
				nosound)
				acodec[$i]="-nosound"
				aid[$i]=
				;;
				*)
				error "-> Track $i: Unknown audio codec: '${audiocodec[$i]}'"
				rmtemp
				;;
			esac
		fi
	done
	;;
esac

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

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

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

case "$SKIPBTRCALC" in
	yes)
	false
	;;
	*)
	case "$1" in
		-[1-3]p)
		case "${audiocodec[1]}" in
			mp3|ac3|aac|aac+|neroaac|vorbis|pcm|copy|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 "divxenc can calculate the video bitrate for you"
				echo "based on the video length, chosen audio bitrate and"
				echo "target file size. The only thing you have to provide"
				echo "here is the desired target size in Mebibytes for the"
				echo "encode. After that, you can choose to keep the bitrate"
				echo "calculated by divxenc, or you can provide a new one."
				echo ""
				printf "Specify the desired Target File Size in Mebibytes [default is 700]: "
				read tfsm
				if [ -z "$tfsm" ]; then
					TARGET_SIZE=700
				else
					TARGET_SIZE=$tfsm
				fi
				# Get the chosen audio bitrate
				for i in {1..3}; do
					if [ "${TRACKID[$i]}" = "yes" ]; then
						case "${audiocodec[$i]}" in
							ac3)
							AUDIO_BITRATE[$i]=${abitrate[$i]}
							;;
							mp3|"")
							case "${mp3mode[$i]}" in
								a*|A*|c*|C*|"")
								AUDIO_BITRATE[$i]=$(echo ${abitrate[$i]} | awk -F= '{print $2}')
								;;
								v*|V*)
								# Use 10 kbps lesser compared
								# to the LAME specs
								case "${abitrate[$i]}" in
									q=0) AUDIO_BITRATE[$i]=230 ;;
									q=1) AUDIO_BITRATE[$i]=200 ;;
									q=2) AUDIO_BITRATE[$i]=180 ;;
									q=3) AUDIO_BITRATE[$i]=165 ;;
									q=4) AUDIO_BITRATE[$i]=155 ;;
									q=5) AUDIO_BITRATE[$i]=120 ;;
									q=6) AUDIO_BITRATE[$i]=105 ;;
									q=7) AUDIO_BITRATE[$i]=90 ;;
									q=8) AUDIO_BITRATE[$i]=75 ;;
									q=9) AUDIO_BITRATE[$i]=54 ;;
								esac
								;;
								p*|P*)
								case "${mp3preset[$i]}" in
									0|"") AUDIO_BITRATE[$i]=160 ;;
									1) AUDIO_BITRATE[$i]=185 ;;
									2) AUDIO_BITRATE[$i]=210 ;;
									3) AUDIO_BITRATE[$i]=320 ;;
								esac
								;;
							esac
							;;
							aac)
							AUDIO_BITRATE[$i]=$(echo ${br[$i]} | awk -F= '{print $2}')
							;;
							aac+)
							AUDIO_BITRATE[$i]=${aacplusbr[$i]}
							;;
							neroaac)
							AUDIO_BITRATE[$i]=$(($(echo ${neroaacbr[$i]} | awk '{print $2}')/1000))
							;;
							vorbis)
							case "${vorbmode[$i]}" in
								a*|A*)
								AUDIO_BITRATE[$i]=$(echo ${vorbq[$i]} | awk '{print $2}')
								;;
								v*|V*|"")
								# Quality values -> bitrate mappings
								case "$(echo ${vorbq[$i]} | awk '{print $2}')" in
									-1) AUDIO_BITRATE[$i]=45 ;;
									0) AUDIO_BITRATE[$i]=64 ;;
									1) AUDIO_BITRATE[$i]=80 ;;
									2) AUDIO_BITRATE[$i]=96 ;;
									3) AUDIO_BITRATE[$i]=112 ;;
									4) AUDIO_BITRATE[$i]=128 ;;
									5) AUDIO_BITRATE[$i]=160 ;;
									6) AUDIO_BITRATE[$i]=192 ;;
									7) AUDIO_BITRATE[$i]=224 ;;
									8) AUDIO_BITRATE[$i]=256 ;;
									9) AUDIO_BITRATE[$i]=320 ;;
									10) AUDIO_BITRATE[$i]=500 ;;
								esac
								;;
							esac
							;;
							pcm)
							# Get channels info. Resampling is not
							# taken into account so we assume 48 kHz
							case "$(echo ${channels[$i]} | awk '{print $2}')" in
								2|""|*) AUDIO_BITRATE[$i]=1536 ;;
								4) AUDIO_BITRATE[$i]=3072 ;;
								5) AUDIO_BITRATE[$i]=3840 ;;
								6) AUDIO_BITRATE[$i]=4608 ;;
							esac
							;;
							copy)
							$MPLAYER "$sourcetype" $device $MPLAYEROPTS ${aid[$i]} -identify -vo null -frames 1 -nocache 2>/dev/null > "$TEMPDIR/copybitrate$i"
							AUDIO_BITRATE[$i]=$(echo $(($(grep '^ID_AUDIO_BITRATE' "$TEMPDIR/copybitrate$i" | tail -n 1 | awk -F= '{print $2}')/1000)) | awk -F. '{print $1}')
							rm -f "$TEMPDIR/copybitrate$i"
							;;
							nosound)
							AUDIO_BITRATE[$i]=0
							;;
						esac
					fi
				done
				
				if [ ! -z "${aid[2]}" -a ! -z "${aid[3]}" ]; then
					AUDBTR=$((${AUDIO_BITRATE[1]}+${AUDIO_BITRATE[2]}+${AUDIO_BITRATE[3]}))
					BTRINFO="(${AUDIO_BITRATE[1]} kbps + ${AUDIO_BITRATE[2]} kbps + ${AUDIO_BITRATE[3]} kbps)"
				elif [ ! -z "${aid[2]}" -a -z "${aid[3]}" ]; then
					AUDBTR=$((${AUDIO_BITRATE[1]}+${AUDIO_BITRATE[2]}))
					BTRINFO="(${AUDIO_BITRATE[1]} kbps + ${AUDIO_BITRATE[2]} kbps)"
				elif [ -z "${aid[2]}" -a ! -z "${aid[3]}" ]; then
					AUDBTR=$((${AUDIO_BITRATE[1]}+${AUDIO_BITRATE[3]}))
					BTRINFO="(${AUDIO_BITRATE[1]} kbps + ${AUDIO_BITRATE[3]} kbps)"
				else
					AUDBTR=${AUDIO_BITRATE[1]}
				fi
				echo ""
				brown "Available Formulas"
				brown "~~~~~~~~~~~~~~~~~~"
				echo "0 -> MeGUI formula"
				echo "1 -> divxenc's refactored MeGUI formula"
				echo "2 -> divxenc/ripdvd old formula"
				echo "3 -> Use a custom factor value"
				echo ""
				printf "Which formula to use? [default is 0]: "
				read formula
				case "$formula" in
					0|"") FACTOR="0.125" ;;
					1) FACTOR="0.1244" ;;
					2) FACTOR= ;;
					3)
					echo
					brown "Custom Factor Value"
					brown "~~~~~~~~~~~~~~~~~~~"
					echo "You can provide a custom factor value which is"
					echo "used to adjust the formula's bitrate calculation."
					echo "Lower factor values result in higher bitrates while"
					echo "higher factor values result in lower bitrates. The"
					echo "default factor is that of the MeGUI formula, which"
					echo "is 0.125. The factor of divxenc's refactored MeGUI"
					echo "formula is 0.1244 resulting in roughly 10 kbps higher"
					echo "bitrate, thus increasing the final file size by a few"
					echo "Megabytes. A factor of 0.127 for example, will result"
					echo "in a bitrate of ~20 kbps less that the default factor"
					echo "of 0.125"
					echo
					printf "Provide the Factor value [default is 0.125 (MeGUI's factor)]: "
					read customfactor
					if [ -z "$customfactor" ]; then
						FACTOR="0.125"
					else
						FACTOR="$customfactor"
					fi
					;;
					*)
					error "-> Unknown option: '$formula'"
					rmtemp
					;;
				esac
				echo ""
				green "-> Detecting video length..."
				$MPLAYER "$sourcetype" $device $MPLAYEROPTS $vid -demuxer lavf -identify -vo null -frames 1 -ao null -nocache 2>/dev/null > "$TEMPDIR/video_length"
				VIDEO_LENGTH=$(grep "^ID_LENGTH" "$TEMPDIR/video_length" | awk -F= '{print $2}')
				rm -f "$TEMPDIR/video_length"
				if [ -z "$VIDEO_LENGTH" ]; then
					echo ""
					green "-> Could not detect the video length!"
					green "-> Will skip video bitrate calculation!"
					echo ""
				else
					if [ ! -z "$ofps" ]; then
						FRAMES=$(echo "scale=0; $VIDEO_LENGTH * $(echo "$ofps" | awk '{print $2}')" | $BC -l | awk -F. '{print $1}')
					else
						FRAMES=$(echo "scale=0; $VIDEO_LENGTH * $GETFPS" | $BC -l | awk -F. '{print $1}')
					fi
					case "$formula" in
						0|1|3|"")
						EST_BITRATE=$(echo "scale=0; ($TARGET_SIZE * 1024 * 1024 - $FRAMES * 24 - $AUDBTR * 1000 * $VIDEO_LENGTH * $FACTOR) / ($VIDEO_LENGTH * $FACTOR) / 1000" | $BC -l)
						;;
						2)
						EST_BITRATE=$(echo "scale=0; ($TARGET_SIZE * 8192 / $VIDEO_LENGTH) - $AUDBTR" | $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: $FRAMES"
					green "-> Chosen/detected audio bitrate is $AUDBTR kbps $BTRINFO"
					echo
					green "-> Estimated video bitrate for $TARGET_SIZE MiB: $EST_BITRATE kbps"
					green "-> Bits Per Pixel value: $BPP bpp"
					green "-> Bits Per Block value: $BPB bpb"
					echo
					printf "Specify the new video bitrate in kbps [default is $EST_BITRATE]: "
					read new_bitrate
					if [ -z "$new_bitrate" ]; then
						vbitrate="vbitrate=$EST_BITRATE"
					else
						vbitrate="vbitrate=$new_bitrate"
					fi
				fi
			fi
			;;
		esac
		;;
	esac
	;;
esac

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

# Audio/video filters variables for all
# passes. Since all filters are the same in
# each pass, we put them in a single
# variable to reduce code duplication and
# filter maintenance.
#
# The softskip filter should come after filters
# which need to see duplicate or skipped frames
# in order to operate 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 but it can also be done after it
# (it's faster that way too) and since I don't want to
# maintain two filter chains, one for when tfields is
# used and one when it isn't, we'll always deinterlace
# after 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.
#

# Video filters chain
videofilters="-vf $(echo $ivtcfilter$delogofilter$cropfilter$deintfilter$fpsfilter$ild$deblockfilter$denoisefilter$debandfilter$ili$brightnessfilter$colorspacefilter,softskip,$dsizefilter$expandfilter_bfr$scale$isws$swsparam$expandfilter_afr$noisefilter$unsharpfilter$eq2filter,harddup$intfilter$telecinefilter | sed 's|^,||; s|,,|,|g; s|,$||')"

# Audio filters chain
for i in {1..3}; do
	if [ "${TRACKID[$i]}" = "yes" ]; then
		if [ ! -z "${afilters[$i]}" ]; then
			audiofilters[$i]="-af $(echo ${afilters[$i]} | sed 's|^,||; s|,,|,|g; s|,$||')"
		fi
	fi
done

case "$1" in
	-1p|-fq)
	if [ ! -z "${vobsubout[1]}" ]; then
		menc_subtitle="${subtitle[1]} ${vobsubout[1]}"
	else
		menc_subtitle="${subtitle[1]}"
	fi
	;;
	-[2-3]p)
	if [ ! -z "${vobsubout[1]}" ]; then
		menc_subtitle="${subtitle[1]} ${vobsubout[1]}"
		menc_hardsub="-nosub"
	else
		menc_subtitle="${subtitle[1]}"
		menc_hardsub="${subtitle[1]}"
	fi
	# Log file for 2- and 3-pass
	case "$source" in
		dir)	PASSLOG="-passlogfile \"$TEMPDIR/\${i%.*}.log\"" ;;
		*)	PASSLOG="-passlogfile \"$TEMPDIR/$(basename "${OUTPUT%.*}.log")\"" ;;
	esac
	;;
esac

case "$source" in
	dvd|vcd)
	if [ ! -z "$($MPLAYER -vc help 2>/dev/null | grep 'libmpeg2')" ]; then
		MPEGVC="-vc mpeg12"
	fi
	;;
esac

mencoder_opts() {
	case "$1" in
		-1p|-fq)	pass_output1="-o \"$OUTPUT\"" ;;
		-2p) 		passopt1="vpass=1:turbo:"; passopt2="vpass=2:"; pass_output1="-o /dev/null"; pass_output2="-o \"$OUTPUT\"" ;;
		-3p) 		passopt1="vpass=1:turbo:"; passopt2="vpass=3:"; pass_output1="-o /dev/null"; pass_output2="-o /dev/null" ;;
	esac
	# Pass one
	echo "$priority_level $MENCODER \"$sourcetype\" $pass_output1 $PASSLOG $MPEGVC $chapters $device $dvdangle $nosub $menc_subtitle $vid $ffourcc $fps $ofps $videofilters $field_dominance $sws $aspect $noodml \
	${aid[1]} ${audiofilters[1]} ${channels[1]} ${acodec[1]} -ovc lavc -lavcopts vcodec=mpeg4:$passopt1$vbitrate$divxparams$stats $quiet"
	case "$1" in
		-[2-3]p)
		# Pass two
		echo
		echo "$priority_level $MENCODER \"$sourcetype\" $pass_output2 $PASSLOG $MPEGVC $chapters $device $dvdangle $nosub $menc_hardsub $vid $ffourcc $fps $ofps $videofilters $field_dominance $sws $aspect $noodml \
		${aid[1]} ${audiofilters[1]} ${channels[1]} ${acodec[1]} -ovc lavc -lavcopts vcodec=mpeg4:$passopt2$vbitrate$divxparams$stats $quiet"
		case "$1" in
			-3p)
			# Pass three
			echo
			echo "$priority_level $MENCODER \"$sourcetype\" -o \"$OUTPUT\" $PASSLOG $MPEGVC $chapters $device $dvdangle $nosub $menc_hardsub $vid $ffourcc $fps $ofps $videofilters $field_dominance $sws $aspect $noodml \
			${aid[1]} ${audiofilters[1]} ${channels[1]} ${acodec[1]} -ovc lavc -lavcopts vcodec=mpeg4:$passopt2$vbitrate$divxparams$stats $quiet"
			;;
		esac
		;;
	esac
}

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

DIVX1PFQ="$TEMPDIR/pass1_fq"
DIVX2P1="$TEMPDIR/pass1"
DIVX2P2="$TEMPDIR/pass2"
DIVX2P3="$TEMPDIR/pass3"

case "$source" in
	dir)
	BATCH="$DIVXENCDIR/batch$$"
	echo "#!/bin/bash" > "$BATCH"
	echo "# Automatically generated batch file by divxenc $version on $(date)" >> "$BATCH"
	echo "" >> "$BATCH"
	chmod 755 "$BATCH"
	echo "################### START OF COMMANDS ###################" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "cd \"$(dirname "$sourcetype")\"" >> "$BATCH"
	echo "test -d \"$(dirname "$OUTPUT")\" || mkdir -p \"$(dirname "$OUTPUT")\"" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "for i in *; do" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "if [ -f \"\$i\" ]; then" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "test -d \"$TEMPDIR\" || mkdir -p \"$TEMPDIR\"" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "echo" >> "$BATCH"
	echo "echo -e \"\e[1;32m-> Processing file '$(dirname "$sourcetype")/\$i'\e[0;39;49m\"" >> "$BATCH"
	echo "echo" >> "$BATCH"
	echo "sleep 3" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "$(mencoder_opts $1 | sed "s|$sourcetype|\$i|g")" >> "$BATCH"
	echo "" >> "$BATCH"
	;;
	*)
	case "$1" in
		-1p|-fq)
		mencoder_opts $1 > "$DIVX1PFQ"
		;;
		-2p)
		mencoder_opts $1 > "$TEMPDIR/divxenc_2pass"
		# Split 2pass file
		# into two files
		cat "$TEMPDIR/divxenc_2pass" | head -n 1 > "$DIVX2P1"
		cat "$TEMPDIR/divxenc_2pass" | tail -n 1 > "$DIVX2P2"
		rm -f "$TEMPDIR/divxenc_2pass"
		;;
		-3p)
		mencoder_opts $1 > "$TEMPDIR/divxenc_3pass"
		# Split 3pass file
		# into three files
		cat "$TEMPDIR/divxenc_3pass" | head -n 1 > "$DIVX2P1"
		cat "$TEMPDIR/divxenc_3pass" | head -n 3 | tail -n 1 > "$DIVX2P2"
		cat "$TEMPDIR/divxenc_3pass" | tail -n 1 > "$DIVX2P3"
		rm -f "$TEMPDIR/divxenc_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
	file|dvd|vcd)
	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 $DIVX1PFQ)
			;;
			-2p)
			brown "First pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo $(cat $DIVX2P1)
			echo ""
			brown "Second pass options"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo $(cat $DIVX2P2)
			;;
			-3p)
			brown "First pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo $(cat $DIVX2P1)
			echo ""
			brown "Second pass options"
			brown "~~~~~~~~~~~~~~~~~~~"
			echo $(cat $DIVX2P2)
			echo ""
			brown "Third pass options"
			brown "~~~~~~~~~~~~~~~~~~"
			echo $(cat $DIVX2P3)
			;;
		esac
		echo ""
	fi
	;;
esac

# Encode a sample
if [ "$ALLOW_SAMPLE_ENCODING" = "y" ]; then
	case "$source" in
		file|dvd|vcd)
		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 "$DIVX1PFQ" | sed -e "s|$MENCODER|$MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > "$TEMPDIR/sampleopts1"
				;;
				-2p)
				cat "$DIVX2P1" | sed "s|$MENCODER|$MENCODER $samplepos $sampledur|" > "$TEMPDIR/sampleopts1"
				cat "$DIVX2P2" | sed -e "s|$MENCODER|$MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > "$TEMPDIR/sampleopts2"
				;;
				-3p)
				cat "$DIVX2P1" | sed "s|$MENCODER|$MENCODER $samplepos $sampledur|" > "$TEMPDIR/sampleopts1"
				cat "$DIVX2P2" | sed "s|$MENCODER|$MENCODER $samplepos $sampledur|" > "$TEMPDIR/sampleopts2"
				cat "$DIVX2P3" | sed -e "s|$MENCODER|$MENCODER $samplepos $sampledur|" -e "s|\"$OUTPUT\"|$HOME/sample_$$.avi|" > "$TEMPDIR/sampleopts3"
				;;
			esac
			for i in {1..3}; do
				if [ -f "$TEMPDIR/sampleopts$i" ]; then
					green "-> Running pass $i..."
					source "$TEMPDIR/sampleopts$i" >/dev/null 2>&1
					green "-> Done"
				fi
			done
			for i in sampleopts* *.log; do
				rm -f "$TEMPDIR/$i"
			done
			# Remove subs if any
			test -e "${IDXFILE[1]}" && rm -f "${IDXFILE[1]}" "${SUBFILE[1]}"
			if [ -e "$HOME/sample_$$.avi" ]; then
				green "-> Previewing..."
				sleep 1
				$MPLAYER $MPLAYEROPTS -nocache "$HOME/sample_$$.avi" >/dev/null 2>&1
			else
				error "-> Failed"
			fi
			echo
		fi
		;;
	esac
fi

# Ask user to save the MEncoder parameters so
# he/she can use them again.
case "$source" in
	file|dvd|vcd)
	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
		if [ -z "$storeopts" ]; then
			OPTSFILE="$HOME/batchfile"
		else
			if [ -z "$(echo "$storeopts" | grep '^/')" ]; then
				echo ""
				green "-> You have to provide the full path!"
				green "-> Using default file: $HOME/batchfile"
				echo ""
				OPTSFILE="$HOME/batchfile"
			else
				OPTSFILE="$storeopts"
			fi
		fi
		CMDSTART="################### START OF COMMANDS ###################"
		DIRTEST="test -d \"$(dirname "$OUTPUT")\" || mkdir -p \"$(dirname "$OUTPUT")\""
		CONFTEST="test -d \"$TEMPDIR\" || mkdir -p \"$TEMPDIR\""
		FILETEST="test -e \"$OUTPUT\" && mv -f \"$OUTPUT\" \"$OUTPUT.old\""
		# Dump the second/third subtitle if selected
		case "${audiocodec[1]}" in
			nosound)
			audfmt="-nosound"
			;;
			*)
			audfmt="-oac pcm"
			;;
		esac
		if [ ! -z "${subtitle[2]}" ]; then
			SUB2="$MENCODER $sourcetype $device $MPEGVC $chapters ${aid[1]} $ofps ${subtitle[2]} ${vobsubout[2]} $audfmt -ovc copy -o /dev/null"
		fi
		if [ ! -z "${subtitle[3]}" ]; then
			SUB3="$MENCODER $sourcetype $device $MPEGVC $chapters ${aid[1]} $ofps ${subtitle[3]} ${vobsubout[3]} $audfmt -ovc copy -o /dev/null"
		fi
		# Write out...
		if [ -e "$OPTSFILE" ]; then
			if [ -z "$(grep '^#!/bin/bash' "$OPTSFILE")" ]; then
				mv -f "$OPTSFILE" "$OPTSFILE$$"
				echo "#!/bin/bash" > "$OPTSFILE"
				echo "# Automatically generated by divxenc $version on $(date)" >> "$OPTSFILE"
				echo "" >> "$OPTSFILE"
				cat "$OPTSFILE$$" >> "$OPTSFILE"
				rm -f "$OPTSFILE$$"
				chmod 755 "$OPTSFILE"
			fi
		else
			echo "#!/bin/bash" > "$OPTSFILE"
			echo "# Automatically generated by divxenc $version on $(date)" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			chmod 755 "$OPTSFILE"
		fi
		echo "$CMDSTART" >> "$OPTSFILE"
		echo "" >> "$OPTSFILE"
		echo "$DIRTEST" >> "$OPTSFILE"
		echo "$CONFTEST" >> "$OPTSFILE"
		echo "$FILETEST" >> "$OPTSFILE"
		echo "" >> "$OPTSFILE"
		case "$1" in
			-1p|-fq)
			echo $(cat $DIVX1PFQ) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$SUB2" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$SUB3" >> "$OPTSFILE"
			echo "sleep 2" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			;;
			-2p)
			echo $(cat $DIVX2P1) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo $(cat $DIVX2P2) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$SUB2" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$SUB3" >> "$OPTSFILE"
			echo "sleep 2" >> "$OPTSFILE"
			;;
			-3p)
			echo $(cat $DIVX2P1) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo $(cat $DIVX2P2) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo $(cat $DIVX2P3) >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$SUB2" >> "$OPTSFILE"
			echo "" >> "$OPTSFILE"
			echo "$SUB3" >> "$OPTSFILE"
			echo "sleep 2" >> "$OPTSFILE"
			;;
		esac
	fi
	;;
esac

# Audio code for all audio tracks. Currently
# we have to separate the code for the first
# track from the 2nd & 3rd since if the user
# selects to copy only one track from a DVD,
# we'll get extra encoder options which the for
# loop adds but which must *not* be there.
# This approach results in a bit more code but
# what the heck, maybe one day I'll fix it :)
#
# Nasty hack for ivtc/fps/deint filters.
# Filter order is all wrong but who
# cares at this point

if [ ! -z "$ivtcfilter" ]; then
	vidfilter=",$(echo $ivtcfilter | sed 's|,$||')"
fi
if [ ! -z "$fpsfilter" ]; then
	vidfilter=",$(echo $fpsfilter | sed 's|,$||')"
fi
if [ "$deintmethod" = "0" ]; then
	vidfilter=",framestep=2"
elif [ "$deintmethod" = "2" ]; then
	vidfilter=",yadif=3"
fi
vidfilteropts="-sws 1 -vf scale=16:16$vidfilter$intfilter$telecinefilter,softskip,harddup"
vidcodecopts="-ovc lavc -lavcopts vcodec=mpeg2video"

# For neroAAC, AAC+, FLAC and Vorbis audio
# $FIFO is used only once and is global
# meaning it is used for all audio track
mkfifo "$TEMPDIR/audio.wav"
FIFO="test -p \"$TEMPDIR/audio.wav\" || mkfifo \"$TEMPDIR/audio.wav\""
MPL="$MPLAYER \"$OUTPUT\" $MPLAYEROPTS -really-quiet -vc null -vo null -nocache ${channels[1]} -ao pcm:fast:file=\"$TEMPDIR/audio.wav\""
NERO="$NEROAACENC -ignorelength ${neroaacbr[1]} -if \"$TEMPDIR/audio.wav\" -of \"$TEMPDIR/audio.aac\" &"
AACPLUS="$AACPLUSENC \"$TEMPDIR/audio.wav\" \"$TEMPDIR/audio.aac\" ${aacplusbr[1]} &"
OGG="$OGGENC ${vorbq[1]} \"$TEMPDIR/audio.wav\" -o \"$TEMPDIR/audio.ogg\" &"
FLACENC="$FLAC ${flacq[1]} \"$TEMPDIR/audio.wav\" -o \"$TEMPDIR/audio.flac\" &"

case "${audiocodec[1]}" in
	aac+|neroaac|vorbis|flac)
	case "$source" in
		dir)	AUDIOENC[1]="$BATCH" ;;
		*)	AUDIOENC[1]="$TEMPDIR/audioenc1" ;;
	esac
	aud1_export_func() {
		echo "$FIFO"
		case "${audiocodec[1]}" in
			aac+)		echo "$AACPLUS" ;;
			neroaac)	echo "$NERO" ;;
			vorbis)		echo "$OGG" ;;
			flac)		echo "$FLACENC" ;;
		esac
		echo "$MPL"
		if [ "${nero2p[1]}" = "y" -o "${nero2p[1]}" = "Y" ]; then
			echo "sleep 2"
			echo "$MPL"
		fi
		echo "sleep 2"
		echo
	}
	aud1_export_func >> "${AUDIOENC[1]}"
	if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
		aud1_export_func >> "$OPTSFILE"
	fi
	;;
esac

# Get the audio codec from the
# input source when using audio
# stream copy. Based on detected
# audio codec, decision is made
# if we allow certain containers
case "${audiocodec[1]}" in
	copy)
	echo
	green "-> Track 1: Detecting audio codec of the $type..."
	AUDCODEC=$($MPLAYER "$sourcetype" $device $MPLAYEROPTS ${aid[1]} -vo null -frames 1 -identify -nocache 2>/dev/null | grep '^ID_AUDIO_CODEC' | tail -n 1 | awk -F= '{print $2}')
	case "$AUDCODEC" in
		*a52*|*ac3*)	audiocodec[1]="ffac3"; detectaud[1]="AC3" ;;
		*eac3*)		audiocodec[1]="ffeac3"; detectaud[1]="E-AC3" ;;
		*dca*|*dts*)	audiocodec[1]="ffdts"; detectaud[1]="DTS" ;;
		*dvdpcm*)	audiocodec[1]="unsupported"; detectaud[1]="LPCM" ;;
		*vorbis*)	audiocodec[1]="ffvorbis"; detectaud[1]="Vorbis" ;;
		*pcm*)		audiocodec[1]="ffpcm"; detectaud[1]="PCM" ;;
		*faad*|*aac*)	audiocodec[1]="ffaac"; detectaud[1]="AAC" ;;
		*mp3*|*mad*)	audiocodec[1]="ffmp3"; detectaud[1]="MP3" ;;
		*flac*)		audiocodec[1]="ffflac"; detectaud[1]="FLAC" ;;
		*wma*)		audiocodec[1]="unsupported"; detectaud[1]="WMA" ;;
		*|"")		audiocodec[1]="unsupported"; detectaud[1]="unknown/unsupported" ;;
	esac
	green "-> Track 1: Detected ${detectaud[1]} audio"
	if [ "${audiocodec[1]}" = "unsupported" ]; then
		green "-> Skipping MKV/MP4/OGM containers"
	fi
	;;
esac

# Code for second/third DVD audio track
for i in {2..3}; do
	if [ "${TRACKID[$i]}" = "yes" ]; then
		# Set global variables
		AUDIOENC[$i]="$TEMPDIR/audioenc$i"
		NERO[$i]="$NEROAACENC -ignorelength ${neroaacbr[$i]} -if \"$TEMPDIR/audio.wav\" -of \"$TEMPDIR/audio$i.aac\" &"
		AACPLUS[$i]="$AACPLUSENC \"$TEMPDIR/audio.wav\" \"$TEMPDIR/audio$i.aac\" ${aacplusbr[$i]} &"
		OGG[$i]="$OGGENC ${vorbq[$i]} \"$TEMPDIR/audio.wav\" -o \"$TEMPDIR/audio$i.ogg\" &"
		FLACENC[$i]="$FLAC ${flacq[$i]} \"$TEMPDIR/audio.wav\" -o \"$TEMPDIR/audio$i.flac\" &"
		MPL[$i]="$MPLAYER \"$TEMPDIR/audio$i.avi\" $MPLAYEROPTS ${channels[$i]} ${audiofilters[$i]} -really-quiet -vc null -vo null -nocache -ao pcm:fast:file=\"$TEMPDIR/audio.wav\""
		
		# Check for LPCM audio on DVDs
		AUDCODEC[$i]=$($MPLAYER $sourcetype $device $MPLAYEROPTS ${aid[$i]} -vo null -frames 1 -identify -nocache 2>/dev/null | grep '^ID_AUDIO_CODEC' | tail -n 1 | awk -F= '{print $2}')
		case "${AUDCODEC[$i]}" in
			*dvdpcm*)	AUDCODECOPTS[$i]="-oac pcm" ;;
			*)		AUDCODECOPTS[$i]="-oac copy" ;;
		esac
		# Identify audio codec of the DVD
		# for audio stream copy
		case "${audiocodec[$i]}" in
			copy)
			echo
			green "-> Track $i: Detecting audio codec..."
			case "${AUDCODEC[$i]}" in
				*a52*|*ac3*)	audiocodec[$i]="ffac3"; detectaud[$i]="AC3" ;;
				*dca*|*dts*)	audiocodec[$i]="ffdts"; detectaud[$i]="DTS" ;;
				*dvdpcm*)	audiocodec[$i]="unsupported"; detectaud[$i]="LPCM" ;;
				*|"")		audiocodec[$i]="unsupported"; detectaud[$i]="unknown/unsupported" ;;
			esac
			green "-> Track $i: Detected ${detectaud[$i]} audio"
			if [ "${audiocodec[$i]}" = "unsupported" ]; then
				green "-> Skipping track $i for the MKV/MP4/TS/OGM containers"
			fi
			;;
		esac
		case "${audiocodec[$i]}" in
			mp3|aac|ac3|"")
			if [ -z "${audiocodec[$i]}" ]; then
				audext[$i]=mp3
			else
				audext[$i]=${audiocodec[$i]}
			fi
			MENC[$i]="$MENCODER $sourcetype $device $MPEGVC $chapters ${aid[$i]} ${channels[$i]} $fps $ofps ${acodec[$i]} ${audiofilters[$i]} $vidfilteropts $vidcodecopts -of rawaudio -o \"$TEMPDIR/audio$i.${audext[$i]}\""
			;;
			ffac3|ffdts)
			MENC[$i]="$MENCODER $sourcetype $device $MPEGVC $chapters ${aid[$i]} ${channels[$i]} $fps $ofps $vidcodecopts $vidfilteropts -oac copy -of rawaudio -o \"$TEMPDIR/audio$i.raw\""
			;;
			aac+|neroaac|vorbis|flac)
			MENC[$i]="$MENCODER $sourcetype $device $MPEGVC $chapters ${aid[$i]} ${channels[$i]} $fps $ofps $vidcodecopts $vidfilteropts ${AUDCODECOPTS[$i]} -o \"$TEMPDIR/audio$i.avi\""
			;;
		esac
		aud23_export_func() {
			case "${audiocodec[$i]}" in
				mp3|aac|ac3|ffac3|ffdts|"")
				echo "$FIFO"
				echo "${MENC[$i]}"
				echo "sleep 2"
				;;
				aac+|neroaac|vorbis|flac)
				echo "$FIFO"
				echo "${MENC[$i]}"
				echo "sleep 2"
				echo
				case "${audiocodec[$i]}" in
					aac+)		echo "${AACPLUS[$i]}" ;;
					neroaac)	echo "${NERO[$i]}" ;;
					vorbis)		echo "${OGG[$i]}" ;;
					flac)		echo "${FLACENC[$i]}" ;;
				esac
				echo "${MPL[$i]}"
				if [ "${nero2p[$i]}" = "y" -o "${nero2p[$i]}" = "Y" ]; then
					echo "sleep 2"
					echo "${MPL[$i]}"
				fi
				echo "sleep 2"
				;;
			esac
			echo
		}
		aud23_export_func >> "${AUDIOENC[$i]}"
		if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
			aud23_export_func >> "$OPTSFILE"
		fi
	fi
done
test ! -z "${detectaud[*]}" && echo

# Get audio channels info
# Used for audio tagging
for i in {1..3}; do
	if [ "${TRACKID[$i]}" = "yes" ]; then
		if [ ! -z "${channels[$i]}" ]; then
			case "$(echo "${channels[$i]}" | awk '{print $2}')" in
				1) chaninfo[$i]="Mono" ;;
				2) chaninfo[$i]="Stereo" ;;
				3) chaninfo[$i]="3.0" ;;
				4) chaninfo[$i]="4.0" ;;
				5) chaninfo[$i]="5.0" ;;
				6) chaninfo[$i]="5.1" ;;
				7) chaninfo[$i]="6.1" ;;
				8) chaninfo[$i]="7.1" ;;
				*) chaninfo[$i]="$(echo "${channels[$i]}" | awk '{print $2}')" ;;
			esac
		else
			chaninfo[$i]="Stereo"
		fi
	fi
done

# Ask user if he wants to convert
# from AVI to Matroska container
if [ "$ALLOW_MKV_MUXING" = "y" ]; then
	case "${audiocodec[1]}" in
		mp3|ffmp3|aac|aac+|neroaac|ffaac|vorbis|ffvorbis|ac3|ffac3|ffeac3|ffdts|pcm|ffpcm|flac|ffflac|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 "-> Will skip AVI to MKV conversion!"
				echo ""
			else
				avi_to_mkv=yes
				
				# Import of external subtitles.
				# Input type agnostic. Only
				# allow supported subtitle formats
				# by MKV. Others will be skipped
				for i in {1..3}; do
					if [ ! -z "${EXTSUB[$i]}" ]; then
						case "${EXTSUB[$i]##*.}" in
							idx|IDX|srt|SRT|ass|ASS|ssa|SSA)
							MKVSUBS="$MKVSUBS \"$(eval "echo \${EXTSUB[$i]}")\""
							;;
							*)
							echo
							green "-> Subtitle format '$(echo ${EXTSUB[$i]##*.} | tr '[:lower:]' '[:upper:]')' not supported by MKV!"
							green "-> Supported subtitle formats are: IDX, SRT, ASS/SSA"
							green "-> Skipping import of '${EXTSUB[$i]}'"
							echo
							;;
						esac
					fi
				done
				
				case "$source" in
					file|dvd|vcd)
					# Set MKV title
					MKVTITLE="--title \"$(basename "${OUTPUT%.*}")\""
					TRACKTITLE="--track-name 0:\"$(basename "${OUTPUT%.*}")\""
					printf "Specify the Release Year of the content [press 'Enter' to skip]: "
					read mkvyear
					printf "Specify a Genre for the content [press 'Enter' to skip]: "
					read mkvgenre
					# Add cover
					printf "Provide a Cover file in jpeg/png format [press 'Enter' to skip]: "
					read -e mkvcover
					if [ ! -z "$mkvcover" ]; then
						if [ ! -f "$mkvcover" ]; then
							echo
							error "-> No such file: '$mkvcover'"
							error "-> Skipping embedding of cover file"
							echo
						else
							IMGTYPE="$(basename "${mkvcover##*.}" | tr '[:upper:]' '[:lower:]')"
							case "$IMGTYPE" in
								jpg|jpeg|png)
								MKVCOVER="--attachment-mime-type image/$(echo $IMGTYPE | sed 's|jpg|jpeg|') --attachment-name Cover --attach-file \"$mkvcover\""
								;;
								*)
								echo
								error "-> Image type not supported"
								error "-> Skipping embedding of cover file"
								echo
								;;
							esac
						fi
					fi
					case "$source" in
						dvd)
						# DVD audio language for track 1
						case "${audiocodec[1]}" in
							aac+|vorbis|flac)	MKVAUDLANG1="--language 0:${AUDLANG[1]}" ;;
							*)			MKVAUDLANG1="--language 1:${AUDLANG[1]}" ;;
						esac
						# DVD audio language for track 2 & 3
						for i in {2..3}; do
							if [ "${TRACKID[$i]}" = "yes" ]; then
								MKVAUDLANG[$i]="--language -1:${AUDLANG[$i]}"
							fi
						done
						# Chapters for MKV
						if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
							printf "Import chapters information into the MKV container? [y/N]: "
							read mkvimpchap
							if [ "$mkvimpchap" = "y" -o "$mkvimpchap" = "Y" ]; then
								MKVCHAPS="--chapters \"$CHAPTERSFILE\""
							fi
						fi
						# DVD subs for MKV
						if [ ! -z "${vobsubout[1]}" -o ! -z "${vobsubout[2]}" -o ! -z "${vobsubout[3]}" ]; then
							printf "Import the ripped subtitle(s) into the MKV container? [y/N]: "
							read mkvimpsub
							if [ "$mkvimpsub" = "y" -o "$mkvimpsub" = "Y" ]; then
								for i in {1..3}; do
									[[ -z $(eval "echo \${IDXFILE[$i]}") ]] || MKVSUBS="$MKVSUBS \"$(eval "echo \${IDXFILE[$i]}")\""
								done
							fi
						fi
						;;
					esac
					;;
					dir)
					MKVTITLE="--title \"\${i%.*}\""
					TRACKTITLE="--track-name 0:\"\${i%.*}\""
					;;
				esac
				
				# Global tags
				mkvtags_func() {
					echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
					echo "<!DOCTYPE Tags SYSTEM \"matroskatags.dtd\">"
					echo
					echo "<Tags>"
					echo "  <Tag>"
					echo "    <Simple>"
					echo "      <Name>Source</Name>"
					echo "      <String>$(echo $type | sed 's|s$||')</String>"
					echo "    </Simple>"
					echo "    <Simple>"
					echo "      <Name>Title</Name>"
					case "$source" in
						dir)	echo "      <String>\${i%.*}</String>" ;;
						*)	echo "      <String>$(basename "${OUTPUT%.*}")</String>" ;;
					esac
					echo "    </Simple>"
					if [ ! -z "$mkvyear" ]; then
						echo "    <Simple>"
						echo "      <Name>Release Date</Name>"
						echo "      <String>$mkvyear</String>"
						echo "    </Simple>"
					fi
					if [ ! -z "$mkvgenre" ]; then
						echo "    <Simple>"
						echo "      <Name>Genre</Name>"
						echo "      <String>$mkvgenre</String>"
						echo "    </Simple>"
					fi
					echo "    <Simple>"
					echo "      <Name>Video Filters</Name>"
					echo "      <String>$(echo $videofilters | sed 's|^\-vf ||')</String>"
					echo "    </Simple>"
					for i in {1..3}; do
						if [ "${TRACKID[$i]}" = "yes" ]; then
							if [ ! -z "${audiofilters[$i]}" ]; then
								echo "    <Simple>"
								echo "      <Name>Audio Filters (Track $i)</Name>"
								echo "      <String>$(echo ${audiofilters[$i]} | sed 's|^\-af ||; s| \-srate.*||')</String>"
								echo "    </Simple>"
							fi
							if [ "${audiocodec[$i]}" != "nosound" ]; then
								echo "    <Simple>"
								echo "      <Name>Audio Codec (Track $i)</Name>"
								case "${audiocodec[$i]}" in
									aac)		echo "      <String>LC-AAC ${chaninfo[$i]}</String>" ;;
									neroaac)	echo "      <String>${AACTYPE[$i]} ${chaninfo[$i]}</String>" ;;
									aac+)		echo "      <String>HE-AACv1 ${chaninfo[$i]}</String>" ;;
									vorbis)		echo "      <String>Vorbis ${chaninfo[$i]}</String>" ;;
									mp3|"")		echo "      <String>MP3 ${chaninfo[$i]}</String>" ;;
									ac3)		echo "      <String>AC3 ${chaninfo[$i]}</String>" ;;
									flac)		echo "      <String>FLAC ${chaninfo[$i]}</String>" ;;
									pcm)		echo "      <String>PCM ${chaninfo[$i]}</String>" ;;
									*)		echo "      <String>${detectaud[$i]} ${chaninfo[$i]}</String>" ;;
								esac
								echo "    </Simple>"
								case "$source" in
									dvd)
									echo "    <Simple>"
									echo "      <Name>Audio Language (Track $i)</Name>"
									echo "      <String>${AUDLANG[$i]}</String>"
									echo "    </Simple>"
									;;
								esac
							fi
						fi
					done
					echo "    <Simple>"
					echo "      <Name>Encoder</Name>"
					echo "      <String>$($MENCODER 2>/dev/null | head -n 1)</String>"
					echo "    </Simple>"
					echo "    <Simple>"
					echo "      <Name>lavc parameters</Name>"
					echo "      <String>$(mencoder_opts $1 | tail -n 1 | grep -o '\-ovc.*' | sed 's|\-ovc lavc \-lavcopts ||; s| ||g; s|2>/dev/null||')</String>"
					echo "    </Simple>"
					echo "    <Simple>"
					echo "      <Name>mkvmerge version</Name>"
					echo "      <String>$($MKVMERGE --version | awk '{print $2}' | sed 's|v||')</String>"
					echo "    </Simple>"
					echo "    <Simple>"
					echo "      <Name>divxenc parameters</Name>"
					echo "      <String>divxenc $@</String>"
					echo "    </Simple>"
					echo "    <Simple>"
					echo "      <Name>Comment</Name>"
					echo "      <String>Tagged by divxenc $version on $(date +%Y/%m/%d)</String>"
					echo "    </Simple>"
					echo "  </Tag>"
					echo "</Tags>"
				}
				MKVTAGS="--global-tags \"$TEMPDIR/mkvtags.xml\""
				case "$source" in
					dir)
					DIRTAGS="echo \"$(mkvtags_func $@ | sed 's|\"|\\"|g')\" > \"$TEMPDIR/mkvtags.xml\""
					;;
					*)
					mkvtags_func $@ > "$TEMPDIR/mkvtags.xml"
					;;
				esac
				
				# MKV audio & tagging for track 1
				case "${audiocodec[1]}" in
					aac+)
					NOAUDIO="-A"
					TRACKNAME="$TRACKTITLE"
					MKVAUD1="--track-name 0:\"HE-AACv1 ${chaninfo[1]}\" $MKVAUDLANG1 --aac-is-sbr 0:1 \"$TEMPDIR/audio.aac\""
					;;
					neroaac)
					NOAUDIO="-A"
					TRACKNAME="$TRACKTITLE"
					case "${aacprof[1]}" in
						-he|-hev2) MKVSBR="--aac-is-sbr 1:1" ;;
					esac
					MKVAUD1="--track-name 1:\"${AACTYPE[1]} ${chaninfo[1]}\" $MKVAUDLANG1 $MKVSBR --no-chapters \"$TEMPDIR/audio.aac\""
					;;
					vorbis)
					NOAUDIO="-A"
					TRACKNAME="$TRACKTITLE"
					MKVAUD1="--track-name 0:\"Vorbis ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio.ogg\""
					;;
					flac)
					NOAUDIO="-A"
					TRACKNAME="$TRACKTITLE"
					MKVAUD1="--track-name 0:\"FLAC ${chaninfo[1]}\" $MKVAUDLANG1 \"$TEMPDIR/audio.flac\""
					;;
					ffac3|ffeac3|ffdts|ffaac|ffvorbis|ffmp3|ffpcm|ffflac)
					TRACKNAME="$TRACKTITLE $MKVAUDLANG1 --track-name 1:\"${detectaud[1]} ${chaninfo[1]}\""
					;;
					mp3|ac3|aac|"")
					case "${audiocodec[1]}" in
						aac)	MKVAUDCDC=LC-AAC ;;
						mp3|"")	MKVAUDCDC=MP3 ;;
						ac3)	MKVAUDCDC=AC3 ;;
					esac
					TRACKNAME="$TRACKTITLE $MKVAUDLANG1 --track-name 1:\"$MKVAUDCDC ${chaninfo[1]}\""
					;;
				esac
				
				# MKV audio & tagging for track 2 & 3
				for i in {2..3}; do
					if [ "${TRACKID[$i]}" = "yes" ]; then
						case "${audiocodec[$i]}" in
							# ffac3|ffdts is equivalent to
							# audio stream copy
							ffac3|ffdts)
							MKVAUD[$i]="--track-name -1:\"${detectaud[$i]} ${chaninfo[$i]}\" ${MKVAUDLANG[$i]} \"$TEMPDIR/audio$i.raw\""
							;;
							mp3|aac|ac3|"")
							case "${audiocodec[$i]}" in
								mp3|"")	MKVAUDCDC[$i]=MP3 ;;
								aac)	MKVAUDCDC[$i]=LC-AAC ;;
								ac3)	MKVAUDCDC[$i]=AC3 ;;
							esac
							MKVAUD[$i]="--track-name -1:\"${MKVAUDCDC[$i]} ${chaninfo[$i]}\" ${MKVAUDLANG[$i]} \"$TEMPDIR/audio$i.${audext[$i]}\""
							;;
							aac+)
							MKVAUD[$i]="--track-name -1:\"HE-AACv1 ${chaninfo[$i]}\" ${MKVAUDLANG[$i]} --aac-is-sbr 0:1 \"$TEMPDIR/audio$i.aac\""
							;;
							neroaac)
							case "${aacprof[$i]}" in
								-he|-hev2) MKVSBR[$i]="--aac-is-sbr 1:1" ;;
							esac
							MKVAUD[$i]="--track-name -1:\"${AACTYPE[$i]} ${chaninfo[$i]}\" ${MKVAUDLANG[$i]} ${MKVSBR[$i]} --no-chapters \"$TEMPDIR/audio$i.aac\""
							;;
							vorbis)
							MKVAUD[$i]="--track-name -1:\"Vorbis ${chaninfo[$i]}\" ${MKVAUDLANG[$i]} \"$TEMPDIR/audio$i.ogg\""
							;;
							flac)
							MKVAUD[$i]="--track-name -1:\"FLAC ${chaninfo[$i]}\" ${MKVAUDLANG[$i]} \"$TEMPDIR/audio$i.flac\""
							;;
						esac
					fi
				done
				
				# Export commands to files
				case "$source" in
					dir)
					MKVOUT="$OUTPUTDIR/\${i%.*}.mkv"
					MKVMUXING="$BATCH"
					;;
					*)
					MKVOUT="${OUTPUT%.*}.mkv"
					MKVMUXING="$TEMPDIR/mkvmuxing"
					;;
				esac
				echo "$DIRTAGS" >> "$MKVMUXING"
				mkv_export_func() {
					echo "test -e \"$MKVOUT\" && mv -f \"$MKVOUT\" \"$MKVOUT.old\""
					echo "$MKVMERGE $MKVCOVER $MKVTAGS $NOAUDIO $MKVTITLE $TRACKNAME \"$OUTPUT\" $MKVAUD1 ${MKVAUD[2]} ${MKVAUD[3]} $MKVSUBS $MKVCHAPS -o \"$MKVOUT\""
					echo "sleep 2"
					echo
				}
				mkv_export_func >> "$MKVMUXING"
				if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
					echo "echo \"$(mkvtags_func $@ | sed 's|\"|\\"|g')\" > \"$TEMPDIR/mkvtags.xml\"" >> "$OPTSFILE"
					mkv_export_func >> "$OPTSFILE"
				fi
			fi
		else
			avi_to_mkv=no
		fi
		;;
		*|"")
		avi_to_mkv=no
		;;
	esac
else
	avi_to_mkv=no
fi

# Ask for AVI -> MP4 conversion
if [ "$ALLOW_MP4_MUXING" = "y" ]; then
	case "${audiocodec[1]}" in
		mp3|ffmp3|aac|aac+|neroaac|ffaac|ac3|ffac3|vorbis|ffvorbis|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
				
				# Global variables
				MP4FPS="$MPLAYER \"$OUTPUT\" $MPLAYEROPTS -identify -nosound -vo null -nocache -frames 1 2>/dev/null | grep '^ID_VIDEO_FPS' | tail -n 1 | awk -F= '{print \$2}' > \"$TEMPDIR/mp4fps\""
				MP4VID="$MENCODER \"$OUTPUT\" -nosound -ovc copy -of rawvideo -o \"$TEMPDIR/divx_video.cmp\""
				VIDEOINPUT="-add \"$TEMPDIR/divx_video.cmp\""
				if [ "$3" = "ipod" ]; then
					MP4IPOD="-ipod"
				fi
				
				# Import of external subtitles.
				# Input type agnostic. Only
				# allow supported subtitle formats
				# by MP4. Others will be skipped
				for i in {1..3}; do
					if [ ! -z "${EXTSUB[$i]}" ]; then
						case "${EXTSUB[$i]##*.}" in
							idx|IDX|srt|SRT|ttxt|TTXT)
							MP4SUBS="$MP4SUBS -add \"$(eval "echo \${EXTSUB[$i]}")\""
							;;
							*)
							echo
							green "-> Subtitle format '$(echo ${EXTSUB[$i]##*.} | tr '[:lower:]' '[:upper:]')' not supported by MP4!"
							green "-> Supported subtitle formats are: IDX, SRT, TTXT"
							green "-> Skipping import of '${EXTSUB[$i]}'"
							echo
							;;
						esac
					fi
				done
				
				# Add cover/chaps/DVD subs
				case "$source" in
					file|dvd|vcd)
					# Year - a bit misleading
					# since created could also
					# mean when the file was
					# encoded
					printf "Specify the Release Year of the content [press 'Enter' to skip]: "
					read mp4year
					if [ ! -z "$mp4year" ]; then
						MP4YEAR=":created=\"$mp4year\""
					fi
					# Genre
					printf "Specify a Genre for the content [press 'Enter' to skip]: "
					read mp4genre
					if [ ! -z "$mp4genre" ]; then
						MP4GENRE=":genre=\"$mp4genre\""
					fi
					# Cover
					printf "Provide a Cover file in jpeg/png format [press 'Enter' to skip]: "
					read -e mp4cover
					if [ ! -z "$mp4cover" ]; then
						if [ ! -f "$mp4cover" ]; then
							echo
							error "-> No such file: '$mp4cover'"
							error "-> Skipping embedding of cover file"
							echo
						else
							case "$(basename "${mp4cover##*.}" | tr '[:upper:]' '[:lower:]')" in
								jpg|jpeg|png)
								MP4COVER=":cover=\"$mp4cover\""
								;;
								*)
								echo
								error "-> Image type not supported"
								error "-> Skipping embedding of cover file"
								echo
								;;
							esac
						fi
					fi
					case "$source" in
						dvd)
						# Audio language info
						for i in {1..3}; do
							if [ "${TRACKID[$i]}" = "yes" ]; then
								MP4AUDLANG[$i]=":lang=${AUDLANG[$i]}"
							fi
						done
						# Chapters for MP4
						if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
							printf "Import chapters information into the MP4 container? [y/N]: "
							read mp4impchap
							if [ "$mp4impchap" = "y" -o "$mp4impchap" = "Y" ]; then
								MP4CHAPS="-chap \"$CHAPTERSFILE\""
							fi
						fi
						# DVD subs for MP4
						if [ ! -z "${vobsubout[1]}" -o ! -z "${vobsubout[2]}" -o ! -z "${vobsubout[3]}" ]; then
							printf "Import the ripped subtitle(s) into the MP4 container? [y/N]: "
							read mp4impsub
							if [ "$mp4impsub" = "y" -o "$mp4impsub" = "Y" ]; then
								for i in {1..3}; do
									[[ -z $(eval "echo \${IDXFILE[$i]}") ]] || MP4SUBS="$MP4SUBS -add \"$(eval "echo \${IDXFILE[$i]}")\""
								done
							fi
						fi
						;;
					esac
					;;
				esac
				
				# MP4 hinting
				printf "Hint the MP4 file for RTP/RTSP streaming sessions? [y/N]: "
				read mp4hint
				if [ "$mp4hint" = "y" -o "$mp4hint" = "Y" ]; then
					MP4HINT="-hint"
				fi
				
				# First audio track for MP4
				case "${audiocodec[1]}" in
					mp3|ffmp3|"")
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/mp3.mp3\""
					AUDIOINPUT="-add \"$TEMPDIR/mp3_audio.mp3\"#audio:name=\"MP3 Stereo\"${MP4AUDLANG[1]}"
					;;
					aac|ffaac)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/aac.raw\""
					MVRAW="mv -f \"$TEMPDIR/aac_audio.raw\" \"$TEMPDIR/aac_audio.aac\""
					AUDIOINPUT="-add \"$TEMPDIR/aac_audio.aac\"#audio:name=\"LC-AAC ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					;;
					aac+)
					AUDIOINPUT="-add \"$TEMPDIR/audio.aac\"#audio:sbr:name=\"HE-AACv1 Stereo\"${MP4AUDLANG[1]}"
					;;
					neroaac)
					case "${aacprof[1]}" in
						-he|-hev2) AACSBR=":sbr" ;;
					esac
					AUDIOINPUT="-add \"$TEMPDIR/audio.aac\"#audio:name=\"${AACTYPE[1]} ${chaninfo[1]}\"$AACSBR${MP4AUDLANG[1]}"
					;;
					ac3|ffac3)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/ac3.raw\""
					MVRAW="mv -f \"$TEMPDIR/ac3_audio.raw\" \"$TEMPDIR/ac3_audio.ac3\""
					AUDIOINPUT="-add \"$TEMPDIR/ac3_audio.ac3\"#audio:name=\"AC3 ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					;;
					ffvorbis)
					MP4AUD="$MP4BOX -aviraw audio \"$OUTPUT\" -out \"$TEMPDIR/vorbis.raw\""
					MVRAW="mv -f \"$TEMPDIR/vorbis_audio.raw\" \"$TEMPDIR/vorbis_audio.ogg\""
					AUDIOINPUT="-add \"$TEMPDIR/vorbis_audio.ogg\"#audio:name=\"Vorbis ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					;;
					vorbis)
					AUDIOINPUT="-add \"$TEMPDIR/audio.ogg\"#audio:name=\"Vorbis ${chaninfo[1]}\"${MP4AUDLANG[1]}"
					;;
				esac
				
				# Second & third audio tracks for MP4
				for i in {2..3}; do
					if [ "${TRACKID[$i]}" = "yes" ]; then
						case "${audiocodec[$i]}" in
							ffac3)
							# ffac3 is equivalent to
							# audio stream copy
							AUDIOINPUT[$i]="-add \"$TEMPDIR/audio$i.ac3\"#audio:name=\"AC3 ${chaninfo[$i]}\"${MP4AUDLANG[$i]}"
							;;
							mp3|aac|ac3|"")
							if [ -z "${audiocodec[$i]}" ]; then
								AUDCDC[$i]="MP3"
							else
								AUDCDC[$i]="$(echo ${audiocodec[$i]} | tr '[:lower:]' '[:upper:]')"
							fi
							AUDIOINPUT[$i]="-add \"$TEMPDIR/audio$i.${audext[$i]}\"#audio:name=\"${AUDCDC[$i]} ${chaninfo[$i]}\"${MP4AUDLANG[$i]}"
							;;
							vorbis)
							AUDIOINPUT[$i]="-add \"$TEMPDIR/audio$i.ogg\"#audio:name=\"Vorbis ${chaninfo[$i]}\"${MP4AUDLANG[$i]}"
							;;
							aac+)
							AUDIOINPUT[$i]="-add \"$TEMPDIR/audio$i.aac\"#audio:sbr:name=\"HE-AACv1 Stereo\"${MP4AUDLANG[$i]}"
							;;
							neroaac)
							RMNEROAUD[$i]="rm -f \"$TEMPDIR/audio$i.aac\""
							case "${aacprof[$i]}" in
								-he|-hev2) AACSBR[$i]=":sbr" ;;
							esac
							AUDIOINPUT[$i]="-add \"$TEMPDIR/audio$i.aac\"#audio:name=\"${AACTYPE[$i]} ${chaninfo[$i]}\"${AACSBR[$i]}${MP4AUDLANG[$i]}"
							;;
						esac
					fi
				done
				
				# Stupid MP4Box, moving around files as it's
				# too dumb to find out the format by itself :/
				if [ ! -z "${aid[2]}" ]; then
					case "${audiocodec[2]}" in
						ffac3)
						MVRAW2="mv -f \"$TEMPDIR/audio2.raw\" \"$TEMPDIR/audio2.ac3\""
						MVRAW3="mv -f \"$TEMPDIR/audio2.ac3\" \"$TEMPDIR/audio2.raw\""
						;;
					esac
				fi
				if [ ! -z "${aid[3]}" ]; then
					case "${audiocodec[3]}" in
						ffac3)
						MVRAW4="mv -f \"$TEMPDIR/audio3.raw\" \"$TEMPDIR/audio3.ac3\""
						MVRAW5="mv -f \"$TEMPDIR/audio3.ac3\" \"$TEMPDIR/audio3.raw\""
						;;
					esac
				fi
				
				# Export commands to files
				case "$source" in
					dir)
					MP4OUT="$OUTPUTDIR/\${i%.*}.mp4"
					MP4TAGS="-itags name=\"\${i%.*}\":comment=\"Tagged by divxenc $version on \$(date)\""
					MP4MUXING="$BATCH"
					;;
					*)
					MP4OUT="${OUTPUT%.*}.mp4"
					MP4TAGS="-itags name=\"$(basename "${OUTPUT%.*}")\"$MP4YEAR$MP4GENRE$MP4COVER:comment=\"Tagged by divxenc $version on \$(date)\""
					MP4MUXING="$TEMPDIR/mp4muxing"
					;;
				esac
				mp4_export_func() {
					echo "test -e \"$MP4OUT\" && mv -f \"$MP4OUT\" \"$MP4OUT.old\""
					echo "$MP4VID"
					echo "sleep 2"
					echo "$MP4AUD"
					echo "$MVRAW"
					echo "$MVRAW2"
					echo "$MVRAW4"
					echo "$MP4FPS"
					echo "$MP4BOX -fps \$(cat \"$TEMPDIR/mp4fps\") -tmp \"$TEMPDIR\" $VIDEOINPUT $MP4HINT $AUDIOINPUT ${AUDIOINPUT[2]} ${AUDIOINPUT[3]} $MP4TAGS $MP4SUBS $MP4CHAPS $MP4IPOD -mpeg4 -new \"$MP4OUT\""
					echo "$MVRAW3"
					echo "$MVRAW5"
					echo "sleep 2"
					echo "${RMNEROAUD[2]}"
					echo "${RMNEROAUD[3]}"
					echo
				}
				mp4_export_func >> "$MP4MUXING"
				if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
					mp4_export_func >> "$OPTSFILE"
				fi
			fi
		else
			avi_to_mp4=no
		fi
		;;
		*)
		avi_to_mp4=no
		;;
	esac
else
	avi_to_mp4=no
fi

# Ask for AVI -> OGM
if [ "$ALLOW_OGM_MUXING" = "y" ]; then
	case "${audiocodec[1]}" in
		mp3|ffmp3|vorbis|ffvorbis|ac3|ffac3|pcm|ffpcm|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 "${audiocodec[1]}" in
					vorbis)
					# We only take the video from the AVI,
					# hence the --noaudio option which ignores
					# audio from the AVI
					NOAUDIO="--noaudio"
					case "$source" in
						dvd)
						OGMAUD="-c LANGUAGE=${AUDLANG[1]} \"$TEMPDIR/audio.ogg\""
						;;
						*)
						OGMAUD="\"$TEMPDIR/audio.ogg\""
						;;
					esac
					;;
					mp3|ac3|ffac3|pcm)
					case "$source" in
						dvd)
						OGMAUDLANG="-c LANGUAGE=${AUDLANG[1]}"
						;;
					esac
					;;
				esac
				
				# Second & third audio track for DVD encodings
				for i in {2..3}; do
					if [ "${TRACKID[$i]}" = "yes" ]; then
						case "${audiocodec[$i]}" in
							# ffac3 is equivalent to
							# AC3 audio stream copy
							ffac3)
							OGMAUD[$i]="-c LANGUAGE=${AUDLANG[$i]} \"$TEMPDIR/audio$i.raw\""
							;;
							ac3|mp3|"")
							OGMAUD[$i]="-c LANGUAGE=${AUDLANG[$i]} \"$TEMPDIR/audio$i.${audext[$i]}\""
							;;
							vorbis)
							OGMAUD[$i]="-c LANGUAGE=${AUDLANG[$i]} \"$TEMPDIR/audio$i.ogg\""
							;;
						esac
					fi
				done
				
				# Title/Genre/Year for OGM
				case "$source" in
					file|dvd|vcd)
					OGMTITLE="-c TITLE=\"$(basename "${OUTPUT%.*}")\""
					printf "Specify the Release Year of the content [press 'Enter' to skip]: "
					read ogmyear
					if [ ! -z "$ogmyear" ]; then
						OGMYEAR="-c YEAR=\"$ogmyear\""
					fi
					printf "Provide a Genre for the content [press 'Enter' to skip]: "
					read ogmgenre
					if [ ! -z "$ogmgenre" ]; then
						OGMGENRE="-c GENRE=\"$ogmgenre\""
					fi
					;;
					dir)
					OGMTITLE="-c TITLE=\"\${i%.*}\""
					;;
				esac
				
				# Import of external subtitles.
				# Input type agnostic. Only
				# allow supported subtitle formats
				# by OGM. Others will be skipped
				for i in {1..3}; do
					if [ ! -z "${EXTSUB[$i]}" ]; then
						case "${EXTSUB[$i]##*.}" in
							srt|SRT)
							OGMSUBS="$OGMSUBS \"$(eval "echo \${EXTSUB[$i]}")\""
							;;
							*)
							echo
							green "-> Subtitle format '$(echo ${EXTSUB[$i]##*.} | tr '[:lower:]' '[:upper:]')' not supported by OGM!"
							green "-> Supported subtitle formats are: SRT"
							green "-> Skipping import of '${EXTSUB[$i]}'"
							echo
							;;
						esac
					fi
				done
				
				case "$source" in
					dvd)
					# Chapters for OGM
					if [ "$chapexp" = "y" -o "$chapexp" = "Y" ]; then
						printf "Import chapters information into the OGM container? [y/N]: "
						read ogmimpchap
						if [ "$ogmimpchap" = "y" -o "$ogmimpchap" = "Y" ]; then
							OGMCHAPS="-c @\"$CHAPTERSFILE\""
						fi
					fi
					;;
				esac
				
				# Export commands to files
				case "$source" in
					dir)
					OGMOUT="$OUTPUTDIR/\${i%.*}.ogm"
					OGMMUXING="$BATCH"
					;;
					*)
					OGMOUT="${OUTPUT%.*}.ogm"
					OGMMUXING="$TEMPDIR/ogmmuxing"
					;;
				esac
				OGMCOMMENT="-c COMMENT=\"Tagged by divxenc $version on \$(date)\""
				ogm_export_func() {
					echo "test -e \"$OGMOUT\" && mv -f \"$OGMOUT\" \"$OGMOUT.old\""
					echo "$OGMMERGE $NOAUDIO $OGMTITLE $OGMYEAR $OGMGENRE $OGMAUDLANG $OGMCOMMENT $OGMCHAPS \"$OUTPUT\" $OGMAUD ${OGMAUD[2]} ${OGMAUD[3]} $OGMSUBS -o \"$OGMOUT\""
					echo "sleep 2"
					echo
				}
				ogm_export_func >> "$OGMMUXING"
				if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
					ogm_export_func >> "$OPTSFILE"
				fi
			fi
		else
			avi_to_ogm=no
		fi
		;;
		*|"")
		avi_to_ogm=no
		;;
	esac
else
	avi_to_ogm=no
fi

# Footers for batch files
case "$source" in
	dir)
	if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" -o "$avi_to_ogm" = "yes" ]; then
		printf "Delete the AVI file after remuxing? [y/N]: "
		read rmavi
		if [ "$rmavi" = "y" -o "$rmavi" = "Y" ]; then
			echo "rm -f \"$OUTPUT\"" >> "$BATCH"
		fi
	fi
	echo "rm -rf \"$TEMPDIR\"" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "fi" >> "$BATCH"
	echo "" >> "$BATCH"
	echo "done" >> "$BATCH"
	echo "" >> "$BATCH"
	send_email_func exp >> "$BATCH"
	echo "#################### END OF COMMANDS ####################" >> "$BATCH"
	;;
	*)
	if [ "$saveopts" = "y" -o "$saveopts" = "Y" ]; then
		echo "rm -rf \"$TEMPDIR\"" >> "$OPTSFILE"
		echo "" >> "$OPTSFILE"
		send_email_func exp >> "$OPTSFILE"
		echo "#################### END OF COMMANDS ####################" >> "$OPTSFILE"
		echo "" >> "$OPTSFILE"
	fi
	if [ "$avi_to_mkv" = "no" -a "$avi_to_mp4" = "no" -a "$avi_to_ogm" = "no" ]; then
		if [ "${TRACKID[2]}" = "yes" -o "${TRACKID[3]}" = "yes" ]; then
			echo
			error "-> 2nd/3rd audio track only supported by"
			error "   the MKV/MP4/OGM containers!"
			echo
			rmtemp
		fi
		case "${audiocodec[1]}" in
			neroaac|aac+|vorbis|flac)
			echo
			error "-> ${audiocodec[1]} audio not supported by the AVI container!"
			echo
			rmtemp
			;;
		esac
	fi
	;;
esac

case "$1" in
	-1p)	passmode="1-pass mode" ;;
	-fq)	passmode="fixed-quant mode" ;;
	-2p)	passmode="2-pass mode" ;;
	-3p)	passmode="3-pass mode" ;;
esac

echo
case "$source" in
	dir)
	green "-> Starting to batch encode $type in '$(dirname "$sourcetype")'"
	display_quality_preset_func $3 $4
	green "-> Using '$(dirname "$OUTPUT")' as output directory for all $type"
	green "-> Using $passmode for all $type"
	green "-> Batch file located in '$BATCH'"
	;;
	*)
	green "-> Starting to encode the $type in $passmode"
	display_quality_preset_func $3 $4
	case "$1" in
		-2p)	green "-> Using '/dev/null' as output for the first pass"; finalpass="for the second pass" ;;
		-3p)	green "-> Using '/dev/null' as output for the first & second pass"; finalpass="for the third pass" ;;
	esac
	green "-> Using '$OUTPUT' as output file $finalpass"
	;;
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 non-zero status!"
		error "-> Exiting in function: mencoder_exit()"
		rmtemp
	fi
}

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


# Start encoding
case "$source" in
	dir)
	if [ -f "$BATCH" ]; then
		cp -f $BATCH $HOME
		source $BATCH
		echo ""
		brown "-> Have a nice day ^_^"
		echo ""
		rmtemp
	else
		error "-> File '$BATCH' is missing!"
		error "-> Exiting..."
		rmtemp
	fi
	;;
	*)
	case "$1" in
		-1p|-fq)
		source "$DIVX1PFQ"
		mencoder_exit
		;;
		-2p)
		source "$DIVX2P1"
		mencoder_exit
		echo ""
		brown "=============================================================="
		echo ""
		color blue && printf "Starting the second pass of the encoding process in: " && counter
		color normal && echo ""
		source "$DIVX2P2"
		mencoder_exit
		;;
		-3p)
		source "$DIVX2P1"
		mencoder_exit
		echo ""
		brown "=============================================================="
		echo ""
		color blue && printf "Starting the second pass of the encoding process in: " && counter
		color normal && echo ""
		source "$DIVX2P2"
		mencoder_exit
		echo ""
		brown "=============================================================="
		echo ""
		color blue && printf "Starting the third pass of the encoding process in: " && counter
		color normal && echo ""
		source "$DIVX2P3"
		mencoder_exit
		;;
	esac
	;;
esac

case "${audiocodec[1]}" in
	nosound)	audfmt="-nosound" ;;
	*)		audfmt="-oac pcm" ;;
esac

# Dump the second/third subtitle if selected
for i in {2..3}; do
	if [ ! -z "${subtitle[$i]}" ]; then
		echo 
		green "-> Dumping subtitle $i, please wait..."
		sleep 2
		$MENCODER $sourcetype $device $MPEGVC $chapters $ofps ${aid[1]} ${subtitle[$i]} -vobsubout "${SUBFILE[$i]%.*}" -vobsuboutindex $(($i-1)) $audfmt -ovc copy -o /dev/null >/dev/null 2>&1
		if [ -e "${IDXFILE[$i]}" ]; then
			green "-> Done"
		else
			error "-> Failed!"
			if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" ]; then
				if [ "$mkvimpsub" = "y" -o "$mkvimpsub" = "Y" -o "$mp4impsub" = "y" -o "$mp4impsub" = "Y" ]; then
					error "-> Exiting as container conversion will also fail!"
					echo
					rmtemp
				fi
			fi
			echo
		fi
	fi
done

# Encode audio to neroAAC/AAC+/Vorbis.
# mkvmerge/ogmmerge directly take the
# video from the AVI. MP4Box extracts
# it first in its config above
if [ "$avi_to_mp4" = "yes" -o "$avi_to_mkv" = "yes" -o "$avi_to_ogm" = "yes" ]; then
	audio_exit_func() {
		case "$1" in
			audiofile)
			error "-> Failed!"
			;;
			track1)
			error "-> File '${AUDIOENC[1]}' is missing!"
			;;
			track23)
			error "-> File '${AUDIOENC[$i]}' is missing!"
			;;
		esac
		error "-> Exiting as container conversion will also fail!"
		echo
		rmtemp
	}
	
	case "${audiocodec[1]}" in
		aac+|neroaac|vorbis|flac)
		echo
		case "${audiocodec[1]}" in
			aac+)
			audfile="$TEMPDIR/audio.aac"
			green "-> Track 1: Encoding audio with 'aacplusenc' to HE-AACv1, please wait..."
			green "-> Track 1: This can take a while..."
			;;
			neroaac)
			audfile="$TEMPDIR/audio.aac"
			green "-> Track 1: Encoding audio with 'neroAacEnc' to ${AACTYPE[1]}, please wait..."
			green "-> Track 1: This can take a while..."
			;;
			vorbis)
			audfile="$TEMPDIR/audio.ogg"
			green "-> Track 1: Encoding audio with 'oggenc' to Vorbis, please wait..."
			green "-> Track 1: This can take a while..."
			;;
			flac)
			audfile="$TEMPDIR/audio.flac"
			green "-> Track 1: Encoding audio with 'flac' to FLAC, please wait..."
			green "-> Track 1: This can take a while..."
			;;
		esac
		sleep 2
		if [ -f "${AUDIOENC[1]}" ]; then
			source "${AUDIOENC[1]}" >/dev/null 2>&1
			if [ -e "$audfile" ]; then
				green "-> Track 1: Done"
			else
				audio_exit_func audiofile
			fi
		else
			audio_exit_func track1
		fi
		;;
	esac
	
	# Second & third audio track for DVD encodings
	for i in {2..3}; do
		if [ "${TRACKID[$i]}" = "yes" ]; then
			sleep 2
			echo
			case "${audiocodec[$i]}" in
				ffac3|ffdts)
				audfile[$i]="$TEMPDIR/audio$i.raw"
				green "-> Track $i: Dumping ${detectaud[$i]} audio, please wait..."
				;;
				mp3|ac3|aac|"")
				audfile[$i]="$TEMPDIR/audio$i.${audext[$i]}"
				green "-> Track $i: Encoding audio to $(echo ${audext[$i]} | tr '[:lower:]' '[:upper:]'), please wait..."
				;;
				neroaac)
				audfile[$i]="$TEMPDIR/audio$i.aac"
				green "-> Track $i: Dumping & encoding audio with 'neroAacEnc' to ${AACTYPE[$i]}, please wait..."
				green "-> Track $i: This can take a while..."
				;;
				aac+)
				audfile[$i]="$TEMPDIR/audio$i.aac"
				green "-> Track $i: Dumping & encoding audio with 'aacplusenc' to HE-AACv1, please wait..."
				green "-> Track $i: This can take a while..."
				;;
				vorbis)
				audfile[$i]="$TEMPDIR/audio$i.ogg"
				green "-> Track $i: Dumping & encoding audio with 'oggenc' to Vorbis, please wait..."
				green "-> Track $i: This can take a while..."
				;;
				flac)
				audfile[$i]="$TEMPDIR/audio$i.flac"
				green "-> Track $i: Dumping & encoding audio with 'flac' to FLAC, please wait..."
				green "-> Track $i: This can take a while..."
				;;
			esac
			if [ -f "${AUDIOENC[$i]}" ]; then
				source "${AUDIOENC[$i]}" >/dev/null 2>&1
				if [ -e "${audfile[$i]}" ]; then
					green "-> Track $i: Done"
				else
					audio_exit_func audiofile
				fi
			else
				audio_exit_func track23
			fi
		fi
	done
fi

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

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

# AVI -> MP4 conversion
if [ "$avi_to_mp4" = "yes" ]; then
	echo ""
	green "-> Converting AVI file to the MP4 container, please wait..."
	sleep 3
	if [ -f "$MP4MUXING" ]; then
		source "$MP4MUXING" >/dev/null 2>&1
		if [ -e "$MP4OUT" ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$MP4MUXING' is missing!"
		error "-> Skipping AVI to MP4 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 "$OGMMUXING" ]; then
		source "$OGMMUXING" >/dev/null 2>&1
		if [ -e "$OGMOUT" ]; then
			green "-> Done"
		else
			error "-> Failed!"
		fi
	else
		error "-> File '$OGMMUXING' is missing!"
		error "-> Skipping AVI to OGM conversion!"
	fi
fi

rm -rf "$TEMPDIR"

# 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 MiB ($OUTPUT)"
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 MiB ($MKVOUT)"
	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 MiB ($MP4OUT)"
	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 MiB ($OGMOUT)"
	fi
fi

send_email_func

if [ "$avi_to_mkv" = "yes" -o "$avi_to_mp4" = "yes" -o "$avi_to_ogm" = "yes" ]; then
	echo ""
	printf "Delete the 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
