#!/bin/bash

# Description #
# A script to aid in the conversion of Vobsub (.sub/.idx) subtitles, back to DVD using dvdauthor
# This script uses the subtitleripper package available at subtitleripper.sf.net
#  but eliminates the need for an Optical Character Recognition (OCR) step by overlaying the
#  extracted graphics files directly into the MPEG stream via spumux
# Author: rickfharris@yahoo.com.au
#
# Depends:	vobsub2pgm	-> subtitleripper.sf.net
#		imagemagick	-> www.imagemagick.org
#		spumux		-> dvdauthor.sf.net
#
# Usage: ./vobsub2spumux.sh baseinputname baseoutputname <options>

help_text () {
	echo -e "\n Usage: $0 baseinputname baseoutputname <options>"
	echo "	-t <subtitle_track>	Set the subitle track number, default is 0"
	echo -e "	-n <n|p>		Set the TV format to either PAL or NTSC, default is PAL\n"
	exit
}

die () {
	echo -e "\n Oops, an error has occurred, exiting!\n"
	exit
}

	BASE_INNAME="$1"
	BASE_OUTNAME="$2"
	if [ -z "$BASE_INNAME" ] || [ -z "$BASE_OUTNAME" ]; then
		help_text
	else
		until [ -z "$1" ] ; do
			case "$1" in
			-t) shift;	if [ -z "$1" ]; then
						help_text
					else
						while [ ! -z "$1" ] && [ "$1" != "-n" ]; do
							VOBSUB_ID="$1"
							shift
						done
					fi;;
			-n) shift;	if [ -z "$1" ]; then
						help_text
					else
						while [ ! -z "$1" ] && [ "$1" != "-t" ]; do
							TV_NORM="$1"
							shift
						done
					fi;;
			*) shift;;
			esac
		done
	fi

	[ -z "$VOBSUB_ID" ] && VOBSUB_ID=0
	if [ -z "$TV_NORM" ]; then TV_HEIGHT=576
	elif [ "$TV_NORM" = "p" ]; then TV_HEIGHT=576
	elif [ "$TV_NORM" = "n" ]; then TV_HEIGHT=480
	fi

	echo -e "\n Running: vobsub2pgm "$BASE_INNAME" "$BASE_OUTNAME" -t"$VOBSUB_ID" -c 255,0,0,0 -g5 -v\n"
	vobsub2pgm "$BASE_INNAME" "$BASE_OUTNAME" -t"$VOBSUB_ID" -c 255,0,0,0 -g5 -v || die
	echo -en " Creating '"$BASE_OUTNAME".xml' for spumux, please wait ..."

cat <<EOF > $BASE_OUTNAME.xml
<subpictures>
        <stream>
EOF
	SPUIMAGE_ID=1
	for PTS in `cat "$BASE_OUTNAME".srtx | grep "\-->" | sed 's/,/./g;s/[0-9] / /g;s/[0-9]$//g;s/ --> /_/g'`; do
		SPU_START=`echo "$PTS" | awk -F_ '{print $1}'`
		SPU_END=`echo "$PTS" | awk -F_ '{print $2}'`
		SPUIMAGE=""$BASE_OUTNAME"$(printf "%.4d\n" $SPUIMAGE_ID ).png"
		SPUIMAGE_SIZE=`identify "$SPUIMAGE" | awk '{print $3}'`
		SPUIMAGE_WIDTH=`echo "$SPUIMAGE_SIZE" | cut -dx -f1`
		SPUIMAGE_HEIGHT=`echo "$SPUIMAGE_SIZE" | cut -dx -f2`
		XOFFSET=`perl -le "print int((720 - $SPUIMAGE_WIDTH)/2)"`
		YOFFSET=`perl -le "print int(($TV_HEIGHT - 20) - $SPUIMAGE_HEIGHT)"`
		echo -e "\t\t<spu image=\"$SPUIMAGE\" start=\"$SPU_START\" end=\"$SPU_END\" xoffset=\"$XOFFSET\" yoffset=\"$YOFFSET\" />" >> "$BASE_OUTNAME".xml
		SPUIMAGE_ID=$(($SPUIMAGE_ID+1))
	done
cat <<EOF >> $BASE_OUTNAME.xml
        </stream>
</subpictures>
EOF

echo -e "Done!\n\n Now run for example 'spumux -s0 "$BASE_OUTNAME".xml < movie.VOB > movie_new.VOB'\n"
