#!/usr/bin/env perl

use strict;
use warnings;

sub usage
{
    $\ = "\n";
    print "\nUsage: $0 [mplayeropts] ifile [px] <pos1> [<pos2> [cut]]\n";

    print "\tFirst args not existing file are added to mplayeropts.";
    print "\tFile position offsets are megabytes, negative from end of file.";
    print "\tIf there is only <pos1>, play 2 mb from that position.";
    print "\tIf there is also <pos2>, play 2 mb from that position (pos2).";
    print "\tWith `cut' write file c-ifile from ifile between pos1 and pos2.";
    print "\tIf there is `px' anywhere after `ifile', ProjectX is used to.";
    print "\tdemux material when testing cut positions...";
    print "";
    exit 1;
}

my @mplayeropts = ( 'mplayer' );

while (defined $ARGV[1] && ! -f $ARGV[0])
{
	push @mplayeropts, shift @ARGV;
}

usage unless (defined $ARGV[1]);

usage unless (-f $ARGV[0]);

my $filename = shift @ARGV;

my @fi = stat($filename);

my @pa;
my $opt;
my ($px, $cut) = (0, 0);

while (@ARGV)
{
    $opt = shift @ARGV;
    $px = 1, next if ($opt eq 'px');
    $cut = 1, next if ($opt eq 'cut');
    push @pa, $opt;
}

if ($cut)
{
    die 'Wrong number of "offsets"', "\n" if (@pa != 2);
    $_ = $pa[0];
}
else { $_ = $pa[$#pa]; } # fixme, check pa here too.

my $seekto;
if (/^[0-9\.]+$/)
{
    $seekto = $_ * 1024 * 1024;
    die "out > !\n" if ($seekto > $fi[7]);
}
elsif (/^-[0-9\.]+$/)
{
    $seekto = $fi[7] - -$_ * 1024 * 1024;
    die "out < !\n" if ($seekto < 0);
}
else { die "Incorrect value: $_\n"; }

$seekto -= ($seekto % 188);

print "seekto: $seekto";

my $len = 2 * 1024 * 1024 - 12; # % 188 = 0
#my $len = 5 * 1024 * 1024 + 64; # % 188 = 0

my $ofname = "stsc-$$.ts";
if ($cut)
{
    $_ = $pa[1];
    $ofname = "c-$filename";
    my $end;
    if (/^[0-9\.]+$/)
    {
	$end = $_ * 1024 * 1024;
    }
    elsif (/^-[0-9\.]+$/)
    {
	$end = $fi[7] - -$_ * 1024 * 1024;
    }
    else { die "Incorrect value: $_\n"; }

    $end -= ($end % 188);
    die "Position $end ($_) before $seekto.\n" if ($end <= $seekto);

    $len = $end - $seekto;
    print ", end: $end, len: $len";
}
elsif (@pa == 2)
{
    $seekto -= $len;
}
print "\n";

open my $ifh, $filename || die "Open: $!\n";

die "Seek: $!\n" unless (seek $ifh, $seekto, 0);

open my $ofd, ">$ofname" || die "Open: $!\n";

END { unlink <stsc-$$*>; }

my $buf;
while ($len > 0)
{
    my $l = read($ifh, $buf, $len > 32768? 32768: $len);
    last if ($l <= 0);
    print $ofd $buf;
    $len -= $l;
}

if (-f "stsc-$$.ts")
{
    my $vfn;
    if ($px)
    {
	exit 1 if system ('projectx-wrapper', "stsc-$$.ts");
	exit 1 if system ('mplex', '-f', '3', '-o', "stsc-$$.mpg",
			  "stsc-$$.m2v", "stsc-$$.mp2");
	$vfn = "stsc-$$.mpg";
    }
    else { $vfn = "stsc-$$.ts"; }

    push @mplayeropts, $vfn;
    system (@mplayeropts);
    unlink('stsc-latest.tmp');
    link($vfn, 'stsc-latest.tmp');

    #print "@mplayeropts\n";
}

