#!/bin/bash
#

MPlayerOutput="/tmp/DVDRipOMatic-TEMP-MPlayer-$RANDOM"
TCProbeOutput="/tmp/DVDRipOMatic-TEMP-TCProbe-$RANDOM"
MPlayerAudioDetectOutput="/tmp/DVDRipOMatic-TEMP-Audio-$RANDOM"

# Optimal amount of bits used to encode
# 1000 pixels in MPEG4. 
# (BitsPerKiloPixel)
OptimalBpkp=220

# Cropping values in pixels of the *unscaled* image.
# BOTH VALUES MUST BE MULTIPLES OF TWO!
HorizontalCrop=0
VerticalCrop=0

# Search for the resolution that yields the best
# bits per kilopixel value. Resolution needs to be
# multiples of 16! 250 bits per kpixel seems to be
# optimal value for MPEG4-like codecs.

FindOptimalOutputResolution ()
{
 # Calculate new Width, Height and Display Aspect based on
 # cropping parameters:
 
 SourceDisplayAspect=$(echo "scale=4; $(echo $DisplayAspect | cut -d ":" -f 1)/$(echo $DisplayAspect | cut -d ":" -f 2)" | bc)

 echo "Aspect: $SourceDisplayAspect"

 TargetHeight=$(echo "$VideoHeight - $VerticalCrop" | bc)
 TargetWidth=$(echo "scale=8; ($VideoWidth - $HorizontalCrop) / $VideoWidth" | bc)
 TargetWidth=$(echo "scale=8; $TargetWidth * $VideoWidth * $SourceDisplayAspect / ($VideoWidth / $VideoHeight)" | bc | cut -d "." -f 1)
 TargetDisplayAspect=$(echo "scale=4; $TargetWidth / $TargetHeight" | bc)

 echo "Image dimensions after cropping: ${TargetWidth}x${TargetHeight} ($TargetDisplayAspect)"

 # Round to nearest multiple of 16
 TargetWidth=$(echo "tmp=$TargetWidth % 16; if (tmp < 8) print (($TargetWidth/16)-1)*16 else print (($TargetWidth/16)+1)*16;" | bc)

 # Try various resolutions from high to low, stop when
 # computed BitsPerKiloPixel is good enough.

 bpkp=0
 OriginalTargetWidth=$TargetWidth

 while [ $TargetWidth -ge 320 ] && [ $bpkp -lt $OptimalBpkp ]
 do

  TargetHeight=$(echo "$TargetWidth / $TargetDisplayAspect" | bc)

  # Round to nearest multiple of 16
  TargetHeight=$(echo "tmp=$TargetHeight % 16; if (tmp < 8) print $TargetHeight - ($TargetHeight % 16) else print (($TargetHeight/16)+1)*16;" | bc)

  # Compute number of bits per kilopixel
  bpkp=$(echo "( $VideoKBitsPerSecond * 1024 * 1000) / ( $TargetWidth * $TargetHeight * $FramesPerSecond )" | bc)

  # Try smaller width
  TargetWidth=$[$TargetWidth - 16]  

 done

 TargetWidth=$[$TargetWidth + 16]

 echo "Found optimal resolution of ${TargetWidth}x${TargetHeight}, $(echo "scale=3; $bpkp / 1000" | bc) bpp."

 if [ $TargetWidth ==  $OriginalTargetWidth ] && [ $bpkp -ge $OptimalBpkp ]; then
  echo "The selected target size might be unnecessarily large."
  echo "Please try using a smaller target size."
  echo "*exaggeration*"
 fi

 if [ $TargetWidth == 320 ] && [ $bpkp -lt $OptimalBpkp ]; then
  echo "The selected target size is insufficient to encode the video with good quality."
  echo "Consider choosing a larger target size."
  echo "*insufficiency*"
 fi
}

# Calculates the bitrates for each 700 MB part of a multi-disk
# DVD rip, based on the scenes where the splitting is done.

CalcDiskBitrates ()

{

 # Compute playing time of chapters that will be on disk 1.

 TimeIndex=$(cat "$TCProbeOutput" | grep -E Chapter\ [0-9]{1,\} | tail -n $[$NumChapters - $SplitPointOne] | head -n 1 | grep -E -o [0-9]{1,\}:[0-9]{1,\}:[0-9]{1,\}.[0-9]{1,\})

 Hours=$(echo "$TimeIndex" | cut -d : -f 1)
 Minutes=$(echo "$TimeIndex" | cut -d : -f 2)
 Seconds=$(echo "$TimeIndex" | cut -d : -f 3)

 Time1=$(echo "scale=3; $Hours * 3600 + $Minutes * 60 + $Seconds" | bc | cut -d . -f 1)

 echo "Disk one length is $Time1 seconds."
 echo "Disk1BitRate=$(( (700 * 1024 * 8) / $Time1 ))"

 if [ $SplitPointTwo == $NumChapters ]; then

   # We have only one possible split point.

   echo "Disk2BitRate=$(( (700 * 1024 * 8) / ( $PlayingTime - $Time1) ))" 

 else

   # We have two possible split points.
   # Compute playing time of chapters that will be on disk 2.

   TimeIndex=$(cat "$TCProbeOutput" | grep -E Chapter\ [0-9]{1,\} | tail -n $[$NumChapters - $SplitPointTwo] | head -n 1 | grep -E -o [0-9]{1,\}:[0-9]{1,\}:[0-9]{1,\}.[0-9]{1,\})

   Hours=$(echo "$TimeIndex" | cut -d : -f 1)
   Minutes=$(echo "$TimeIndex" | cut -d : -f 2)
   Seconds=$(echo "$TimeIndex" | cut -d : -f 3)
 
   Time=$(echo "scale=3; $Hours * 3600 + $Minutes * 60 + $Seconds" | bc | cut -d . -f 1)
   Time2=$(( $Time - $Time1 ))
 
   echo "Disk two length is $Time2 seconds."
   echo "Disk2BitRate=$(( (700 * 1024 * 8) / $Time2 ))" 
   echo "Disk3BitRate=$(( (700 * 1024 * 8) / ( $PlayingTime - $Time1 - $Time2 ) ))" 
 
 fi
}

# Find bitrate of title $1 audio language $2

# WE MAY WANT TO IMPROVE THIS MY USING FFMPEG
#
# SELECTING AUDIO TRACK BY LANGUAGE IS A PROBLEM. THERE
# MAY BE SEVERAL STREAMS WITH SAME LANGUAGE (AC3/DTS)

DetectAudioBitrate ()
{
  # Have MPlayer play the requested title and soundtrack.
  # Catch the output.

 if [ -n "$(echo "$2" | grep -E [0-9]{1,\})" ]; then

   mplayer -v 2 dvd://$1 -aid $2 -dvd-device "$DVDDevice" -frames 0 -vo null -ao null < /dev/null > "$MPlayerAudioDetectOutput" 2>&1

 else

   mplayer -v 2 dvd://$1 -alang $2 -dvd-device "$DVDDevice" -frames 0 -vo null -ao null < /dev/null > "$MPlayerAudioDetectOutput" 2>&1

 fi

 if [ -n "$(cat "$MPlayerAudioDetectOutput" | grep -E ^AC3:)" ]; then

   # The soundtrack played was AC3.
   # Find the bitrate.

   DetectedAudioType="AC3"

   DetectedAudioBitrate=$(cat "$MPlayerAudioDetectOutput" | grep -E ^AC3: \
                           | grep -o -E [0-9]{1,\}[.,][0-9]?\ kbit/s \
                           | sed 's/,/./' | sed 's/kbit\/s/ /' | cut -d "." -f 1 | bc)


 elif [ -n "$(cat "$MPlayerAudioDetectOutput" | grep -E "(DTS)")" ]; then

   # The soundtrack played was DTS.
   # Find the bitrate.

   DetectedAudioType="DTS"

   DetectedAudioBitrate=$(cat "$MPlayerAudioDetectOutput" | grep -E ^AUDIO: \
                           | grep -o -E [0-9]{1,\}[.,][0-9]?\ kbit | sed 's/,/./' \
                           | sed 's/kbit/ /' | cut -d "." -f 1 | bc)

 
 # FIX DETECTION OF MPEG AUDIO (JAN AKKERMAN RECORDING)

 elif [ -n "$(cat "$MPlayerAudioDetectOutput" | grep -E "audio format: mpeg1")" ]; then


   # The soundtrack played was MPEG Audio.
   # Find the bitrate.

   DetectedAudioType="MP2"

   DetectedAudioBitrate=$(cat "$MPlayerAudioDetectOutput" | grep -E ^AUDIO: \
                           | grep -o -E [0-9]{1,\}[.,][0-9]?\ kbit | sed 's/,/./' \
                           | sed 's/kbit/ /' | cut -d "." -f 1 | bc)


 else

   DetectedAudioType=""
   DetectedAudioBitrate=""

 fi

 # No audio streams found?
 if [ -z "$DetectedAudioBitrate" ]; then
   DetectedAudioBitrate="0"
   DetectedAudioType=""
 fi

 rm -f "$MPlayerAudioDetectOutput"

}

# scan DVD title number $1

ScanDVDTitle ()
{

 mplayer -v 2 dvd://$1 -identify -dvd-device "$DVDDevice" -frames 1 -vo yuv4mpeg -ao null > "$MPlayerOutput" 2>&1

 tcprobe -i "$DVDDevice" -T $1 > "$TCProbeOutput" 2>&1

 if [ ! "$?" -eq 0 ]; then
  echo "ERROR: Transcode was unable to read from DVD device at $DVDDevice!"
  kdialog -error "Transcode was unable to read from DVD device at $DVDDevice.\n\nPlease check if $DVDDevice exists, and if you have permission to read from it. Also check that you your Transcode version had support for reading DVD disks."
  exit -1
 fi


 PlayingTime=$(cat "$TCProbeOutput" | grep "playback time" | grep -E -o [0-9]{1,\}\ sec | awk '{print $1}')
 FramesPerSecond=$(cat "$MPlayerOutput" | grep "ID_VIDEO_FPS=" | cut -d = -f 2 | cut -d . -f 1 | cut -d , -f 1)
 NumChapters=$(cat "$MPlayerOutput" | grep "ID_DVD_TITLE_$1_CHAPTERS" | cut -d = -f 2 | cut -d . -f 1 | cut -d , -f 1)

 echo -e "Title[$1]PlayingTime\t$PlayingTime"
 echo -e "Title[$1]FrameRate\t$FramesPerSecond"
 echo -e "Title[$1]NumChapters\t$NumChapters"
 echo -e "Title[$1]VideoBitrate\t$[ $(cat "$MPlayerOutput" | grep "ID_VIDEO_BITRATE=" | cut -d = -f 2 | cut -d . -f 1 | cut -d , -f 1) / 1000]"
 
 # Detect video standard and resolution
 #VideoProperties=`cat "$TCProbeOutput" | grep ^\(dvd_reader.c\) | grep -E pal\|ntsc\|' 16:9 '\|' 4:3 '\|film\|video`
 
# if [ -z "$VideoProperties" ]; then
#  echo "ERROR - Unable to determine video properties!!"
#  return 1
# fi 

 VideoWidth=$(cat "$MPlayerOutput" | grep "ID_VIDEO_WIDTH=" | cut -d = -f 2)
 VideoHeight=$(cat "$MPlayerOutput" | grep "ID_VIDEO_HEIGHT=" | cut -d = -f 2)

 if [ $VideoHeight -eq 576 ] || [ $VideoHeight -eq 288 ]; then

  VideoStandard="pal"

 else

  VideoStandard="ntsc"

 fi

 InterlaceTypeString=$(head -n 1 stream.yuv | awk '{print $5}')

 rm -f stream.yuv

 if [ $InterlaceTypeString == "Ip" ]; then

  VideoType="film"

 else

  VideoType="video"

 fi

 DisplayAspect=$(cat "$TCProbeOutput" | grep ^\(dvd_reader.c\) | grep -o -E 16:9\|4:3 | tail -n 1)
 
 # Now find the ideal points to split the movie into
 # two or three files.
 # 
 # Fails when the first chapter is longer than 1/3 or 1/2 of 
 # total playing time.
 # Fails when the last scene starts before 2/3 or 1/2 of the
 # total playing time.
 
 SplitPointFound="false"
 FirstSplitPointFound="false"
 SecondSplitPointFound="false"

 Time=0
 PreviousTime=0

 for ((Chapter=1; Chapter <= $[$NumChapters - 1] ; Chapter++))
 do
   TimeIndex=`cat "$TCProbeOutput" | grep -E Chapter\ [0-9]{1,\} | tail -n $[$NumChapters - $Chapter] | head -n 1 | grep -E -o [0-9]{1,\}:[0-9]{1,\}:[0-9]{1,\}.[0-9]{1,\}`
   
   Hours=`echo "$TimeIndex" | cut -d : -f 1`
   Minutes=`echo "$TimeIndex" | cut -d : -f 2`
   Seconds=`echo "$TimeIndex" | cut -d : -f 3`
   PreviousTime=$Time
   Time=`echo "scale=3; $Hours * 3600 + $Minutes * 60 + $Seconds" | bc | cut -d . -f 1`
   
   echo -e "Title[$1]Chapter${Chapter}Time\t$Time"
   
   if [ $Time -ge $[$PlayingTime / 2] ] && [ $SplitPointFound == "false" ]; then

     DistanceOne=$[ $[$PlayingTime / 2] - $PreviousTime]
     DistanceTwo=$[ $Time - $[$PlayingTime / 2] ]
     
     if [ $DistanceOne -lt $DistanceTwo  ]; then
       SplitPoint=$(( $Chapter - 1))
       echo -e "Title[$1]TwoDiskLength1\t$PreviousTime"
       echo -e "Title[$1]TwoDiskLength2\t$(($PlayingTime - $PreviousTime ))"
     else
       SplitPoint=$Chapter
       echo -e "Title[$1]TwoDiskLength1\t$Time"
       echo -e "Title[$1]TwoDiskLength2\t$(($PlayingTime - $Time ))"
     fi
   
     echo -e "Title[$1]TwoDiskSplitPoint\t$SplitPoint"
     SplitPointFound="true"
   fi

   if [ $Time -ge $[$PlayingTime / 3] ] && [ $FirstSplitPointFound == "false" ]; then

     DistanceOne=$[ $[$PlayingTime / 2] - $PreviousTime]
     DistanceTwo=$[ $Time - $[$PlayingTime / 2] ]
     
     if [ $DistanceOne -lt $DistanceTwo  ]; then
       SplitPoint=$(( $Chapter - 1))
       ThreeDiskLength1=$PreviousTime
       echo -e "Title[$1]ThreeDiskLength1\t$PreviousTime"
     else
       SplitPoint=$Chapter
       ThreeDiskLength1=$Time
       echo -e "Title[$1]ThreeDiskLength1\t$Time"
     fi
   
     echo -e "Title[$1]ThreeDiskSplitPoint1\t$SplitPoint"
     FirstSplitPointFound="true"
   fi
   
   if [ $Time -ge $[ ($PlayingTime * 2) / 3] ] && [ $SecondSplitPointFound == "false" ]; then

     DistanceOne=$[ $[$PlayingTime / 2] - $PreviousTime]
     DistanceTwo=$[ $Time - $[$PlayingTime / 2] ]
     
     if [ $DistanceOne -lt $DistanceTwo  ]; then
       SplitPoint=$(( $Chapter - 1))
       echo -e "Title[$1]ThreeDiskLength2\t$(($PreviousTime - $ThreeDiskLength1))"
       echo -e "Title[$1]ThreeDiskLength3\t$(($PlayingTime - $PreviousTime ))"
     else
       SplitPoint=$Chapter
       echo -e "Title[$1]ThreeDiskLength2\t$(($Time - $ThreeDiskLength1))"
       echo -e "Title[$1]ThreeDiskLength3\t$(($PlayingTime - $Time ))"
     fi
   
     echo -e "Title[$1]ThreeDiskSplitPoint2\t$SplitPoint"
     SecondSplitPointFound="true"
   fi
         
 done 

 # Try to guess the exact type of video.
 # Possible types are:
 
 # 1: Progressive NTSC Film
 # 2: Telecined NTSC Film
 # 3: Interlaced NTSC Video
 # 4: Progressive PAL Film
 # 5: Interlaced PAL Video
 # 6: Mixed progressive and telecined NTSC Film
 # 7: Unknown
 
 if [ $VideoStandard == "ntsc" ]; then
   
  # Check if the stream contains FPS switches during the first 100 seconds
  NumFPSChanges=$(mplayer dvd://$1 -benchmark -vo null -nosound -frames 2500 2>&1 < /dev/null | grep "switching framerate" | wc -l)
   
  if [ $NumFPSChanges -ge 1 ]; then
   VideoExactType=6
  else
   if [ $VideoType == "film" ]; then
    VideoExactType=1
   else
     VideoExactType=3
   fi
  fi
 elif [ $VideoStandard == "pal" ]; then
  if [ $VideoType == "film" ]; then
   VideoExactType=4
  else
   VideoExactType=5
  fi
 else
  VideoType=6
 fi
 
 echo -e "Title[$1]VideoStandard\t$VideoStandard"
 echo -e "Title[$1]VideoType\t$VideoType"
 echo -e "Title[$1]VideoExactType\t$VideoExactType"
 echo -e "Title[$1]VideoXRes\t$VideoWidth"
 echo -e "Title[$1]VideoYRes\t$VideoHeight"
 echo -e "Title[$1]DisplayAspect\t$DisplayAspect"
 
 # Scan audio streams:
 
 NumAudioStreams=$(cat "$MPlayerOutput" | grep "\[open\] audio stream" | wc -l)

 # Not all audio streams reported by MPlayer may actually exist.
 # Count which streams really exist.

 NumDetectedAudioStreams=0


 for ((Stream=1; Stream <= $NumAudioStreams ; Stream++))
 do

   if [ $NumDetectedAudioStreams -ge $NumAudioStreams ]; then
     break;
   fi

   StreamDescription=`cat "$MPlayerOutput" | grep "\[open\] audio stream" | tail -n $[$NumAudioStreams - $Stream + 1] | head -n 1`

   if [ -z "$StreamDescription" ]; then
     break;
   fi


   AudioLanguage=`echo $StreamDescription | grep -E -o language:\ [a-z]{2} | awk '{print $2}'`
   
   if [ `echo "$StreamDescription" | grep "5.1" | wc -l` -ge 1 ]; then
     AudioChannels=6
   elif [ `echo "$StreamDescription" | grep "stereo" | wc -l` -ge 1 ]; then
     AudioChannels=2
   elif [ `echo "$StreamDescription" | grep "mono" | wc -l` -ge 1 ]; then
     AudioChannels=1
   else
     AudioChannels=6
   fi
   
   StreamID=`echo $StreamDescription | grep -E -o aid:\ [0-9]{1,\} | grep -E -o [0-9]{1,\}`

   # Now detect the audio bitrate of each stream.
   # If stream does not exist, it will be skipped.

   DetectAudioBitrate $1 $StreamID

   if [ $DetectedAudioBitrate -ne 0 ]; then

     if [ -z "$DetectedAudioType" ]; then
       DetectedAudioType="unknown"
     fi

     AudioType=$DetectedAudioType
     AudioBitrate=$DetectedAudioBitrate

     NumDetectedAudioStreams=$[ $NumDetectedAudioStreams + 1 ]

     echo -e "Title[$1]AudioStream[$NumDetectedAudioStreams]Language\t$AudioLanguage"
     echo -e "Title[$1]AudioStream[$NumDetectedAudioStreams]Channels\t$AudioChannels"
     echo -e "Title[$1]AudioStream[$NumDetectedAudioStreams]Type\t$AudioType"
     echo -e "Title[$1]AudioStream[$NumDetectedAudioStreams]Bitrate\t$AudioBitrate"
     echo -e "Title[$1]AudioStream[$NumDetectedAudioStreams]StreamID\t$StreamID"

     if [ $AudioChannels == 1 ]; then
      PrettyDescription="Mono"
     elif [ $AudioChannels == 2 ]; then
      PrettyDescription="Stereo"
     else
      PrettyDescription="$AudioType Surround"
     fi

     if [ $AudioLanguage == "unknown" ]; then
      PrettyDescription="$PrettyDescription, Unknown Language"
     else
       PrettyDescription="$PrettyDescription ($AudioLanguage)"
     fi

     echo -e "Title[$1]AudioStream[$NumDetectedAudioStreams]Description\t$PrettyDescription"

   fi

 done

 echo -e "Title[$1]NumAudioStreams\t$NumDetectedAudioStreams"

 # Scan subtitle streams:
 
 NumSubtitleStreams=$(cat "$MPlayerOutput" | grep "ID_SUBTITLE_ID=" | wc -l)
 echo -e "Title[$1]NumSubtitleStreams\t$NumSubtitleStreams"

 for ((Stream=0; Stream < $NumSubtitleStreams ; Stream++))
 do
  SubtitleLanguage=$(cat "$MPlayerOutput" | grep "ID_SID_${Stream}_LANG=" | cut -d = -f 2)

  if [ -z "$SubtitleLanguage" ]; then
    SubtitleLanguage="??"
  fi

  echo -e "Title[$1]SubtitleLanguage[$[$Stream + 1]]\t$SubtitleLanguage"
 done
}

ScanDVD ()
{

 mplayer -dvd-device "$DVDDevice" -identify -vo null -ao null -frames 0 dvd://0 > "$MPlayerOutput" 2>&1

 if [ -n "$(cat "$MPlayerOutput" | grep ID_DVD_TITLES)" ]; then

   NumTitles=$(cat "$MPlayerOutput" | grep ID_DVD_TITLES | cut -d = -f 2)
   echo "DVD contains $NumTitles titles."

   MainTitle=1
   LongestPlayingTime=0
   for ((Title=1; Title <= $NumTitles ; Title++))
   do
     PlayingTime=$(tcprobe -i "$DVDDevice" -T $Title 2>&1 | grep "playback time" | grep -E -o [0-9]{1,\}\ sec | awk '{print $1}')

     if [ $PlayingTime -ge $LongestPlayingTime ]; then
       LongestPlayingTime=$PlayingTime
       MainTitle=$Title
     fi

     echo "Title[$Title]PlayingTime=$PlayingTime"

   done

   echo "MainTitle=$MainTitle"

 else

   echo "ERROR: Cannot read from DVD device at $DVDDevice"
   kdialog -error "Unable to read from DVD device at $DVDDevice.\n\nPlease check if $DVDDevice exists, and if you have permission to read from it. Also check that you have the required libraries installed for playing DVD disks."
   exit -1

 fi
}


if [ -z "$1" ]; then

 echo
 echo USAGE: DVDScan -scan-dvd path-to-dvd
 echo USAGE: DVDScan -scan-title title path-to-dvd
 echo USAGE: DVDScan -calc-target-resolution title targetbitrate cropx cropy qualitycorrection path-to-dvd
 echo USAGE: DVDScan -calc-disk-bitrates title numdisks splitpoint1 splitpoint2 path-to-dvd
 echo
 echo -e "path-to-dvd:\t\t *Optional*, the path to the DVD filestructure (/dev/dvd)"
 echo -e "title:\t\t\t The number of the title to use, starting from 1."
 echo -e "targetbitrate:\t\t The bitrate of the final, ripped videostream."
 echo -e "cropx:\t\t How many pixels to cut off the image horizontally."
 echo -e "cropy:\t\t How many pixels to cut off the image vertically."
 echo -e "qualitycorrection:\t Specify +1 for heavy action movies, -1 for quiet movies,"
 echo -e "\t\t\t 0 otherwise."
 exit -1

fi

if [ "$1" == "-scan-dvd" ]; then
 
 if [ -z "$2" ]; then
  DVDDevice=/dev/dvd
 else
  DVDDevice="$2"
 fi 
 
 ScanDVD
 rm -f "$TCProbeOutput"
 rm -f "$MPlayerOutput"
 exit 0
fi

if [ "$1" == "-scan-title" ]; then
 
 if [ -z "$3" ]; then
  DVDDevice=/dev/dvd
 else
  DVDDevice="$3"
 fi 
 
 ScanDVDTitle $2 
 rm -f "$TCProbeOutput"
 rm -f "$MPlayerOutput"
 exit 0
fi

if [ "$1" == "-calc-target-resolution" ]; then
 
 if [ -z "$7" ]; then
  DVDDevice=/dev/dvd
 else
  DVDDevice="$7"
 fi 

 ScanDVDTitle $2
 VideoKBitsPerSecond=$3
 HorizontalCrop=$4
 
 if [ $[ $HorizontalCrop % 4 ] -ne 0 ]; then
   HorizontalCrop=$[ ( ( $HorizontalCrop / 4 ) + 1 ) * 4 ] 
 fi
 if [ $[ $VerticalCrop % 8 ] -ne 0 ]; then
   VerticalCrop=$[ ( ( $VerticalCrop / 8 ) + 1 ) * 8 ] 
 fi
 
 VerticalCrop=$5
 OptimalBpkp=`echo "$OptimalBpkp + ( $6 * 30 )" | bc`
 echo "Corrected Bpkp: $OptimalBpkp" 
 FindOptimalOutputResolution
fi

if [ "$1" == "-calc-disk-bitrates" ]; then
 
 if [ -z "$6" ]; then
  DVDDevice=/dev/dvd
 else
  DVDDevice="$6"
 fi 

 ScanDVDTitle $2
 NumDisks=$3
 SplitPointOne=$4
 SplitPointTwo=$5
 
 CalcDiskBitrates
fi

rm -f "$TCProbeOutput"
rm -f "$MPlayerOutput"
rm -f "$MPlayerAudioDetectOutput"