#!/bin/bash
# ==============================================================================
# title			:roku-ripper
# description	:Converts video content to Roku format seemlessly.
# author		:theemahn <theemahn@ultimateedition.info>
# date			:01/17/2019
# version		:1.0.0
# usage			:roku-ripper --help
# manual		:man roku-ripper
# notes			:See change-log below for further information.
# ==============================================================================
# Change-log:
# 1.0.0	Initial release
#
# 1.0.1 Adjusted dependancies
#
# 1.0.2 Added video tagging
#
# 1.0.3 Added recursive processing
#
# 1.0.4	Added support for mp4
#
# 1.0.5 Added Recursive support
#
# 1.0.6 Added support for multi-core processors (HardwareDetect)
#	   Added Video Quality interaction.
# Version Control
APPNAME="Roku Ripper"
PROGNAME="roku-ripper"
VERSION="1.1.1"
BUILDDATE="07/12/2024"
WEBSITE="roku-ripper.com"
AUTHOR="TheeMahn"
EMAIL="<$AUTHOR@${WEBSITE}>"

LOG_FILE="/var/log/roku-ripper.log"

# Pull in common software
if [[ -f "ultimate-common" ]]; then
	source ultimate-common
elif [[ -f "/usr/share/ultimate_edition/ultimate-common" ]]; then
	source /usr/share/ultimate_edition/ultimate-common
else
	echo "No Ultimate Edition common source. Please install ultimate-edition-common."
	exit 0;
fi
DIR=$(echo "$*" | grep -i "\\-d")
if [[ "${DEBUG}" ]]; then
	Timer "Start" "Debug ${APPNAME}"
	#set -e
fi

#Begin programming...
shopt -s nocasematch
temp_file=$(mktemp)
shopt -s nullglob
declare -a EXTENSIONS=();
declare -a ALLEXTENSIONS=();
declare -a MOVIES=();
declare -a SUPPORTEDAUDIO=();
declare -a VIDEOCODECSSUPPORTED=();
declare -i AUDIOSUPPORT;
declare -i VIDEOSUPPORT;
declare -i COMPLETION;
declare -a QUALITY=();
declare -a QUALITYSETTINGS=();
declare -a RESOLUTIONS=();
declare -a RESOLUTION=();
# let's stop pissing around and break out arrays for handling multiple formats.
EXTENSIONS=( "mkv" "avi" "mp4" "m4v" "mpg" "mpeg" "mts" "wmv" "vob" "3gp" "flv" "mov" "webm" );
ALLEXTENSIONS=( "mkv" "avi" "mp4" "m4v" "mpg" "mpeg" "mts" "wmv" "vob" "3gp" "flv" "mov" "webm" );
SUPPORTEDAUDIO=( "AAC" "MP3" "WMA" "WAV" "AIFF" "FLAC" "ALAC" "AC3" "E-AC3" "AC-3" );
VIDEOCODECSSUPPORTED=( "X264" "x265" "H.264/AVC" "HEVC/H.265" "VP9" );
NOEXTENSIONS="${#ALLEXTENSIONS[@]}"
QUALITY=( "sd" "hd" "fhd" "qhd" "dvd" "bluray" "4k" "8k"); # Optional video output quality - human readable
RESOLUTION=( "720x480" "1280x720" "1920x1080" "2560x1440" "720×480" "1920×1080" "3840x2160" "7680x4320" ); # Like a database QUALITY Array=BluRAY, array RESOLUTION[6]=1920x1080

if ! [[ "${PALNTSC}" ]]; then
	QUALITYSETTINGS=( '' '' '-target ntsc-dvd -af "pan=stereo|FL < 1.0*FL + 0.707*FC + 0.707*BL|FR < 1.0*FR + 0.707*FC + 0.707*BR" -s '${RESOLUTION}'' );
else
	QUALITYSETTINGS=( '' '' '-target pal-dvd -af "pan=stereo|FL < 1.0*FL + 0.707*FC + 0.707*BL|FR < 1.0*FR + 0.707*FC + 0.707*BR" -s '${RESOLUTION}'' );
fi

# Pre-process optional switches.
# QUALITY - output introduce "sd" "hd" "fhd" "qhd" "dvd" "bluray" "4k" "8k" so far
OUTQUALITY=$(echo "$*" | grep -i "\\-q")
if ! [[ "${OUTQUALITY}" ]]; then
	OUTQUALITY=$(echo "$*" | grep -i "quality=" | sed 's/^.*quality=//g' | cut -d' ' -f1)
fi

# Strip Audio from video? - Damn Millinials ;) - Don't worry I have your back too.  Video to mp3.
STRIP=$(echo "$*" | grep -i "\\-s")
if ! [[ "${STRIP}" ]]; then
	STRIP=$(echo "$*" | grep -i "strip")
fi

# always debug at this point of development? Optional currently.
if [[ "${DEBUG}" ]]; then
	if [[ "${STRIP}" ]]; then
		echo "DEBUG: STRIP AUDIO SWITCH DETECTED."
	fi
	if [[ "${OUTQUALITY}" ]]; then
		echo "DEBUG: OUTQUALITY SWITCH DETECTED:${OUTQUALITY}."
	fi
fi

if [[ "${DEBUG}" ]]; then
	if [[ "${FORCE}" ]]; then
		echo "DEBUG: FORCED ENCODING SWITCH DETECTED."
	fi
fi
# Preserve FileNames?
PRESERVE=$(echo "$*" | grep -i "\\-p")
if ! [[ "${PRESERVE}" ]]; then
	PRESERVE=$(echo "$*" | grep -i "preserve")
fi
if [[ "${DEBUG}" ]]; then
	if [[ "${PRESERVE}" ]]; then
		echo "DEBUG: PRESERVING FILENAMES."
	else
		echo "DEBUG: NOT PRESERVING FILENAMES"
	fi
fi

# Forced encoding?
FORCED=$(echo "$*" | grep -i "\\-f")
if ! [[ "${FORCED}" ]]; then
	FORCED=$(echo "$*" | grep -i "force")
fi
if [[ "${DEBUG}" ]]; then
	if [[ "${FORCE}" ]]; then
		echo "DEBUG: FORCED ENCODING SWITCH DETECTED."
	fi
fi

Process () {
	Center "${PROGNAME} - Process function invoked."
	case "${1}" in
		-f|--files) FD='*.*';;
		-d|--directories) FD="*/";;
		* ) echo -e "${BLDRED}Invalid option: "${1};echo -e "\n${BLDGRN}Example: ${PROGNAME} --files\nWill puncuate all files in current folder.${TXTRST}";exit 0;;
	esac
	if [[ "${2}" == "" ]]; then
		for dir in $FD;
		do
			if [[ "${1}" == "-d" ]]; then
				SEDED=$(echo $dir  | sed 's/\(.*\)/\L\1/' | sed 's/720p.*$/720p\//' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/ /\./g' | sed 's/xvid//i' | sed 's/\[/\.\[/i' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/\.-//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/_/\./g' | sed 's/\.\.\.*/\./i' | sed 's/\.\/$/\//' | sed 's/Dvdrip$/Dvdrip/g')
			else
				SEDED=$(echo $dir  | sed 's/\(.*\)/\L\1/' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/ /\./g' | sed 's/xvid//i' | sed 's/\[/\.\[/i' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/_/\./g' | sed 's/\.\.\.*/\./i' | sed 's/\.\/$/\//' | sed 's/Dvdrip$/Dvdrip/g')
			fi
			case "$dir" in
				* )
				if [[ "$dir" != "$SEDED" ]]; then
					#:Set auto increment ID:#
					id=$((id +1));
					Encapsulate ""mv '"'"$dir"'"' '"'"$SEDED"'"';
				fi ;;
			esac
			#echo 'SEDED: '$SEDED

		done
		if [[ "${2}" != "-Y" || "${2}" != "-YES" ]]; then
			Spinner "Processing folders"
		else
			Encapsulate "Folder(s) / Files(s) have been effected: $id"
		fi
	else
		for dir in $FD;
		do
			SEDED=$(echo $dir  | sed 's/\(.*\)/\L\1/' | sed 's/720p.*$/720p\//' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/ /\./g' | sed 's/xvid//i' | sed 's/\[/\.\[/i' | sed 's/\[\]//g' | sed 's/.Dual.Audio//i' | sed 's/BDRip/Bluray/i' | sed 's/\<./\U&/g' | sed 's/_/\./g' | sed 's/\.\.\.*/\./i' | sed 's/\.\/$/\//' | sed 's/Dvdrip$/Dvdrip/g')
			case "$dir" in
				* )
				if [[ "${dir}" != "${SEDED}" ]]; then
					#:Set auto increment ID:#
					id=$((id +1));
					Encapsulate "Moving: ${dir} to ${SEDED}"
					XFER=$(mv -f "${dir}" "${SEDED}")
					#`mv '"$dir"' '"$SEDED"'`

				fi ;;
			esac
			#echo 'SEDED: '$SEDED

		done
		if [[ "${2}" != "-Y" || "${2}" != "-YES" ]]; then
			Encapsulate "Folder(s) / Files(s) to be effected: $id"
		else
			Encapsulate "Folder(s) / Files(s) have been effected: $id"
		fi
	fi
}

AudioSupport () {
	AUDIOSUPPORT=0
	Encapsulate "Scanning for audio support in: ${1}"
	for AUDIO in "${SUPPORTEDAUDIO[@]}"
	do
		ROKUAUDIO=$(mediainfo "${1}" | grep -i "format" | grep -i "$AUDIO")
		if [[ "${ROKUAUDIO}" ]]; then
			Encapsulate "Audio Supported: YES"
			AUDIOSUPPORT=1
		fi
	done
	if [[ "${AUDIOSUPPORT}" == "0" ]]; then
		Encapsulate "Audio Supported: NO"
	fi
	FullBar
}

VideoSupport () {
	VIDEOSUPPORT=0
	Encapsulate "Scanning for video support in: ${1}"
	for VIDEO in "${VIDEOCODECSSUPPORTED[@]}"
	do
		ROKUVIDEO=$(mediainfo "${1}" | grep -i "Writing library" | grep -i "${VIDEO}")
		if [[ "${ROKUVIDEO}" ]]; then
			VIDEOSUPPORT=1
		fi
	done
	if [[ "${VIDEOSUPPORT}" == 0 ]]; then
		Encapsulate "Video Supported: NO"
	else
		Encapsulate "Video Supported: YES"
	fi
}

CountFilez () {
	declare -i TOTALFILES;
	declare -a FILETOCONVERT=();
	for FILETYPE in "${EXTENSIONS[@]}"
	do
		while IFS=  read -r -d $'\0';
		do
			FILETOCONVERT+=("${REPLY}")
		done < <(find . -name "*.${FILETYPE}" -print0)
	done
	for EACH in "${FILETOCONVERT[@]}"
	do
		if ! [[ "${PRESERVE}" ]]; then
			FILENAME=$(echo "${EACH}" | cut -d "/" -f2)
		else
			FILENAME=$(basename "${EACH}")
			FILENAME=$(echo "${FILENAME%.*}")
		fi
		BASE=$(basename "${FILENAME}")
		if [[ "${DEBUG}" ]]; then
			echo "DEBUGGING: FILENAME: ${FILENAME} | EACH: ${EACH} | PRESERVE: ${PRESERVE} | BASE: ${BASE}"
		fi
		Encapsulate "Convert: ${EACH} to ${FILENAME}.mkv"
	done
	Center "Number of files to convert: ${#FILETOCONVERT[@]}"
	while true; do
		read -r -p "Convert the above ${#FILETOCONVERT[@]} files (Y/N)? " yn
		case "$yn" in
			[Nn]* ) exit 0;;
			[Yy]* ) break;;
			* ) echo "Please answer y or n.";;
		esac
	done
}

FileNamesOnly () {
	shopt -s dotglob
	shopt -s nullglob
	declare -a FOLDERS=();
	declare -a SUBFOLDERS=();
	FOLDERS=(./*)
	INFOLDER="${PWD}"
	#shopt -s nullglob
	for FOLDER in "${FOLDERS[@]}"
	do
		cd "${FOLDER}" || exit 1;
		Center "Scanning for filenames in ${FOLDER}."
		OUTFILE=$(basename "${PWD}")
		for EXTENSION in "${ALLEXTENSIONS[@]}"
		do
			if [[ "${DEBUG}" ]]; then
				echo "DEBUG: Looking for extension: ${EXTENSION}"
			fi
			MOVIES=(*.${EXTENSION})
			if [[ "${MOVIES[*]}" ]]; then
				if [[ "${MOVIES[*]}" != "${OUTFILE}.${EXTENSION}" ]]; then
					Encapsulate "In folder:${PWD} renaming ${MOVIES[@]} to ${OUTFILE}.${EXTENSION}."
					mv "${MOVIES[@]}" "${OUTFILE}"."${EXTENSION}"
				else
					Encapsulate "${OUTFILE}.${EXTENSION} is properly named in ${PWD}."
				fi
			fi
		done
		cd "${INFOLDER}" || exit 1;
	done
}

ScanOnly () {
	INFOLDER="${PWD}"
	FLICKZ=();
	CountFilez
	#shopt -s nullglob
	for EACH in "${EXTENSIONS[@]}"
	do
		while IFS=  read -r -d $'\0'; do
			FLICKZ+=("${REPLY}")
		done < <(find . -iname "*.${EACH}" -print0 | sort)
		for FLICK in "${FLICKZ[@]}"
		do
			if [[ "${DEBUG}" ]]; then
				echo "Scanning for ${EACH} in ${PWD} | FLICK:${FLICK}"
			fi
			OFILE=$(dirname "${FLICK}")
			TDIR="$(dirname "${FLICK}")/"
			FTP="$(dirname "${ln}")/$(basename "${ln}" ."${EACH}").jpeg" #FTP="$(dirname "${ln}")/$(basename "${ln}" .${EACH}).jpeg"
			Encapsulate "${FLICK} is in ${TDIR}:"
			if [[ -d "${TDIR}" ]]; then
				cd "${TDIR}" || exit 1;
				OFILE=$(dirname "${FLICK}")
				Encapsulate "Processing ${FLICK} in ${PWD} as ${OFILE}.${EACH}."
				VideoSupport "${FLICK}"
				AudioSupport "${FLICK}"
				cd "${INFOLDER}" || exit 1;
			else
				Error "Folder not found: ${TDIR}, exiting."
				exit 1;
			fi
		done
	done
}

Tag () {
	#re-write is happening now this entire section to allow it to not only allow individual files, but broadbased.  We are deving powerful tools at least in the cli, will write the gui to correnspond.  We want results & now, how can you advance software without that mode of thinking?  Does anyone care if I trash a Terabyte at a time in testing?  I now understand why I have tons of space.  Testing...

	FILE="${1}"
	DIR="${FILE%.*}"
	#echo "DEBUGGING: $FILE | $DIR"
	if [[ -f "${1}" ]]; then
		if [[ -f "$DIR.nfo" ]]; then
			Encapsulate "Skipping, nfo exists."
		else
			### Define the variables.
			FILENAME="${FILE}"
			DATERECORDED=$(mediainfo "${FILENAME}" | grep -i "date" | head -1 | awk -F" : " '{ print ${2} }' | tr -d '\r' | sed -e 's/ /\_/' | rev | cut -b 10- | rev | sed "s/UTC_//g")
			RECORDEDTIME=$(mediainfo "${FILENAME}" | grep -i "date" | head -1 | awk -F" : " '{ print ${2} }' | tr -d '\r' | sed -e 's/ /\_/' | cut -b 12- | rev | cut -b 4- | rev | cut -d " " -f2)
			LONGDATE=$(date -d "$DATE" "+%B %d, %Y")
			LONGTIME=$(date -d "$TIME" "+%l:%M %p" |  sed -e 's/^[ \t]*//')
			DURATION=$(ffmpeg -i "${FILENAME}" 2>&1 | awk '/Duration:/{$4 gsub(/\:/," ") ;realseconds= $4; seconds = int($4); minutes= ${3} ;hours= ${2};totalsoundtrack = (seconds+(minutes*60)+(hours*3600)) $8 } END { print hours ":" minutes ":" realseconds}' | rev | cut  -b 5- | rev)
			ASPECT=$(mediainfo "${FILENAME}" | grep -i "aspect" | head -1 | awk -F" : " '{ print ${2} }' | tr -d '\r' | sed -e 's/[/]/\:/')
			#MKVNAME="$DATE"_"$TIME"
			### Create an XBMC-compliant .nfo file
			FTH="$DIR"
			#echo ${FTH}
			echo "<episodedetails>" > "${FTH}".nfo
			echo "<title>${FTH}</title>" >> "${FTH}".nfo
			echo "<rating></rating>" >> "${FTH}".nfo
			echo "<season></season>" >> "${FTH}".nfo
			echo "<episode></episode>" >> "${FTH}".nfo
			echo "<plot>This video was recorded on ${LONGDATE} at ${LONGTIME}.</plot>" >> "${FTH}".nfo
			echo "<credits></credits>" >> "${FTH}".nfo
			echo "<director></director>" >> "${FTH}".nfo
			echo "<aired>${LONGDATE}</aired>" >> "${FTH}".nfo
			echo "<time>${LONGTIME}</time>" >> "${FTH}".nfo
			echo "<runtime>${DURATION}</runtime>" >> "${FTH}".nfo
			echo "</episodedetails>" >> "${FTH}".nfo

			echo "" >> "${FTH}".nfo
			echo "========== ORIGINAL FILE Info ==========" >> "${FTH}".nfo
			echo "" >> "${FTH}".nfo

			mediainfo "${FILENAME}" >> "${FTH}".nfo

			### Create an XBMC-compliant video thumbnail

			if [[ "${ASPECT}" == "4:3" ]]; then
				THUMBSIZE="640x480!"
			else
				THUMBSIZE="854x480!"
			fi

			ffmpegthumbnailer -i "${FILENAME}" -o temp.jpg -s 854
			convert -resize "${THUMBSIZE}" temp.jpg "${FTH}".jpg
			mv "${FTH}".jpg "${FTH}".tbn
			Encapsulate "Tagged"
			#mkvpropedit Star.Wars-Episode.1.The.Phantom.Menace.1999.720p.Bluray.Mkv --edit info --set "title=Star.Wars-Episode.1.The.Phantom.Menace" was going to actually impregnate the file, lets comply / keep the users happy.
		fi
	else
		Error "File does not exist: ${1}"
	fi
}

#1: Input Video 2:Output Video
ScanCompletion () {
	COMPLETION=0
	FALIURE=$(basename -- "${2}")
	FAILUREEXT="${2##*.}"
	if ! [[ -f "${1}" ]]; then
		Error "Source file not found 1: ${1}"
	fi
	if ! [[ "${SKIP}" ]]; then
		if ! [[ -f "${2}" ]]; then
			Error "Destination file not found: ${2}"
		fi
	fi
	if ! [[ "${SKIP}" ]]; then
		INSIZE=$(mediainfo "${1}" | grep -i "Duration" | head -1 | cut -d ":" -f2)
		OUTSIZE=$(mediainfo "${2}" | grep -i "Duration" | head -1 | cut -d ":" -f2)
		if [[ "${INSIZE}" == "${OUTSIZE}" ]]; then
			COMPLETION=1
			FullBar
			Encapsulate "Source duration: ${INSIZE} equals destination: ${OUTSIZE}"
			Encapsulate "Conversion complete: ${2}. Clearing Temp file: ${1}"
			rm "${1}"
		else
			FullBar
			Error "Critical Error: Conversion for ${2} FAILED."
			Encapsulate "Source duration: ${INSIZE} does not equal ${OUTSIZE}"
			Encapsulate "Please investigate: ${1}, not deleting."
			Encapsulate "Moving: ${1} ${FAILURE}.${FAILUREEXT}"
			mv ${1} "${FAILURE}.${FAILUREEXT}"
			FullBar
		fi
	fi
	SKIP=0
}

# Let's strip subtitles...
Subtitles () {
	IN="${1}"
	OUT="${1}"
	if ! [[ -f "${IN}" ]]; then
		Error "Critical Error in conversion (File Not Found): ${IN}"
		exit 1;
	else
		Encapsulate "Scanning for subtitles in: ${IN}."
		SUBS=$(mediainfo -i "${IN}" | grep "S_TEXT")
	fi
	if [[ "${SUBS}" ]]; then
		FILENAME="${1}"
		EXTENSION="${FILENAME##*.}"
		temp_file=$(mktemp /tmp/${PROGNAME}.XXXXX."${EXTENSION}")
		if [[ "${EXTENSION}" == "mkv" ]]; then
			Encapsulate "Stripping Subtitles from ${IN} to ${temp_file}"
			#Uncessary, large overhead for AVI based movies for example.
			OF=$(mkvmerge --no-subtitles "${IN}" -o "${temp_file}")
		fi
		if [[ -s "${temp_file}" ]]; then
			rm "${IN}"
			mv "${temp_file}" "${IN}"
		else
			mv "${temp_file}" "${IN}"
		fi
	else
		Encapsulate "No subtitles found."
	fi
}

#1: Input Video 2:Output Video
ConvertVideo () {
	IN="${1}"
	OUT="${2}"
	Subtitles "${IN}" "${OUT}"
	VideoSupport "${IN}"
	AudioSupport "${IN}"
	temp_file=$(mktemp /tmp/${PROGNAME}.XXXXX."${EXTENSION}")
	if ! [[ $"{SKIP" ]]; then
		if [[ -f "${1}" ]]; then
			Encapsulate "Copying ${1} to ${temp_file}"
			cp "${1}" "${temp_file}"
		else
			Error "File not found: ${1}, exiting."
			exit 1;
		fi
	fi
	if ! [[ "${PRESERVE}" ]]; then
		OUTBASE=$(basename -- "${2}")
		OUT="${OUTBASE}"
	fi
	if [[ "${CORES}" -gt 16 ]]; then
		Encapsulate "More then 16 cores / threads detected.  Setting 16 cores a limitation of ffmpeg (Complain to devs of ffmpeg)."
		CORES=16
	fi
	case "${AUDIOSUPPORT}" in
		0)  if  [[ "${VIDEOSUPPORT}" == "1" ]]; then
				Encapsulate "Processing Audio Only using ${CORES} core(s) / thread(s)."
				Encapsulate "Processing ffmpeg -y -i ${temp_file} -threads ${CORES} -c:v copy -c:a ac3 ${OUT}"
				FullBar
				GREPFAILURE=$(ffmpeg -y -i "${temp_file}" -threads "${CORES}" -c:v copy -c:a ac3 "${OUT}")
			else
				Encapsulate "Processing Audio & Video using ${CORES} core (s) thread(s).."
				Encapsulate "Processing ffmpeg -y -i ${temp_file} -threads ${CORES} -c:v libx264 -c:a ac3 ${OUT}"
				FullBar
				GREPFAILURE=$(ffmpeg -y -i "${temp_file}" -threads "${CORES}" -c:v libx264 -c:a ac3 "${OUT}")
		fi ;;
		1)  if  [[ "${VIDEOSUPPORT}" == "0" ]]; then
				Encapsulate "Processing Video Only using ${CORES} core(s) / thread(s)."
				Encapsulate "Processing ffmpeg -y -i ${temp_file} -threads ${CORES} -c:v libx264 -c:a copy ${OUT}"
				FullBar
				GREPFAILURE=$(ffmpeg -y -i "${temp_file}" -threads "${CORES}" -c:v libx264 -c:a copy "${OUT}")
			else
				Encapsulate "Video & audio is supported, not doing any conversion."
				SKIP=1
				FullBar
		fi;;
	esac

	if [[ -f "${temp_file}" ]]; then
		ScanCompletion "${temp_file}" "${OUT}"
	else
		Error "FATAL ERROR: Both situations have failed.  ${temp_file} does not exist as well ${OUT}."
		exit 1;
	fi
	#fi
	if [[ "${DEBUG}" ]]; then
		echo "DEBUG FAILURE: ${GREPFAILURE}"
	fi
}

ProcessVideo () {
	PROCESSED=0
	Timer Start "Process Video"
	for EACH in "$@"
	do
		if [[ -f "${EACH}" ]]; then
			INFILE="${EACH}"
			OUTFILE="${EACH%.*}"
		fi
	done
	if ! [[ "${PRESERVE}" ]]; then
		OUTFILE=$(basename "${PWD}")
		OUTFILE+=".mkv"
	fi
	if [[ "${INFILE}" == "" ]]; then
		INFILE="*"
	fi
	INCREMENT=0
	if [[ "${INFILE}" == "*" ]]; then
		for EXTENSION in "${EXTENSIONS[@]}"
		do
			INCREMENT=$((INCREMENT +1))
			Encapsulate "Processing extension type #${INCREMENT} (${EXTENSION}) of ${NOEXTENSIONS}"
			if [[ "${DEBUG}" ]]; then
				echo "DEBUG: We are in ${PWD}"
			fi
			shopt -s nocaseglob
			MOVIES=(*.${EXTENSION})
			TOTAL=${#MOVIES[@]}
			#PERVIDEO=0
			if [[ "${TOTAL}" -gt 0 ]]; then
				PERVIDEO=$(( PERVIDEO +1 ))
				Encapsulate "Number of Video(s) detected with ${EXTENSION} extension detected: ${TOTAL}"
				Encapsulate "Processing Video ${PERVIDEO} of ${TOTAL}"
				for MOVIE in "${MOVIES[@]}"
				do
					INFILE="${MOVIE}"
					OUTFILE="${MOVIE%.*}"
					OUTFILE+=".mkv"
					if [[ "${DEBUG}" ]]; then
						Encapsulate "Processing Video: ${INFILE} to ${OUTFILE} in ${PWD}"
					fi
					ConvertVideo "${INFILE}" "${OUTFILE}"
					FullBar
				done
			else
				Encapsulate "No video(s) detected with extension (${EXTENSION})."
			fi
		done
	else
		VideoSupport "${INFILE}"
		AudioSupport "${INFILE}"
		if [[ "${AUDIOSUPPORT}" == "1" && "${VIDEOSUPPORT}" = "1" ]]; then
			Encapsulate "No need to process: ${INFILE} audio and video is supported."
			FullBar
			if [[ "${FORCED}" ]]; then
				Encapsulate "Forced encoding switch detected for: ${INFILE} audio and video will be encoded."
				VIDEOSUPPORT=0
				AUDIOSUPPORT=0
				ConvertVideo "${INFILE}" "${OUTFILE}"
				PROCESSED=$((PROCESSED +1))
				Encapsulate "Video(s) currently processed: ${PROCESSED} of ${TOTAL}"
				return
			fi
			return;
		else
			ConvertVideo "${INFILE}" "${OUTFILE}"
			PROCESSED=$((PROCESSED +1))
			Encapsulate "Video(s) currently processed: ${PROCESSED} of ${TOTAL}"
		fi
	fi
	if [[ "${DEBUG}" ]]; then
		echo "AUDIO: ${AUDIOSUPPORT} | VIDEO: ${VIDEOSUPPORT}"
	fi
	FullBar
	Timer "Stop" "Process Video"
}

MergeVideo () {
	# tons of work to do here & no time currently.
	Timer "Start" "Merge Video"
	DIR=$(echo "$*" | grep -i "\\-d")
	if [[ "$DIR" ]]; then
		OUTFILE=$(basename "${PWD}")
	else
		for EACH in "$@"
		do
			if [[ -f "${EACH}" ]]; then
				OUTFILE="${EACH%.*}"
			fi
		done
	fi
	if [[ "${DEBUG}" ]]; then
		echo "Debugging Fileout: ${OUTFILE}"
	fi
	STD_IN=0
	prefix=""
	key=""
	value=""
	for keyValue in "$@"
	do
		case "${prefix}${keyValue}" in
			-o*|--output=*)  key="-o";	 value="${keyValue#*}";;
			*)									  value="${keyValue}";;
		esac
	done
	if [[ "${DEBUG}" ]]; then
		echo "DEBUGGING: KEYVALUE=$value KEY=$key"
	fi
	declare -a EXISTS=();
	FILEZ=();
	FILESIZES=();
	for VIDEO in "$@"
	do
		if [[ -f "${VIDEO}" ]]; then
			Encapsulate "Checking for existance of ${VIDEO} it exists."
			FILEZ+=("${VIDEO}")
		else
			if ! [[ "${VIDEO}" == "-o" || "${VIDEO}" == "${value}" || "${VIDEO}" == "" || "${VIDEO}" == "--merge" || "${VIDEO}" == "-m" ]]; then
				Error "Checking for existance of ${VIDEO} it does not exist."
			fi
		fi
	done
	#STATEMENT=$(echo -n "-oac copy -ovc copy ")
	for EACH in "${FILEZ[@]}"
	do
		STATEMENT+=$(echo -n "${EACH} ")
		EXTENSION="${EACH##*.}"
	done
	if [[ "$DIR" ]]; then
		OUTFILE="${OUTFILE}.${EXTENSION}"
	else
		OUTFILE="$value"
	fi
	if [[ "${EXTENSION}" == "avi" || "${EXTENSION}" == "Avi" ]]; then
		Encapsulate "Executing... mencoder -oac copy -ovc copy ${STATEMENT}-o ${OUTFILE}"
		FullBar
		mencoder -oac copy -ovc copy "${STATEMENT}" -o "${OUTFILE}"
		FullBar
	fi
	if [[ "${EXTENSION}" == "mp4" || "${EXTENSION}" == "Mp4" ]]; then
		Encapsulate "Executing... mencoder -oac pcm -ovc copy ${STATEMENT}-o ${OUTFILE}"
		FullBar
		mencoder -oac pcm -ovc copy "${STATEMENT}" -o "${OUTFILE}"
		FullBar
	fi
	Columnize -t "SIZE IN BYTES" "FILE"
	NUMBER=0
	for EACH in "${FILEZ[@]}"
	do
		((NUMBER=NUMBER+1))
		FILESIZES+=$(stat --printf="%s" "${EACH}")
		FILESIZE=$(stat -c%s "${EACH}")
		FDISKSIZE=$(printf "%'.3f\n" "${FILESIZE}")
		FILESIZE=$(echo "${FDISKSIZE}" | cut -d. -f1)
		Columnize "${FILESIZE}" "${EACH}"
	done
	FullBar
	FILESIZE=$(stat --printf="%s" "${OUTFILE}")
	FDISKSIZE=$(printf "%'.3f\n" "${FILESIZE}")
	FILESIZE=$(echo "${FDISKSIZE}" | cut -d. -f1)
	Center "${OUTFILE} FILESIZE=${FILESIZE} bytes."
	Encapsulate "Checking for success / failure."
	if [[ -f "${OUTFILE}" ]]; then
		if [[ -s "${OUTFILE}" ]]; then
			for EACH in "${FILEZ[@]}"
			do
				if [[ "${EACH}" != "${OUTFILE}" ]]; then
					Encapsulate "Success, removing: ${EACH}"
					rm "${EACH}"
				fi
			done
		else
			Error "Error: ${OUTFILE} did not encode properly."
		fi
	else
		Error "Error: ${OUTFILE} did not encode properly."
	fi
	FullBar
	Timer "Stop" "Merge Video"
	FullBar
}

Sort () {
	case "${1}" in
		-f|--files) FILES=(*);;
		-d|--directories) FILES=(./*);;
		* ) Encapsulate "Invalid option: ${1}"; Encapsulate "${PROGNAME} --sort --files"; Encapsulate "Will sort all files in current folder.";exit 0;;
	esac
	Encapsulate "Pattern: ${FILES}"
	for FILE in "${FILES[@]}"
	do
		# echo "Processing: ${FILE}"
		if [[ "${1}" == "--files" ]]; then
			if [[ -f "${FILE}" ]]; then
				FTP=$(basename "${FILE}" | sed 's/\(.*\)\..*/\1/')
				# echo "FILEFOUND: ${FILE} | ${FTP}"
				mkdir "${FTP}/"
				mv "${FILE}" "${FTP}/"
			fi
		fi
	done
}

TheeMahn () {
	Timer "Start" "TheeMahn"
	declare -i INDEX;
	INDEX=0
	Process -d -YES
	# shopt -s dotglob
	declare -a NAMING=();
	NAMING=( "-Usury" "-Cmrg" ".Will1869" "-.Eng" ".Eng" "-.Ac3" ".Ac3" "-.X264" ".X264" "-.H264" ".H264" "H.264" "H264" ".Hevc" "-.Divx" ".Divx" ".Dd+5.1" ".Multi.Dvdrip" "-.Hdrip" ".Hdrip" "-.Dvdrip" ".Dvdrip" "Dvdrip" ".Bluray" ".Dts" ".-Adtrg" "-Adtrg" ".-Etrg" "-Etrg" ".Etrg" "-Aqos" ".Aqos" "-Juggs" ".Juggs" "-Evo" ".Evo" "-.720p" ".720p" "-.Hdrip" ".Hdrip" ".-Vlis" "-Vlis" ".1080p" "1080p" ".-Maxspeed" "-Maxspeed"  ".Web-Dl" ".Webdl" "-.Webrip" ".Webrip" "-.Brrip" ".Brrip" ".Dvdscr" ".Dvdscr" "-.3d" ".3d" ".-Axxo" "-Axxo" "-.Hdtv" ".Hdtv" ".-Sam" ".-Ptpower" ".-Diamond" ".Diamond" "Legi0n" "Anonym0us" ".Dd5.1" ".Dd5" "-Rarbg" ".Rarbg" ".-Santi" ".By.Smelly-Cat" ".-S4a" ".Hsbs" ".(Silvertorrent)" ".No1knows" ".Aac2.0" "Aac2.0" ".Retail" "-Playnow" ".Hq.Hive-Cm8" "-Jyk" "-Sir.Paul" ".Omt" ".Hive-Cm8" ".-Fas" ".-An0nym0us" ".-Hellraz0r" ".Readnfo" "-Nvadr" ".-Klaxxon700mb" ".-Fingerblast" ".-Nedivx" ".Unrated" ".Amzn" "Ddp2.0" ".Remux" ".Blu-Ray" ".Avc" ".-Hd" "Ddp5.1" "5.1" ".10bit" ".Dd+7.1" "Dd+7.1" ".Amazon.Will1869" ".Amazon" ".Anoxmous" ".-Publichd" "Amzn" ".{1337x}-Noir" ".Will1869" ".-Guacamole" ".-Cmrg" ".2160p" ".Uhd" ".X265" ".-B0mbardiers" ".Extended.Cut" ".Remux" ".Directors.Cut" ".Atmos" ".Truehd" ".7.1" ".X26h" ".-Roccat" "Dd" ".Ift" ".Ma.Dd+.-" ".Nf" "-Pignus" ".Hdr" ".(Liltvision)" "-.1080p" ".Web-Dl" ".(Liltv)" ".-Gasmask" ".H.265" ".X260bit" ".Hd" "-Swtyblz" "Www.Torrenting.Com.-." ".x264" "-BARC0DE" "BluRay" ".-.4k" "-.4k" ".4k" ".-" "Web" ".Aa" ".Yts" ".Mx" ".REPACK" ".WEB" ".DDPREVILS");
	declare -a DIRECTORIES=();
	declare -i STRIPTYPES;
	declare -i NDIRECTORIES=();
	DIRECTORIES=(*/)
	NDIRECTORIES="${#DIRECTORIES[@]}"
	for EACH in "${DIRECTORIES[@]}"
	do
		THERE=$(echo "${EACH}" | grep -e ".\[")
		if [[ "${THERE}" ]]; then
			REPLACEMENT="${EACH//[/.}"
			STRIPPED="${REPLACEMENT//]/.}"
			PERIODS="${STRIPPED//../.}"
			Encapsulate "Stripping brackets from: ${EACH} Replaced: ${PERIODS}"
			mv "${EACH}" "${STRIPPED}"
		fi
	done
	Process -d -YES
	# Wasted cycles probably.  I want to be sure I am not boogering your folders.
	Process -d -YES
	DIRECTORIES=(*/)
	STRIPTYPES="${#NAMING[@]}"
	# snap open a nested loop.  Process data with the quickness.
	for DIRNAME in "${NAMING[@]}"
	do
		INDEX=$(( INDEX + 1 ))
		PCOMP=$((100*INDEX / STRIPTYPES))
		ProgressBar "$PCOMP" "Processing ${NDIRECTORIES} folder(s) :${DIRNAME} ${INDEX} of ${STRIPTYPES}"
		for EACH in "${DIRECTORIES[@]}"
		do
			# Sanitize "${EACH}" - garbage.
			# echo "Testing Each: ${EACH} against: ${DIRNAME}" - in house debugging.
			TESTIT=$(echo "${EACH}" | grep -e "${DIRNAME}")
			if [[ "${TESTIT}" ]]; then
				# echo "Found Each: ${EACH} against: ${DIRNAME}" - debugging.
				#read -n 1 -s -r -p "TESTIT: ${TESTIT}:  Dirname: ${DIRNAME}\n Press any key to continue" - pause so I can see it as it happens. - debugging again.
				FIXEDNAME=$(echo "${EACH}" | sed "s/${DIRNAME}//g")
				mv "${EACH}" "${FIXEDNAME}"
				# tmrename -d -YES - unnessary stokes of I/O and CPU.
				# mv "${EACH}" $(echo "${EACH}" | sed -e 's/[^A-Za-z0-9._-]//g') - fixed way above and with the quickness.
				if [[ "${PCOMP}" -ge 99 ]]; then
						Process -d -YES # try and strip double periods before the array is reloaded.  We are at 99%+ done.
				fi
				DIRECTORIES=(*/) #reload array with changes.
			fi
		done
	done
	Process -d -YES
	Process -d -YES  # pull again in case double periods in folder names.  At this point probably unnessary.
	Timer "Stop" "TheeMahn"
}

VideoTag () {
	Timer "Start" "VideoTag"
	Sort "--files" "-Y"
	TheeMahn "@"
	GIO=$(type -p gio)
	FFMPEGTHUMBNAILER=$(type -p ffmpegthumbnailer)
	INFOLDER="${PWD}"
	declare -i PROCESS;
	declare -i CREATED;
	declare -i COVERS;
	declare -i NFOS;
	shopt -s nullglob
	declare -a COVER=();
	EXTENSIONS=( "avi" "mp4" "mkv" "Mp4" "Avi" "Mp4" );
	CREATED=0
	NFOS=0
	COVERS=0
	VTYPES="${#EXTENSIONS[@]}"
	if [[ -d "${2}" ]]; then
		PROCESS=1
		cd "${2}" || exit 0;
		for EACH in "${EXTENSIONS[@]}"
		do
			PROCESS=$((PROCESS+1))
			Encapsulate "Processing ${2} for video format: ${EACH}.  Type ${PROCESS} of ${VTYPES} available."
			find . -type f -iname \*."${EACH}" | while read ln;
			do
				cd "${ln}" || exit 1;
				POSTER=$(printf '%s\n' *"poster"*.jpeg)
				if [[ "${POSTER}" ]]; then
					Encapsulate "Cover found: ${POSTER} copying."
					cp "${POSTER}" cover.jpeg
					cp "${POSTER}" cover.jpg
					FOUNDCOVER=1
					FOUND=$(( FOUND + 1))
				fi
				COVER=$(printf '%s\n' *"cover"*.jpeg)
				if ! [[ "${COVER}" ]]; then
					FTP="$(dirname "${ln}")/$(basename "${ln}" .${EACH}).jpeg"
					TDIR="$(dirname "${ln}")/"
					ffmpegthumbnailer -i "${ln}" -o "${FTP}"
					Encapsulate "Creating thumbnail file: ${FTP}"
					Encapsulate "Creating Cover for ${ln} Destination: ${TDIR}"
				fi
				cd "${INFOLDER}" || exit 1;
			done
			CREATED=$((CREATED+1))
		done
		Encapsulate "Thumbnails Created: ${CREATED}"
	else
		shopt -s nullglob
		declare -a FOLDERS=();
		declare -a SUBFOLDERS=();
		FOLDERS=(./*)
		PROCESS="${#FOLDERS[@]}"
		INFOLDER="${PWD}"
		#shopt -s nullglob
		for FOLDER in "${FOLDERS[@]}"
		do
			if [[ -d "${FOLDER}" ]]; then
				cd "${FOLDER}" || exit 1;
			else
				Error "Will not process files."
				COVER=$(printf '%s\n' *"cover"*.jpg)
				if ! [[ "${COVER}" ]]; then
					for EACH in "${VTYPES[@]}"
					do
						VIDEO=$(*."${EACH}")
						if [[ "${VIDEO}" ]]; then
							Encapsulate "Creating thumbnail for ${VIDEO}"
							ffmpegthumbnailer -i "${VIDEO}" -o Cover.jpeg
							CREATED=$(( CREATED + 1))
						fi
					done
				fi
			fi
			COVER=$(printf '%s\n' *"cover"*.jpg)
			POSTER=$(printf '%s\n' *"poster"*.jpg)
			if ! [[ "${COVER}" ]]; then
				if [[ "${POSTER}" ]]; then
					Encapsulate "Cover found in ${PWD}: ${POSTER} copying."
					OLDFOLDER="${PWD}"
					cp "${POSTER}" Cover.jpeg
					cp "${POSTER}" Cover.jpg
					FOUNDCOVER=1
					FOUND=$(( FOUND + 1))
				fi
			fi
			if [[ "${FFMPEGTHUMBNAILER}" ]]; then
				if [[ "${FOUNDCOVER}" ]]; then
					COVER=$(printf '%s\n' *"cover"*.jpg)
					if ! [[ "${COVER}" ]]; then
						for EACH in "${VTYPES[@]}"
						do
							VIDEO=$(*."${EACH}")
							if [[ "${VIDEO}" ]]; then
								Encapsulate "Creating thumbnail for ${VIDEO}"
								ffmpegthumbnailer -i "${VIDEO}" -o Cover.jpeg
								CREATED=$(( CREATED + 1))
							fi
						done
					fi
				fi
			else
				if [[ "${ISARCH}" ]]; then
					Error "No Cover found and ffmpegthumbnailer is not installed, we are done.  sudo pacman -Syuu ffmpegthumbnailer"
				else
					Error "No Cover found and ffmpegthumbnailer is not installed, we are done.  sudo apt-get install ffmpegthumbnailer"
				fi
			fi
			FOUNDCOVER=0
			cd "${INFOLDER}" || exit 1;
			if [[ "${GIO}" ]]; then
				Encapsulate "Setting default icon: file://${PWD}/${OLDFOLDER}/Cover.jpeg"
				gio set -t "string" "${OLDFOLDER}/" "metadata::custom-icon" "file:///${OLDFOLDER}/Cover.jpeg"
			fi
		done
		PROCESS=$(( PROCESS +1 ))
		Encapsulate "Thumbnails Created: ${CREATED} | Covers found: ${FOUND} | nfo's created: ${NFOS} | Processed: ${PROCESS}"
	fi
	Timer "Stop" "VideoTag"
	FullBar
}

Help () {
#CONTAINS=$(echo "$*" | grep -w '\-h\|\-\-help')
	if [[ "${DEBUG}" ]]; then
		echo "DEBUGGING HELP FUNCTION: 1:${1} 2:${2} 3:${3} CONTAINS:${CONTAINS}"
	fi
	if ! [[ "${2}" == "" && "${CONTAINS}" ]]; then
		if [[ "${2}" != "" ]]; then
			PRAM="${2}"
		else
			PRAM="ALL"
		fi
	fi
	case "${PRAM}" in

# Main Menu
	ALL)
	Encapsulate "Usage: ${PROGNAME} -<-COMMAND> [OPTION]"
	FullBar
	Encapsulate "Mandatory arguments to long options are identical for short options."
	Encapsulate "  possible commands..."
	Encapsulate " "
	Encapsulate " -c --convert       makes video(s) ©Roku compatible."
	Encapsulate " -f --filenamesonly renames video files based on folder name."
	Encapsulate " -h --help          this help message."
	Encapsulate " -i --info          displays information about video."
	Encapsulate " -m --merge         merges multiple video(s)."
	Encapsulate " -r --rename        recursively renames video(s)."
	Encapsulate " -R --recursive     recursively converts video(s) to ©Roku format."
	Encapsulate " -v --version       dump version info and exit."
	Encapsulate " -V --videotag      recursively tag video(s) and exit."
	Encapsulate " "
	FullBar
	Center "${PROGNAME} --help [COMMAND] for further information."
	FullBar;;

# Convert videos Help
	ALL|c|convert)
		Encapsulate "Usage convert;"
		FullBar
		Center "${PROGNAME} -c [VideoFile] [force]"
		FullBar
		Encapsulate "Converts optional [VideoFile] to Roku compatable format."
		Encapsulate "Optional is because if you do not specify a file will convert"
		Encapsulate "all files supported currently in the folder you are in."
		Encapsulate ""
		Encapsulate "[force] option will force ${PROGNAME} to convert audio and video"
		Encapsulate "Current formats:"
		for EACH in "${EXTENSIONS[@]}"
		do
			Encapsulate "${EACH}"
		done
		FullBar
		Encapsulate "Example: ${PROGNAME} --convert The.Bone.Collector.1999.avi"
	FullBar;;
# Filenames only Help
	ALL|f|filenamesonly)
	Encapsulate "Usage filenames;"
	FullBar
	Center "${PROGNAME} -f "
	FullBar
	Encapsulate "Recursiveliy scans and renames filenames to Roku compatable format."
	Encapsulate "Optional is because if you do not specify a file will convert"
	Encapsulate "all filesnames."
	Encapsulate ""
	Encapsulate "Current formats:"
	for EACH in "${EXTENSIONS[@]}"
	do
		Encapsulate "${EACH}"
	done
	FullBar;;
# Rename Help
	ALL|r|rename)
	Encapsulate "Usage rename;"
	FullBar
	Center "${PROGNAME} -r [rename]"
	FullBar
	Encapsulate "Makes Roku Ripper scan all subfolders in your current path through"
	Encapsulate "all subfolders looking for all supported formats and converts them"
	Encapsulate "in place to Roku format.  Removing the old file after verifying success."
	Encapsulate ""
	Encapsulate "I highly suggest making a backup of the videos you are processing."
	Encapsulate "The optional [rename] switch will rename the file to the name of the"
	Encapsulate "subfolder the file was found in."
	Encapsulate "Example: ${PROGNAME} --recursive rename"
	FullBar;;
# Recursive Help
	ALL|R|recursive)
	Encapsulate "Usage recursive;"
	FullBar
	Center "${PROGNAME} -R [rename]"
	FullBar
	Encapsulate "Makes Roku Ripper scan all subfolders in your current path through"
	Encapsulate "all subfolders looking for all supported formats and converts them"
	Encapsulate "in place to Roku format.  Removing the old file after verifying success."
	Encapsulate ""
	Encapsulate "I highly suggest making a backup of the videos you are processing."
	Encapsulate "The optional [rename] switch will rename the file to the name of the"
	Encapsulate "subfolder the file was found in."
	Encapsulate "Example: ${PROGNAME} --recursive rename"
	FullBar;;

# Info Help
	ALL|i|info)
	Encapsulate "Usage info;"
	FullBar
	Center "${PROGNAME} -i <VIDEOFile>"
	FullBar
	Encapsulate "Displays general information for an Video."
	Encapsulate "Example: ${PROGNAME} --info The Matrix.avi"
	FullBar;;

# VideoTag
	ALL|V|videotag)
	Encapsulate "Usage videotag;"
	FullBar
	Center "${PROGNAME} -V"
	FullBar
	Encapsulate "Scans and moves movie files sets folder names renames apropriately.  Then scans for nfo's and sets cover file per folder recursively and exits."
	FullBar;;

# Version Help
	ALL|v|version)
	Encapsulate "Usage version;"
	FullBar
	Center "${PROGNAME} -v"
	FullBar
	Encapsulate "Displays ${PROGNAME}'s version number and exits."
	FullBar;;

# Help Help
	ALL|h|help|\?)
	Encapsulate "Usage Help [COMMAND]"
	FullBar
	Center "${PROGNAME} -h [COMMAND]"
	FullBar
	Encapsulate "Displays this message. For futher information ${PROGNAME} help [COMMAND]"
	Encapsulate "or refer to the manpages."
	Encapsulate " "
	Encapsulate "man ${PROGNAME}"
	Encapsulate " "
	Encapsulate "Example: ${PROGNAME} -h version"
	Encapsulate "Will display help about the command switch version"
	FullBar
esac
exit 0;
}

Recursive () {
	Timer "Start" "Recursive encoding."
	INFOLDER="${PWD}"
	FLICKZ=();
	CountFilez
	if ! [[ "${PRESERVE}" ]]; then
		FileNamesOnly
	fi
	shopt -s nocaseglob
	Center "Scanning for mergable movies."
	for EACH in "${EXTENSIONS[@]}"
	do
		while IFS=  read -r -d $'\0'; do
			FLICKZ+=("${REPLY}")
		done < <(find . -iname "*CD*.${EACH}" -print0 | sort)
		for FLICK in "${FLICKZ[@]}"
		do
			OFILE=$(dirname "${FLICK}")
			TDIR="$(dirname "${FLICK}")/"
			FTP="$(dirname "${ln}")/$(basename "${ln}" .${EACH}).jpeg"
			Encapsulate "Found: ${FLICK} is in ${TDIR}:"
			#shopt -s nullglob
			if [[ -d "${TDIR}" ]]; then
				cd "${TDIR}" || exit 1;
				Process -f -YES
				FileNamesOnly
				while IFS= read -d $'\0' -r file ; do
					file_list=("${file_list[@]}" "$file")
				done < <(find . -iname "*CD*.${EACH}" -print0)
				IFS=$'\n' MERGE=($(sort <<<"${file_list[*]}"))
				unset IFS
				COMMAND="roku-ripper -m "
				for FILENAMES in "${MERGE[@]}"
				do
					COMMAND+="${FILENAMES} "
				done
			COMMAND+="-o ${OFILE}.${EACH}"
			Encapsulate "Merging: ${COMMAND} in ${PWD}"
			$COMMAND
			exit 1;
			fi
		done
	done
	if ! [[ "$EXEC" ]]; then
		Center "All applicable movies have been merged, processing each movie to Roku format."
		#Encapsulate "Command: roku-ripper -m ${MERGE[@]} -o ${OFILE}.${EACH}"
		if [[ "${DEBUG}" ]]; then
			echo "DEBUGGING: PWD: ${PWD}, changing to folder: ${INFOLDER} or exiting."
		fi
		cd "${INFOLDER}" || exit 1;
		FullBar
	else
		if [[ "${DEBUG}" ]]; then
			echo "DEBUGGING: PWD: ${PWD}, changing to folder: ${INFOLDER} or exiting PASSING: roku-ripper $@."
		fi
		cd "${INFOLDER}" || exit 1;
		roku-ripper "$@"
	fi
	if [[ "${DEBUG}" ]]; then
		echo "DEBUGGING: PWD: ${PWD}, Scan routine starting or exiting."
	fi
	#exit 1;
	#WORKING CODE
	for EACH in "${EXTENSIONS[@]}"
	do
		while IFS=  read -r -d $'\0'; do
		FLICKZ+=("${REPLY}")
	done < <(find . -iname "*.${EACH}" -print0 | sort)
		for FLICK in "${FLICKZ[@]}"
		do
			if [[ "${DEBUG}" ]]; then
				echo "Scanning for ${EACH} in ${PWD} | FLICK:${FLICK}"
			fi
			OFILE=$(dirname "${FLICK}")
			TDIR="$(dirname "${FLICK}")/"
			FTP="$(dirname "${ln}")/$(basename "${ln}" ."${EACH}").jpeg" #FTP="$(dirname "${ln}")/$(basename "${ln}" .${EACH}).jpeg"
			Encapsulate "${FLICK} is in ${TDIR}:"
			if [[ -d "${TDIR}" ]]; then
				cd "${TDIR}" || exit 1;
				OFILE=$(dirname "${FLICK}")
				Encapsulate "Processing ${FLICK} in ${PWD} as ${OFILE}.${EACH}."
				roku-ripper -c
				cd "${INFOLDER}" || exit 1;
			else
				Error "Folder not found: ${TDIR}, exiting."
				exit 1;
			fi
		done
	done
	Timer "Stop" "Recursive encoding."
}

Rename () {
	INFOLDER="${PWD}"
	FLICKZ=();
	TRENAME=0
	declare -a FLICKTYPES=();
	#shopt -s nullglob
	FLICKTYPES=( 'mp4' );
	for EACH in "${FLICKTYPES[@]}"
	do
	FileNamesOnly
	exit 0;
	while IFS=  read -r -d $'\0'; do
		FLICKZ+=("${REPLY}")
	done < <(find . -type f -iname "*.${EACH}" -print0)
		for FLICK in "${FLICKZ[@]}"
		do
			OFILE=$(dirname "${FLICK}")
			TDIR="$(dirname "${FLICK}")/"
			FTP="$(dirname "${ln}")/$(basename "${ln}" ."${EACH}").jpeg"
			if [[ -d "${TDIR}" ]]; then
				cd "${TDIR}" || exit 1;
				OFILE=$(dirname "${FLICK}")
				if ! [[ -f "${OFILE}.${EACH}" ]]; then
					Encapsulate "Renaming: ${TDIR} in ${PWD} as ${OFILE}.${EACH}."
					FLICKNAME=$(basename "${FLICK}")
					mv "${FLICK}NAME" "${OFILE}"."${EACH}"
					TRENAME=$(( TRENAME + 1 ))
				#else
					#tmrename -f -YES
					#Encapsulate "Already renamed: in ${PWD} as ${OFILE}.${EACH}."
				fi
				cd "${INFOLDER}" || exit 1;
			else
				Error "Folder not found: ${TDIR}, exiting."
				exit 1;
			fi
		done
	done
	Encapsulate "Files renamed: ${TRENAME}"
}

VideoInfo () {
	Timer "Start" "Video Info"
	for EACH in "$@"
	do
		if [[ -f "${EACH}" ]]; then
			Center "Retriving media info for: ${EACH}"
			FullBar
			mediainfo "${EACH}"
			FullBar
		fi
	done
	Timer Stop "Video Info"
}

if ! [[ "${SUPPRESS}" ]]; then
	VersionDump "$@"
	Timer "Start" "${APPNAME}"
else
	Timer "Start" "${APPNAME}"
fi

case "${1}" in
	-f|--filenamesonly) FileNamesOnly "$@"; exit 0;;
#	-h|--help|-\?) Help "$@"; exit 0;;
	-i|--info) VideoInfo "$@"; exit 0;;
	-m|--merge) MergeVideo "$@"; exit 0;;
	-c|--convert) ProcessVideo "$@"; exit 0;;
#	-v|--version) VersionDump "$@"; exit 0;;
	-V|--videotag) VideoTag "$@"; exit 0;;
	-R|--recursive) Recursive "$@"; exit 0;;
	-r|--rename) Rename "$@"; exit 0;;
	-s|--scanonly) ScanOnly "$@"; exit 0;;
	*) Help "$@"; exit 0;;
esac
