#!/usr/bin/perl

#usage: vobcreateProgressControl.pl filename dcopTarget

#parse output of dvdauthor to get current frame that is being processed
#pass back current percentage done value to my progress bar widget.

$filename=$ARGV[0];
$dcopTarget=$ARGV[1];
$currentProgress=-1;
$progress=0;

$startTime=time;
$currentTime=$startTime;
$estimateRemain=0;
$estimateRemainText="??h:??m:??s";

if (`ls -gok $filename` =~ /^.+[rwx-]{6} +\d+ +(\d+)/) {
	$filesize = int($1/(1024))
}

{
	#output from dvdauthor uses chr 13 to seperate progress updates

	#  *** reset progress bar to 0 ***
	local $/ =chr(13);
	while (<STDIN>) {
		if (/STAT: VOBU.+ (\d+)MB/) {
			$progress = int (($1 / $filesize) * 200);
			if ($progress != $currentProgress) {
				$currentProgress = $progress;
				$currentTime = time - $startTime;
				if ($currentProgress != 0) {
					$estimateRemain = int ($currentTime/$currentProgress * (200-$currentProgress));
					$hrs = int($estimateRemain / (60 * 60));
					$mins = int(($estimateRemain - $hrs*60*60)/(60));
					$secs = int($estimateRemain - ($hrs*60*60) - ($mins*60));
					$estimateRemainText = sprintf('%1$uh:%2$.2um:%3$.2us', $hrs, $mins, $secs)
				}
				system "dcop $dcopTarget KommanderIf setText \"progressConvert\" \"$currentProgress\"";
				system "dcop $dcopTarget KommanderIf setText \"status\" \"  Processing:  (step 3 of 5) Creating VOBS... ETA: $estimateRemainText\""
			}
		}

		if (/fixing/) {
			last
		}
	}

	system "dcop $dcopTarget KommanderIf setText \"progressConvert\" \"200\"";

	#*** set status bar to message saying fixing VOBs ***


	$startTime=time;
	$currentTime=$startTime;
	$estimateRemain=0;
	$estimateRemainText="??h:??m:??s";
	system "dcop $dcopTarget KommanderIf setText \"status\" \"  Processing:  (step 4 of 5) Fixing VOBs... ETA: $estimateRemainText\"";

	system "dcop $dcopTarget KommanderIf setText \"progressConvert\" \"0\"";

	while (<STDIN>) {
		chop;
		if(/fixing.+ (\d+)%/) {
			$currentProgress = $1 * 2;
			$currentTime = time - $startTime;
			if ($currentProgress != 0) {
				$estimateRemain = int ($currentTime/$currentProgress * (200-$currentProgress));
				$hrs = int($estimateRemain / (60 * 60));
				$mins = int(($estimateRemain - $hrs*60*60)/(60));
				$secs = int($estimateRemain - ($hrs*60*60) - ($mins*60));
				$estimateRemainText = sprintf('%1$uh:%2$.2um:%3$.2us', $hrs, $mins, $secs)
			}

			system "dcop $dcopTarget KommanderIf setText \"status\" \"  Processing:  (step 4 of 5) Fixing VOBs... ETA: $estimateRemainText\"";
			system "dcop $dcopTarget KommanderIf setText \"progressConvert\" \"$currentProgress\""
		}
	}
	system "dcop $dcopTarget KommanderIf setText \"progressConvert\" \"200\""
}
