#!/usr/bin/perl

#
# file : ctm2show.pl
# Brief : cut in several show files a ctm file 
#           put new seg in output dir
#           Create a list of seg for each show
#

use strict;
use warnings;

my $ctmfile;
my $segfile;
my $outputdir;

if($#ARGV == 2)
{
    $ctmfile=$ARGV[0];
    $segfile=$ARGV[1];
    $outputdir=$ARGV[2];
}
else
{
    die "BAD USAGE : ctm2show.pl <ctm file> <seg show file> <output dir>";
}

## Check files and directory
open(CTMFILE,'<', $ctmfile) or die "can't open $ctmfile file $!";
open(SEGFILE,'<', $segfile) or die "can't open $segfile file $!";
if(!-d $outputdir){ die "can't open $outputdir directory";}
my $FILEOUTPUT=0;
my $show=0;
my $oldctmline="";

while(<SEGFILE>)
{
    # new show
    if($_ =~ m/=+/)
    {
        # close file open new one
        close(FILEOUTPUT);
        close(FILESHOWOUT);
        if(eof(SEGFILE)){last;}
        $show++;
        open(FILEOUTPUT,'>', $outputdir."/show_".$show.".ctm") or die "can't open file $!";
        open(FILESHOWOUT,'>', $outputdir."/show_".$show.".lst") or die "can't open file $!";
        next;
    }
    chomp($_);
    my @segline=split(/-/,$_);

    while(<CTMFILE>)
    {
        my $ctmline=$_;
        my @ctminfo=split(/ /,$_);
        my @basename=split(/#/,$ctminfo[0]);
        my @timecode=split(/:/,$basename[1]);

        if($timecode[0] >= $segline[0] && ($timecode[0]+$timecode[1]) <= $segline[1])
        {
            print FILEOUTPUT $ctmline;
            if($oldctmline ne $ctminfo[0])
            {
                print FILESHOWOUT "$ctminfo[0]\n";       
                $oldctmline=$ctminfo[0];
            }
        }
        else
        {
            seek(CTMFILE, -length($ctmline), 1);
            last;
        }
    }
}
close(CTMFILE);
close(SEGFILE);
close(FILEOUTPUT);
close(FILESHOWOUT);

