#!/usr/local/bin/perl

# @(#)$Id: mpegit,v 1.3 1999/10/18 03:52:03 twitham Exp $

# Copyright (C) 1998 - 1999 Tim Witham <twitham@pcocd2.intel.com>

# (see the files README and COPYING for more details)

use Getopt::Long;

$usage = "usage: $0 "
    . "[--help | --minute | --ten | --hour | --day] "
    . "<mpg file> <directories or yuv files>\n";

%opt = ();
die $usage unless &GetOptions(\%opt, qw(help minute ten hour day));

print($usage) && exit if $opt{'help'};

print($usage) && exit unless $mpg = shift @ARGV;

$ENV{'PATH'} .= ':/usr/local/bin';

mkdir($tmp = "/tmp/mpegit$$", 0775)
    || die "$0: can't mkdir $tmp: $!\n";
$file = "$tmp/mpeg2encode.par";
chomp($pwd = `pwd`);

while ($_ = shift @ARGV) {
    $_ = "$pwd/$_" unless m!^/!;
    if (-d $_) {
	opendir(DIR, $_) || warn "$0: can't opendir $_: $!\n";
	for $yuv (grep(/\.yuv$/, readdir(DIR))) {
	    push(@yuv, "$_/$yuv");
	}
    } elsif (/\.yuv$/ && -e $_) {
	push(@yuv, $_);
    } else {
	warn "$0: skipping $_\n";
    }
}

for (sort @yuv) {

    next if m!/1998/12/2(3|4|8)/!; # skip non-real work days

    next unless m!/(((((\d\d\d\d/\d\d/\d\d)/\d\d)\d)\d)(\d\d)?)\.yuv$!;
    ($all, $min, $ten, $hour, $day) = ($1, $2, $3, $4, $5);

    $frame{$all} = $_ if !%opt; # note last file in selected time frame
    $frame{$min} = $_ if $opt{'minute'};
    $frame{$ten} = $_ if $opt{'ten'};
    $frame{$hour} = $_ if $opt{'hour'};
    $frame{$day} = $_ if $opt{'day'};
}

$frame = 0;
for (sort keys %frame) {	# link desired frames to numbered sequence
    symlink($frame{$_}, "$tmp/$frame.yuv")
	|| die "$0: can't symlink $tmp/$frame.yuv: $!\n";
    $frame++;
}

if ($frame) {
    open(FILE, ">$file")
	|| die "$0: can't write $file: $!\n";
    print FILE "MPEG
$tmp/%d
-
-
-
$tmp/mpeg2encode.log
1
$frame
0
00:00:00:00
12
3
1
0
320
240
8
3
1152000.0
20
0
1
4
8
1
1
1
5
5
5
320
240
0
0
1 1 1
0 0 0
0 0 0
0 0 0
0 0 0
0
1
0
0
0
0
0
0
0
0
0
2 2 11 11
1 1 3 3
1 1 7 7
1 1 7 7
1 1 3 3
";
    close FILE;
    print "running mpeg2encode on $frame frames\n";
    system 'mpeg2encode', $file, $mpg;
}
system 'rm', '-r', '-f', $tmp if -d $tmp;
