#! /usr/bin/perl

if ($#ARGV != 0)
{
	print "Syntax: $0 pfad\n";
	exit (1);
}

($path) = @ARGV;
-d $path || die "$path ist ungültig.\n";

# Slash am Pfadende entfernen falls vorhanden
$path =~ s/\/$//;

open (MARKS, "<$path/marks.vdr") || die "Kann $path/marks.vdr nicht öffnen\n";
@marks=<MARKS>;
close(MARKS);

@stat = stat ("$path/index.vdr");
$length = $stat[7];

$buffer = "";
open (INDEX, "<$path/index.vdr");
binmode (INDEX);
open (MARKS, ">$path/marks.vdr");
for ($i = 0; $i <= $#marks; $i++)
{
	$marks[$i] =~ s/\n//;
	($h, $m, $s, $f) = split (/[:.]/, $marks[$i]);
	($f, undef) = split (/ /, $f);
	$frame = ($h * 3600 + $m * 60 + $s)* 25 + $f-1;

	$pos = 8 * $frame;
	sysseek (INDEX, $pos, 0);
	sysread (INDEX, $buffer, 8);
	($offset, $type, $filenumber, $reserved) = unpack ("LCCS", $buffer);

	# erstes I-Frame vor der Startposition finden, die anderen danach
	if ($i == 0)
	{
		while ($type != 1)
		{
			sysseek (INDEX, $pos, 0);
			sysread (INDEX, $buffer, 8);
			($offset, $type, $filenumber, $reserved) = unpack ("LCCS", $buffer);
			$pos -= 8;
		}
	}
	else
	{
		while ($type != 1)
		{
			sysread (INDEX, $buffer, 8);
			($offset, $type, $filenumber, $reserved) = unpack ("LCCS", $buffer);

			# falls Dateiende erreicht wurde ohne ein I-Frame zu finden gehe zum letzten vorhandenen
			if (sysseek (INDEX, 0, 1) == $length)
			{
				while ($type != 1)
				{
					sysseek (INDEX, $pos, 0);
					sysread (INDEX, $buffer, 8);
					($offset, $type, $filenumber, $reserved) = unpack ("LCCS", $buffer);
					$pos -= 8;
				}
			}
		}
	}

	$pos = (sysseek (INDEX, 0, 1)) / 8;
	$f = $pos % 25;
	$pos -= $f;
	$pos /= 25;
	$s = $pos % 60;
	$pos -= $s;
	$pos /= 60;
	$m = $pos % 60;
	$pos -= $m;
	$pos /= 60;
	$h = $pos;

	printf ("%02d:%02d:%02d.%02d\n", $h, $m, $s, $f);
	printf MARKS ("%02d:%02d:%02d.%02d\n", $h, $m, $s, $f);
}

close (INDEX);


