#!/bin/bash

usage()
{
	echo "makecd v0.2.1 (part of dvdrtools)"
	[ -n "$1" ] && echo $1
	cat <<EOF
Usage:
makecd [-a bitrate] [-b] [-g] [-k] [-d device] [-f format] [-s standard] [-v bitrate] file1 [file2] ...
	-a:          Set audio bitrate (for DVD images only)
	-b:          Blank CD-RW first
	-g:          GUI mode - make the output GUI parseable
	-k:          Keep ISO file
	-d device:   Use specified device [default: 0,0,0]
	-f format:   Use specified format:
	             data: Normal data CD/DVD
	             dvd: Video DVD
	             audio: Audio CD
                     mp3: MP3 CD (for HW MP3 players)
	             mpeg4: MPEG4 CD/DVD
	-p o|a:      Write or append on a DVD PLUS (DVD+R/+RW) medium
	-s standard: TV standard (for video DVD)
	             ntsc: NTSC (720x480, 29.970 fps)
	             pal: NTSC (720x576, 25 fps)
	-S speed:    Set recording speed
	-t dir:      Place temporary files in a directory other
	             than /tmp (they can get big...)
	-T:          Use transcode instead of replex even if both are installed
	-M:          Use mencoder+replex instead of transcode, even if the
	             bitrate has to be changed
	-u:          Use UDF filesystem
	-v:          Preferred video bitrate (for DVD images only)
	             If given as "x,y", x is the avg. bitrate, y the maximum
	             bitrate.
	-N:          Don't change the bitrate
EOF
	exit 0
}

prompt() {
	if [ -n "$GUIMODE" ]; then
		echo "PROMPT[ok|cancel]: `echo $1 |sed -e 's,\\\n, ,g'`"
	else
		echo -e $1
		echo $"Press return or type \"cancel\" to exit"
	fi
	read a
	[ "`echo $a |tr A-Z a-z`" = "cancel" ] && exit 1
}

yesno() {
	if [ -n "$GUIMODE" ]; then
		echo "PROMPT[yes|no|cancel]: `echo $1 |sed -e 's,\\\n, ,g'`"
	else
		echo -e $1
		echo $"Please type \"yes\" or \"no\", or \"cancel\" to exit"
	fi
	read a
	[ "`echo $a |tr A-Z a-z`" = "cancel" ] && exit 1
	[ "`echo $a |tr A-Z a-z`" = "yes" ] && return 0
	return 1
}

ask_append() {
	if [ -n "$GUIMODE" ]; then
		echo "PROMPT[overwrite|append]: `echo $1 |sed -e 's,\\\n, ,g'`"
	else
		echo -e $1
		echo $"Press return to append or type \"overwrite\" to overwrite"
	fi
	OVERWRITE="a"
	read a
	if [ "`echo $a |tr A-Z a-z`" = "overwrite" ]; then
		OVERWRITE="o"
	fi
}

cleanup() {
	[ ! -z "$TO_REMOVE" -a "$TO_REMOVE" != "/" ] && echo "rm -rf $TO_REMOVE"
	if [ -z "$KEEP" ]; then
		if [ -z "$DVDPLUS" -o ! -z "$IS_ISO" ]; then 
			for i in $FILES; do
				if [ "`echo $i |cut -c1`" != "-" ]; then
					rm -f $i
				fi
			done
		fi
	fi
}

check_dvdplustool() {
	which growisofs 2>&1 > /dev/null
	if [ "$?" != 0 ]; then
		echo "Couldn't find growisofs in your PATH, aborting"
		exit 1
	fi
}

# Parse arguments
GUIMODE=""
BLANK=""
KEEP=""
DVDPLUS=""
VBITRATE=""
MAXBITRATE=""
AUDIOBITRATE=""
SPEED=""
FORMAT="data"
STANDARD=""
DEVICE="ATAPI:0,0,0"
TMP="/tmp/"
PARAM=""
TO_REMOVE=""
MENCODER=""
UDF=""
# replex is much faster, but also much less common, than transcode
REPLEX="`which replex 2>/dev/null`"

if [ "$1" == "" ]; then
	usage
fi

while [ "`echo $1 |cut -b1`" = "-" ]; do
	case $1 in
	-b)
		# Start blanking right away - maybe we're done by the time
		# we actually write something...
		BLANK=done
		dvdrecord dev=$DEVICE $SPEED blank=fast -v &>/dev/null &
		PARAM="$PARAM -b"
		;;
	-a)
		shift
		ABITRATE="$1"
		ABITRATE_SPECIFIED=1
		PARAM="$PARAM -a $1"
		;;
	-u)
		UDF="-udf"
		;;
	-v)
		shift
		VBITRATE="$1"
		if echo $VBITRATE |grep -q ","; then
			MAXBITRATE=`echo $VBITRATE |sed -e "s%.*,%%"`
			VBITRATE=`echo $VBITRATE |sed -e "s%,.*%%"`
		else
			MAXBITRATE=$(( $VBITRATE + 512 ))
		fi
		PARAM="$PARAM -v $1"
		;;
	-N)
		VBITRATE="0"
		PARAM="$PARAM -N"
		;;
	-d)
		shift
		DEVICE="$1"
		PARAM="$PARAM -d $1"
		;;
	-k)
		KEEP=yes
		PARAM="$PARAM -k"
		;;
	-f|--format)
		shift
		FORMAT=`echo $1 |tr A-Z a-z`
		if ! echo $FORMAT |grep -qE '(data|dvd|audio|mp3|mpeg4|vcd|svcd)'; then
			usage $"Unknown format $1"
		fi
		PARAM="$PARAM -f $FORMAT"
		;;
	-g|--gui)
		GUIMODE=yes
		PARAM="$PARAM -g"
		;;
	-p|--plus)
		check_dvdplustool
		DVDPLUS=yes
		PARAM="$PARAM -p"
		;;
	-s|--standard)
		shift
		STANDARD=`echo $1 |tr A-Z a-z`
		if [ "$STANDARD" != "pal" -a "$STANDARD" != "ntsc" -a "$STANDARD" != "pal352" -a "$STANDARD" != "ntsc352" -a "$STANDARD" != "pal704" -a "$STANDARD" != "ntsc704" ]; then
			usage $"Unknown standard $1"
		fi
		PARAM="$PARAM -s $STANDARD"
		;;
	-S|--speed)
		shift
		SPEED="speed=$1"
		PARAM="$PARAM -S $1"
		;;
	-t|--tmp)
		shift
		TMP="`echo $1/ |sed -e 's,//$,/,'`"
		if [ ! -d "$TMP" ]; then
			mkdir -p "$TMP"
			if [ ! -d "$TMP" ]; then
				usage $"Directory $TMP doesn't exist and can't be created."
				exit 1
			fi
		fi
		PARAM="$PARAM -t $TMP"
		;;
	-M|--mencoder)
		MENCODER="yes"
		PARAM="$PARAM -M"
		;;
	-T|--transcode)
		REPLEX=""
		PARAM="$PARAM -T"
		;;
	*)
		usage $"WARNING: Unknown flag $1"
		;;
	esac
	shift
done

# Some users apparently like passing us whole directories...
# Catch it, and do what they meant.
# (Yes, this is ugly ;) )
for i in "$@"; do
	if [ -d "$i" ]; then
		SCRIPT=`mktemp /tmp/makecdXXXXXX`
		cat >$SCRIPT <<EOF
#!/bin/bash
$0 $PARAM \\
EOF
		for j in "$@"; do
			if [ -d "$j" ]; then
				find "$j" -type f |while read f; do
					[ -d "$f" ] || echo "	\"$f\" \\" >>$SCRIPT
				done
			else
				echo "	\"$j\" \\" >>$SCRIPT
			fi
		done
		cat >>$SCRIPT <<EOF

rm -f $SCRIPT
EOF
		chmod 0700 $SCRIPT
		exec $SCRIPT
	fi
done

# Generate image...
ISO_FILE=`mktemp $TMP/isoXXXXXX`
ISOSIZE=0
# trap "rm -rf $ISO_FILE" `seq 0 31`
case $FORMAT in
data)
	if [ -z "$DVDPLUS" ]; then
		mkisofs $UDF -f -v -J -r -o $ISO_FILE "$@" 2>&1
		FILES="$ISO_FILE"
		ISOSIZE=`ls -l $ISO_FILE |awk '{ print $5; }'`
	else
		FILES="$@"
		ISOSIZE=0
		I=0
		J=$#
		while [ "$I" -lt "$J" ]; do
			files[$I]=$1
			FILESIZE=`du -s "$1" | cut -f 1`
			ISOSIZE=`expr $ISOSIZE + $FILESIZE`
			shift
			I=`expr $I + 1`
		done
	fi
	;;
dvd)
	[ -z "$ABITRATE" ] && ABITRATE="128"
	[ -z "$VBITRATE" ] && VBITRATE="6000"
	[ -z "$MAXBITRATE" ] && MAXBITRATE="8192"
	IFOASPECT="4:3"
	if [ -z "$STANDARD" ]; then
		# Check if we're supposed to resize things, and
		# decide on PAL vs. NTSC
		# (Majority decision w/ frame rates)
		NTSC=0
		NTSC352=0
		NTSC704=0
		PAL=0
		PAL352=0
		PAL704=0
		FULLSIZE=0
		for i in "$@"; do
			LANG=C mplayer -vo null -ao null -frames 0 -identify "$i" 2>/dev/null |grep "^ID" |sed -e '/^ID_FILENAME/ { s/^ID_FILENAME=\(.*\)/ID_FILENAME="\1"/g; }' >$TMP/vinfo
			source $TMP/vinfo
			rm $TMP/vinfo
			[ "$ID_VIDEO_WIDTH" -gt 352 ] && FULLSIZE=1
			if [ "$ID_VIDEO_FPS" = "29.970" -o "$ID_VIDEO_FPS" = "30.000" ]; then
				# NTSC
				if [ "$ID_VIDEO_WIDTH" -le 352 ]; then
					NTSC352=$(( $NTSC352 + 1 ))
				elif [ "$ID_VIDEO_WIDTH" = "704" ]; then
					NTSC704=$(( $NTSC704 + 1 ))
				else
					NTSC=$(( $NTSC + 1 ))
				fi
			else
				# PAL
				if [ "$ID_VIDEO_WIDTH" -le 352 ]; then
					PAL352=$(( $PAL352 + 1 ))
				elif [ "$ID_VIDEO_WIDTH" = "704" ]; then
					PAL704=$(( $PAL704 + 1 ))
				else
					PAL=$(( $PAL + 1 ))
				fi
			fi
		done
		if [ "$FULLSIZE" = "1" ]; then
			# We don't want to lose resolution, so we scale
			# half size movies --- fit them to the best match
			PAL704=$(( $PAL704 + $PAL352 ))
			NTSC704=$(( $NTSC704 + $NTSC352 ))
			PAL352=0
			NTSC352=0
		fi

		STANDARD="pal352"
		STDCOUNT=$PAL352
		if [ $PAL704 -ge $STDCOUNT ]; then STANDARD="pal704"; STDCOUNT=$PAL704; fi
		if [ $PAL -ge $STDCOUNT ]; then STANDARD="pal"; STDCOUNT=$PAL; fi
		if [ $NTSC352 -ge $STDCOUNT ]; then STANDARD="ntsc352"; STDCOUNT=$NTSC352; fi
		if [ $NTSC704 -ge $STDCOUNT ]; then STANDARD="ntsc704"; STDCOUNT=$NTSC704; fi
		if [ $NTSC -ge $STDCOUNT ]; then STANDARD="ntsc"; STDCOUNT=$NTSC; fi
	fi
	DIR=`pwd`

	if [ "`echo $STANDARD |tr A-Z a-z`" = "pal" ]; then
		RESIZE="-Z720x576 -f 25"
		RESIZE_M="scale=720:576"
		WIDTH=720
		HEIGHT=576
	elif [ "`echo $STANDARD |tr A-Z a-z`" = "ntsc" ]; then
		RESIZE="-Z720x480 -f 29.970"
		RESIZE_M="scale=720:480"
		WIDTH=720
		HEIGHT=480
	elif [ "`echo $STANDARD |tr A-Z a-z`" = "pal704" ]; then
		RESIZE="-Z704x576 -f 25"
		RESIZE_M="scale=704:576"
		WIDTH=704
		HEIGHT=576
	elif [ "`echo $STANDARD |tr A-Z a-z`" = "ntsc704" ]; then
		RESIZE="-Z704x480 -f 29.970"
		RESIZE_M="scale=704:480"
		WIDTH=704
		HEIGHT=480
	elif [ "`echo $STANDARD |tr A-Z a-z`" = "pal352" ]; then
		RESIZE="-Z352x288 -f 25"
		RESIZE_M="scale=352:288"
		WIDTH=352
		HEIGHT=288
	elif [ "`echo $STANDARD |tr A-Z a-z`" = "ntsc352" ]; then
		RESIZE="-Z352x240 -f 29.970"
		RESIZE_M="scale=352:240"
		WIDTH=352
		HEIGHT=240
	else
		RESIZE="-Z$STANDARD"
		RESIZE_M=`echo $STANDARD |sed -e 's,x,:,g'`
		WIDTH=`echo $STANDARD |sed -e 's,x.*,,'`
		HEIGHT=`echo $STANDARD |sed -e 's..*x,,'`
	fi
	
	OLDLANG="$LANG"
	export LANG=C # We need to parse the output of other apps
	mkdir $TMP/vobs
	pushd $TMP/vobs
	for i in `seq 1 $#`; do
		FN="track$i.vob"
		INPUT="$1"
		ARGS=""
		[ "`echo $INPUT |cut -b1`" != "/" ] && INPUT="$DIR/$INPUT"
		KEEP_ASR="--keep_asr"
		FILEINFO="`tcprobe -i \"$INPUT\" 2>&1`"
		if echo $INPUT | grep -qE '\.a[0-9]+\.avi$'; then
			# The Archimedis VCR marks the aspect ratio of MPEG-4 files
			# in the filename because normal AVI files don't remember it...
			# Detect and handle those files, adjusting to the closest match.
			# This is greatly suboptimal, but better than nothing
			# (transcode's --import_asr just isn't flexible enough).
			ASPECT=`echo $INPUT | sed -e 's,\.avi$,,;s,.*\.a,,'`
			if [ $ASPECT -le 110 ]; then
				ARGS="--import_asr 1" # <= 1.1:1 -> 1:1
			elif [ $ASPECT -le 155 ]; then
				ARGS="--import_asr 2" # <= 1.55:1 -> 4:3 (1.33:1)
			elif [ $ASPECT -le 199 ]; then
				ARGS="--import_asr 3" # <= 1.99:1 -> 16:9 (1.77:1)
				IFOASPECT="16:9"
			else
				ARGS="--import_asr 4" # >  1.99:1 -> 2.21:1
			fi
		fi
		if echo $FILEINFO |grep -q -E "import frame size:.*4..x(576|480)"; then
			# Weirdo scaled TV must not be rescaled with keep_asr
			# (odd pixel size)
			KEEP_ASR=""
		fi
		MT=""
		if [ -n "$REPLEX" ]; then
			if echo $FILEINFO |grep -q "transport stream"; then
				MT="TS"
			elif echo $FILEINFO |grep -q "program stream"; then
				MT="PS"
				[ `echo "$INPUT" |sed -e 's,.*\.,,g' |tr A-Z a-z` = vob ] && MT="copy"
			elif echo $FILEINFO |grep -q "packetized elementary stream"; then
				MT="PS"
			fi
		fi
		DONE=""
		if [ -n "$MT" -a "$VBITRATE" = "0" ]; then
			if [ "$MT" = "copy" ]; then
				ln "$INPUT" "$FN" || cp -a "$INPUT" "$FN"
			else
				replex -t DVD -o "$FN" -i $MT "$INPUT"
			fi
			if ! test -s "$FN"; then
				MT=""
			else
				DONE=1
				VOBS="$VOBS $FN"
			fi
		fi
		if [ -n "$MENCODER" -a -n "$REPLEX" -a -z "$DONE" ]; then
			LANG=C mplayer -vo null -ao null -frames 1 -identify "$INPUT" 2>&1 |sed -e 's/[`\\!$"]/\\&/g' |sed -e '/^ID_FILENAME/ { s/^ID_FILENAME=\(.*\)/ID_FILENAME="\1"/g; }' |perl -pi -e 's,^(Movie-Aspect is )(.*)( - prescaling to correct movie aspect\.),ID_REAL_ASPECT=\2,' >$TMP/vinfo
			cat $TMP/vinfo |grep "^ID" >$TMP/vinfo.sh
			source $TMP/vinfo.sh
			ID_REAL_ASPECT=$(python -c "print `echo $ID_REAL_ASPECT |sed -e 's,^,int(100*(float(,;s,:,)/float(,;s,\$,),;s,$,)),'`")
			[ "`echo $ID_VIDEO_ASPECT |perl -pi -e 's,\.,,;s,0+,0,g'`" = "0" ] && ID_VIDEO_ASPECT=$ID_REAL_ASPECT
			rm $TMP/vinfo $TMP/vinfo.sh

			RESIZE_M="scale=$WIDTH:-3,expand=$WIDTH:$HEIGHT" # FIXME

			REALASPECT=`python -c "print int(float($ID_VIDEO_ASPECT)*float($ID_VIDEO_HEIGHT)/float($HEIGHT))"`
			if [ "$REALASPECT" -lt 155 ]; then
				IFOASPECT="4:3"
			else
				IFOASPECT="16:9"
			fi
			
			OPTS="vcodec=mpeg2video:acodec=mp2"
			if [ "$VBITRATE" != 0 ]; then
				OPTS="$OPTS:vbitrate=$VBITRATE:abitrate=$ABITRATE"
			fi
			if [ -n "$RESIZE_M" ]; then
				VF="lavcdeint,$RESIZE_M"
			else
				VF="lavcdeint"
			fi
			mencoder -ovc lavc -oac lavc -lavcopts "$OPTS" -vf $VF -o $TMP/tmp.avi "$INPUT"
			replex -t DVD -d 220 -o "$FN" -i AVI $TMP/tmp.avi
			rm $TMP/tmp.avi
			if test -s "$FN"; then
				VOBS="$VOBS $FN"
				MT="done"
			else
				MT=""
			fi
		fi
		if [ -z "$MT" ]; then
			# TODO: -A etc. for AC3, ogg support
			ARGS="$ARGS -N 0x50 -y mpeg,mpeg -V -x mplayer,mplayer -F d -w $VBITRATE --video_max_bitrate $MAXBITRATE -b $ABITRATE"
			if ! transcode -i "$INPUT" $ARGS -o tmp $RESIZE $KEEP_ASR; then
				# Try without --keep_asr
				if ! transcode -i "$INPUT" $ARGS -o tmp $RESIZE; then
					# The stream seems to be broken, and mencoder is less
					# picky. This is UGLY, but works
					ASPECT=`mencoder -oac copy -ovc copy "$INPUT" -o "$TMP/fixedstream.avi" 2>/dev/null |grep aspect |sed -e 's,.*aspect *,,;s,).*,,'`
					if ! echo $ARGS |grep -q import_asr; then
						[ -n "$ASPECT" ] && ARGS="$ARGS --import_asr $ASPECT"
					fi
					if ! transcode -i "$TMP/fixedstream.avi" $ARGS -o tmp $RESIZE --keep_asr; then
						if ! transcode -i "$TMP/fixedstream.avi" $ARGS -o tmp $RESIZE; then
							echo "Is this really a video??" >&2
						fi
					fi
					rm -f "$TMP/fixedstream.avi"
				fi
			fi
			tcmplex -o $FN -i tmp.m2v -p tmp.mpa -m d
			VOBS="$VOBS $FN"
			if [ -z "$KEEP" ]; then
				rm -f tmp.m2v tmp.mpa
			else
				mv -f tmp.m2v track$i.m2v
				mv -f tmp.mpa track$i.mpa
			fi
		fi
		shift
	done
	ifogen --video `echo $STANDARD |perl -pi -e 's,[0-9]+,,'`+${WIDTH}x${HEIGHT}+$IFOASPECT --audio mp2 -o "$TMP/image" $VOBS
	ifogen --toc -o "$TMP/image"
	popd
	[ -z "$KEEP" ] && rm -rf "$TMP/vobs"
	mkisofs -dvd-video -udf -o "$ISO_FILE" "$TMP/image"
	[ -z "$KEEP" ] && rm -rf "$TMP/image"
	export LANG="$OLDLANG"
	FILES="$ISO_FILE"
	ISOSIZE=`ls -l $ISO_FILE |awk '{ print $5; }'`
	IS_ISO="yes"
	;;
vcd|svcd)
	WORK="`mktemp -d $TMP/vcdXXXXXX`"
	VCD_FILES=""
	t=0
	pushd "$WORK"
	for i in "$@"; do
		EXTENSION="`echo $i |sed -e 's,.*\.,,'`"
		case $EXTENSION in
		mpg|mpeg|mp1|mp2)
			dvb-mplex -t `echo $FORMAT |tr a-z A-Z` -o track$t.mpg "$i"
			;;
		avi|dv|divx)
			transcode -V -x mplayer,mplayer -y mpeg,mpeg -o tmp$t -N 0x50 -i "$i"
			tcmplex -o "track$t-temp.mpg" -i tmp$t.m2v -p tmp$t.mpa
			rm -f tmp$t.m2v tmp$t.mpa
			dvb-mplex -t `echo $FORMAT |tr a-z A-Z` -o track$t.mpg track$t-temp.mpg
			rm track$t-temp.mpg
			;;
		esac
		VCD_FILES="$VCD_FILES track$t.mpg"
		t=$(( $t + 1 ))
	done
	if [ "$FORMAT" = "vcd" ]; then
		FORMAT="vcd11"
	fi
	vcdimager -t $FORMAT $VCD_FILES

	# We can't handle bin/cue files ATM --> use cdrdao for now
	# Unfortunately this means we can't write VCD/SVCD format data to
	# DVDs for now.
	# Wait until blanking is done...
	while [ -n "`/sbin/pidof dvdrecord`" ]; do
		sleep 1s
	done
	cdrdao write --device $DEVICE --driver generic-mmc --overburn videocd.cue
	# rm -f videocd.bin videocd.cue
	popd
	rm -f $ISO_FILE
	;;
audio)
	rm $ISO_FILE
	mkdir -p $ISO_FILE
	TRACK=1
	FILES="-audio -pad"
	for i in "$@"; do
		EXTENSION="`echo $i |sed -e 's,.*\.,,'`"
		case $EXTENSION in
		ogg)
			oggdec -o "$ISO_FILE/track-$TRACK.tmp.wav" "$i"
			;;
		mp1|mp2|mp3)
			lame --decode "$i" "$ISO_FILE/track-$TRACK.tmp.wav"
			;;
		avi|mpg|dv)
			# Hmm... A video. Probably we want the soundtrack.
			rm -f stream.yuv # Workaround for transcode bug
			transcode -x mplayer,mplayer -y null,wav -o /dev/null -m "$ISO_FILE/track-$TRACK.tmp.wav" -i "$i"
			;;
		*)
			# Phew... Let's hope the best
			ln "$i" "$ISO_FILE/track-$TRACK.tmp.wav" || cp "$i" "$ISO_FILE/track-$TRACK.tmp.wav"
			;;
		esac
		sox "$ISO_FILE/track-$TRACK.tmp.wav" -r 44100 -c 2 -w "$ISO_FILE/track-$TRACK.wav" resample || mv -f "$ISO_FILE/track-$TRACK.tmp.wav" "$ISO_FILE/track-$TRACK.wav"
		rm -f "$ISO_FILE/track-$TRACK.tmp.wav"
		FILES="$FILES $ISO_FILE/track-$TRACK.wav"
		# FIXME This is not accurate
		ISOSIZE=$(( $ISOSIZE + `ls -l $ISO_FILE/track-$TRACK.wav |awk '{ print $5; }'` ))
		TRACK=$(( $TRACK + 1 ))
	done
	;;
mp3)
	# MP3 doesn't work at every bitrate --> fix
	if [ "$ABITRATE" -le 8 ]; then
		ABITRATE=8
	elif [ "$ABITRATE" -le 16 ]; then
		ABITRATE=16
	elif [ "$ABITRATE" -le 24 ]; then
		ABITRATE=24
	elif [ "$ABITRATE" -le 32 ]; then
		ABITRATE=32
	elif [ "$ABITRATE" -le 40 ]; then
		ABITRATE=40
	elif [ "$ABITRATE" -le 48 ]; then
		ABITRATE=48
	elif [ "$ABITRATE" -le 56 ]; then
		ABITRATE=56
	elif [ "$ABITRATE" -le 64 ]; then
		ABITRATE=64
	elif [ "$ABITRATE" -le 80 ]; then
		ABITRATE=80
	elif [ "$ABITRATE" -le 96 ]; then
		ABITRATE=96
	elif [ "$ABITRATE" -le 112 ]; then
		ABITRATE=112
	elif [ "$ABITRATE" -le 128 ]; then
		ABITRATE=128
	elif [ "$ABITRATE" -le 160 ]; then
		ABITRATE=160
	elif [ "$ABITRATE" -le 192 ]; then
		ABITRATE=192
	elif [ "$ABITRATE" -le 224 ]; then
		ABITRATE=224
	elif [ "$ABITRATE" -le 256 ]; then
		ABITRATE=256
	else
		ABITRATE=320
	fi
	TMP=`mktemp -d $TMP/mp3cdXXXXXX`
	for i in "$@"; do
		EXTENSION="`echo $i |sed -e 's,.*\.,,'`"
		TARGET="`basename \"$i\" |sed -e \"s,$EXTENSION,mp3,\"`"
		case $EXTENSION in
		ogg)
			oggdec -o "$TMP/track-$TRACK.tmp.wav" "$i"
			lame -h -b "$ABITRATE" "$i" "$TMP/$TARGET"
			;;
		mp1|mp2|mp3)
			if [ -z "$ABITRATE_SPECIFIED" ]; then
				ln "$i" "$TMP/$TARGET" || cp "$i" "$TMP/$TARGET"
			else
				lame --decode "$i" "$TMP/$TARGET.wav"
				lame -h -b "$ABITRATE" "$TMP/$TARGET.wav" "$TMP_TARGET"
				rm -f "$TMP/$TARGET.wav"
			fi
			;;
		avi|mpg|dv|ogm)
			# Hmm... A video. Probably we want the soundtrack.
			rm -f stream.yuv # Workaround for transcode bug
			transcode -x mplayer,mplayer -y null,wav -o /dev/null -m "$TMP/$TARGET.wav" -i "$i"
			lame -h -b "$ABITRATE" "$TMP/$TARGET.wav" "$TMP/$TARGET"
			rm -f "$TMP/$TARGET.wav"
			;;
		*)
			# Phew... Let's hope the best
			lame -h -b "$ABITRATE" "$i" "$TMP/$TARGET"
			;;
		esac
	done
	pushd $TMP
	if [ -z "$DVDPLUS" ]; then
		mkisofs $UDF -f -v -J -r -o $ISO_FILE . 2>&1
		popd
		ISOSIZE=`ls -l $ISO_FILE |awk '{ print $5; }'`
		rm -rf $TMP
	else
		FILES=`ls \`pwd\`/*`
		ISOSIZE=0
		LI=$I
		while [ "$LI" -gt "0" ]; do
			LI=`expr $LI - 1`
			FILESIZE=`du -s "${files[$LI]}" | cut -f 1`
			ISOSIZE=`expr $ISOSIZE + $FILESIZE`
		done
		TO_REMOVE="$TMP"
		popd
	fi
	;;
mpeg4)
	TMP=`mktemp -d $TMP/mp4cdXXXXXX`
	for i in "$@"; do
		EXTENSION="`echo $i |sed -e 's,.*\.,,'`"
		TARGET="`basename \"$i\" |sed -e \"s,$EXTENSION,avi,\"`"
		if tcprobe -i "$i" 2>&1 |grep -q DIVX; then
			# This is already MPEG-4...
			ln "$i" "$TMP/$TARGET" || cp -a "$i" "$TMP/$TARGET"
		else
			mencoder "$i" -ovc lavc -lavcopts vcodec=mpeg4:vhq:vqmin=2:vqmax=4:lumi_mask=0.05:dark_mask=0.01 -vop pp=de/lb -oac mp3lame -lameopts vbr=0:aq=0:br=128 -sws 2 -o "$TMP/$TARGET"
		fi
	done
	pushd $TMP
	if [ -z "$DVDPLUS" ]; then
		mkisofs $UDF -f -v -J -r -o $ISO_FILE . 2>&1
		popd
		FILES="$ISO_FILE"
		ISOSIZE=`ls -l $ISO_FILE |awk '{ print $5; }'`
		rm -rf $TMP
	else
		FILES=`ls \`pwd\`/$TARGET`
		ISOSIZE=0
		LI=$I
		while [ "$LI" -gt "0" ]; do
			LI=`expr $LI - 1`
			FILESIZE=`du -s "${files[$LI]}" | cut -f 1`
			ISOSIZE=`expr $ISOSIZE + $FILESIZE`
		done
		TO_REMOVE="$TMP"
		popd
	fi
	;;
esac
if [ -z "$FILES" ]; then
	if [ -e "$ISO_FILE" ]; then
		FILES="-data $ISO_FILE"
		ISOSIZE=`ls -l $ISO_FILE |awk '{ print $5; }'`
	else
		# We can't write VCDs yet, so we left it to cdrdao...
		exit 0
	fi
fi
# Wait until blanking is done...
while [ -n "`/sbin/pidof dvdrecord`" ]; do
	sleep 1s
done
while true; do
	if [ -z "$DVDPLUS" ]; then
		ATIP=`dvdrecord -atip $SPEED dev=$DEVICE 2>&1`
		if echo $ATIP |grep -q "No disk"; then
			eject
			if [ -z "$GUIMODE" ]; then
				prompt $"Please insert a blank disc and press return."
			else
				prompt $"Please insert a blank disc."
			fi
			[ -n "$BLANK" ] && BLANK=yes
		elif echo $ATIP |grep -q "lead out"; then
			# This is a CD-R/CD-RW, not a DVD-R/DVD-RW
			LEADOUT=`echo $ATIP |sed -e "s,.*start of lead out: ,," |awk '{ print $2; }' |sed -e 's,^(,,;s,)$,,;s,:,,;s,/,,'`
			if [ "$LEADOUT" -le 740000 ]; then
				# 640 MB medium
				MAXSIZE=671088640
			elif [ "$LEADOUT" -le 800000 ]; then
				# 700 MB
				MAXSIZE=734003200
			elif [ "$LEADOUT" -le 900000 ]; then
				# 800 MB (?)
				MAXSIZE=838860800
			else
				# 870 MB (?)
				MAXSIZE=912261120
			fi
			if [ "$ISOSIZE" -gt "$MAXSIZE" ]; then
				eject
				SIZE=$(( $ISOSIZE / 1048576 ))
				if [ -z "$GUIMODE" ]; then
					prompt $"This amount of data ($SIZE MB) will not fit on this disc.\nPlease insert a CD-R[W] with more space or a DVD-R[W] and press return."
				else
					prompt $"This amount of data ($SIZE MB) will not fit on this disc.\nPlease insert a CD-R[W] with more space or a DVD-R[W]."
				fi
				[ -n "$BLANK" ] && BLANK=yes
			else
				break
			fi
		else
			# This is a DVD-R/DVD-RW
			if [ "$ISOSIZE" -gt 4700000000 ]; then
				prompt $"Unfortunately this amount of data will not fit on any disc."
				exit 1
			fi
			break
		fi
	else
		# DVD PLUS
		MINFO=`dvd+rw-mediainfo $DEVICE 2>&1`
		if echo $MINFO | grep -q "no media mounted"; then
			eject
			if [ -z "$GUIMODE" ]; then
				prompt $"Please insert a blank disc and press return."
			else
				prompt $"Please insert a blank disc."
			fi
		else
			if [ "$ISOSIZE" -gt 5046586572 ]; then
				prompt $"Unfortunately this amount of data will not fit on any disc."

				exit 1
			fi
			break
		fi
	fi
done

[ "$BLANK" = "yes" ] && [ -z "$DVDPLUS" ] && dvdrecord $SPEED dev=$DEVICE blank=fast -v

if [ -z "$BLANK" ]; then
	while dd if=/dev/scd0 of=/dev/null bs=1k count=1 &>/dev/null; do
		eject
		if yesno $"This CD/DVD is not empty - blank it?"; then
			dvdrecord $SPEED dev=$DEVICE blank=fast -v
		else
			eject
			if [ -z "$GUIMODE" ]; then
				prompt $"Please insert a blank disc and press return."
			else
				prompt $"Please insert a blank disc."
			fi
		fi
	done
fi

while [ -z "$DVDPLUS" ] && ! dvdrecord $SPEED dev=$DEVICE -gui -delay 1 -eject -v -dao $FILES 2>&1; do
	ATIP=`dvdrecord $SPEED -atip dev=$DEVICE 2>&1`
	if echo $ATIP |grep -q "No disk"; then
		eject
		if [ -z "$GUIMODE" ]; then
			prompt $"Please insert a blank disc and press return."
		else
			prompt $"Please insert a blank disc."
		fi
		[ -n "$BLANK" ] && BLANK=yes
	elif echo $ATIP |grep -q "lead out"; then
		# This is a CD-R/CD-RW, not a DVD-R/DVD-RW
		LEADOUT=`echo $ATIP |sed -e "s,.*start of lead out: ,," |awk '{ print $2; }' |sed -e 's,^(,,;s,)$,,;s,:,,;s,/,,'`
		if [ "$LEADOUT" -le 740000 ]; then
			# 640 MB medium
			MAXSIZE=671088640
		elif [ "$LEADOUT" -le 800000 ]; then
			# 700 MB
			MAXSIZE=734003200
		elif [ "$LEADOUT" -le 900000 ]; then
			# 800 MB (?)
			MAXSIZE=838860800
		else
			# 870 MB (?)
			MAXSIZE=912261120
		fi
		if [ "$ISOSIZE" -gt "$MAXSIZE" ]; then
			eject
			SIZE=$(( $ISOSIZE / 1048576 ))
			if [ -z "$GUIMODE" ]; then
				prompt $"This amount of data ($SIZE MB) will not fit on this disc.\nPlease insert a CD-R[W] with more space or a DVD-R[W] and press return."
			else
				prompt $"This amount of data ($SIZE MB) will not fit on this disc.\nPlease insert a CD-R[W] with more space or a DVD-R[W]."
			fi
			[ -n "$BLANK" ] && BLANK=yes
		fi
	else
		# This is a DVD(-R/DVD-RW)
		eject
		if [ -z "$GUIMODE" ]; then
			prompt $"Please insert a blank disc and press return."
		else
			prompt $"Please insert a blank disc."
		fi
		[ -n "$BLANK" ] && BLANK=yes
	fi
	[ "$BLANK" = "yes" ] && dvdrecord $SPEED dev=$DEVICE blank=fast -v
done

if [ ! -z "$DVDPLUS" ]; then
	while true; do
		# XXX
		COMMAND="growisofs"
		if [ "$OVERWRITE" = "a" ]; then
			COMMAND="$COMMAND -M $DEVICE -J -R"
		else
			if [ "$OVERWRITE" = "o" ]; then
				COMMAND="$COMMAND -use-the-force-luke"
			fi
			if [ -z "$IS_ISO" ]; then
				COMMAND="$COMMAND -Z $DEVICE -J -R"
				KEEP="yes"
			else
				COMMAND="$COMMAND -Z $DEVICE=$FILES"
			fi
		fi
		if [ -z "$IS_ISO" ]; then
			echo "Going to execute $COMMAND $FILES"
			OUTPUT=`$COMMAND "$FILES" 2>&1`
		else
			echo "Going to execute $COMMAND"
			OUTPUT=`$COMMAND 2>&1`
		fi
		if [ "$?" != "0" ]; then
			echo $OUTPUT
			MINFO=`dvd+rw-mediainfo $DEVICE 2>&1`
			if echo $MINFO | grep -q "no media mounted"; then
				eject
				if [ -z "$GUIMODE" ]; then
					prompt $"Please insert a blank disc and press return."
				else
					prompt $"Please insert a blank disc."
				fi
			elif echo $OUTPUT | grep -q "already carries isofs"; then
				if [ -z "$IS_ISO" ]; then
					ask_append $"The DVD+RW medium is not empty, what do you want to do with it?"
					continue;
				else
					if [ -z "$GUIMODE" ]; then
						prompt $"The DVD medium is not empty, press return to overwrite it"
					else
						prompt $"The DVD medium is not empty, do you want to overwrite it?"
					fi
					OVERWRITE="o"
					continue
				fi
				if [ -z "$GUIMODE" ]; then
					prompt $"Please insert a blank disc and press return."
				else
					prompt $"Please insert a blank disc."
				fi
			else
				if [ "$ISOSIZE" -gt 5046586572 ]; then
					prompt $"Unfortunately this amount of data will not fit on any disc."
	
					exit 1
				fi
				break
			fi
		else
			echo $OUTPUT
			break
		fi
	done
fi

cleanup
