#!/usr/local/bin/perl5
#  Edit a .ra Audio File
#
require "cgi-lib.pl"; # Public Domain library to read form data
#
$statusofread =  &ReadParse(*formdata); # read data in associate array formdata
#
if( $statusofread )     { # If $statusofread nonzero, data read OK
        $rafile = $formdata{"filename"}; # The input ra file
        $radirectory = $formdata{"radirectoryname"}; # The input/output ra directory
        $ramdirectory = $formdata{"ramdirectoryname"}; # The input/output RAM directory
        $realaudioserver = $formdata{"realaudioserver"}; # The server for real audio
	$realaudiodirectory = $formdata{"realaudiodirectory"}; # The input/output directory pointed to by RAM file
	$commands = $formdata{"hiddencommands"}; # The Commands
}
else    { # Error Found!
	&dataerror('System Error');
}
#
&dataerror('No Audiofile defined')	unless(defined($rafile));
&dataerror('No Audiofile defined')	unless($rafile);
&dataerror('No Audio Directory defined')	unless(defined($radirectory));
&dataerror('No Audio Directory defined')	unless($radirectory);
&dataerror('No Events to Process')	unless(defined($commands));
&dataerror('No Events to Process')	unless($commands);
&dataerror("Illegal $radirectory Audio Directory")	unless(-e $radirectory );
$radirectory .= '/' unless( $radirectory =~ m%/$% );
$absrafile = $radirectory . $rafile;
&dataerror("Illegal $absrafile Real audio Input File")	 unless(-e $absrafile);
&dataerror("Cannot write $absrafile Real audio Input File")   unless(-w $absrafile);
&dataerror("Backup Error in $absrafile Real audio Input File")   unless(&backupfile($absrafile));
#
if( defined($realaudiodirectory) && ($realaudiodirectory ne '') )       {
        $realaudiodirectory .= '/' unless( $realaudiodirectory =~ m%/$% );
        $absrealaudiofile = $realaudiodirectory . $rafile;
	if( -e $absrealaudiofile )	{
		&dataerror("Cannot write $absrealaudiofile Real audio Input File")   unless(-w $absrealaudiofile);
	}
	else	{
		&dataerror("Cannot write $realaudiodirectory Real audio Directory")	unless(-w $realaudiodirectory);
	}
}
#
if( defined($ramdirectory) && ($ramdirectory ne '') )       {
	$ramdirectory .= '/' unless( $ramdirectory =~ m%/$% );
	$ramfile = $ramdirectory  . $rafile .'m';
	if( -e $ramfile )	{
		&dataerror("Cannot write $ramfile RAM File ")   unless(-w $ramfile);
	}
	else    {
		&dataerror("Cannot write $ramdirectory RAM directory")	unless(-w $ramdirectory);
	}
	&dataerror("No RAM Server") unless( defined($realaudioserver) && ($realaudioserver ne '') );
	$realaudioserver .= '/' unless( $realaudioserver =~ m%/$% );
	$realaudioserverurl = $realaudioserver . $rafile ;
}
#
$raxfile   = "tmp/raxfile";
system("/bin/rm $raxfile");
system("/usr/npac/bin/rax -i $absrafile > $raxfile");
$endtime=0;
open(RAXFILE,"<$raxfile") || &dataerror("Error in Opening $raxfile");
while( $line= <RAXFILE> )	{
	next unless($line =~ m%Length%);
	$line =~ s/^\s*//;
	$line =~ s/\s*$//;
	@raxfields = split(/\s+/,$line);
	$endtime = 60*$raxfields[1] + $raxfields[3];
	my($len) = @raxfields;
	$endtime = 60*$endtime + $raxfields[5] if( $len > 5 );
}
close(RAXFILE);
#
#	Interpret Commands
@fields = split(/#/,$commands);
$num = @fields;
for($i=0; $i < $num; $i++ )	{
	($timeval[$i], $order[$i]) = split(/%/, $fields[$i]);
	$timeval[$i] =~ s/\s*//g;
	$order[$i] =~ s/\s*//g;
}
#
#	Registration
$reg=0;
$regval = 0;
for($i=0; $i < $num; $i++ )     {
	if($order[$i] eq 'register')	{
		++$reg;
		$regval += $timeval[$i];
		if( $reg == 0 )	{
			$regmin = $timeval[$i];
			$regmax = $timeval[$i];
		}
		else	{
			$regmin = $timeval[$i] if( $timeval[$i] < $regmin );
			$regmax = $timeval[$i] if( $timeval[$i] < $regmax );
		}
	}
	else	{
		$eventtimes[$numevents] = $timeval[$i];
		$events[$numevents] = $order[$i];
		$index[$numevents] = $numevents;
		++$numevents;
	}
}
&dataerror("No Real Events")	if( $numevents <= 0);
&dataerror("No Registration Material")	if( $reg <= 0 );
$regval = $regval/$reg;
&dataerror("Registration Range $regmin $regmax too large") unless($regmax-$regmin < 5000);
#
for($i=0; $i < $numevents; $i++ )     {
	if( $events[$i] eq 'BeginAudioUser' )	{
		$events[$i] = 'BeginAudio';
		$eventtimes[$i] += $regval;
	}
	if( $events[$i] eq 'StartSkipUser' )	{
		$events[$i] = 'StartSkip';
		$eventtimes[$i] += $regval;
	}
	if( $events[$i] eq 'StopSkipUser' )	{
		$events[$i] = 'StopSkip';
		$eventtimes[$i] += $regval;
	}
}
#
#	Sort Events
@index = sort {$eventtimes[$a] <=> $eventtimes[$b]} @index;
$beg=0;
$begaudio = -1;
for($i=0; $i < $numevents; $i++ )	{
	$j = $index[$i];
	$eventtimes1[$i] = $eventtimes[$j];
	$events1[$i] = $events[$j];
	if( $events1[$i] eq 'BeginAudio' )	{
		++$beg;
		$begaudio=$i;
	}
}
&dataerror("$beg BeginAudio Events")	if( $beg > 1 );
$actual = 1;
if( $begaudio > 0 )	{
	$actualbeg[0] = $eventtimes1[$begaudio];
	$start = 1+$begaudio;
}
else	{
	if( $events1[0] eq 'BeginAudio' )	{
		$actualbeg[0] = ($eventtimes1[0]-$regval)*.001;
		$start =1;
	}
	elsif( $events1[0] eq 'StartSkip' )	{
		$actualbeg[0] = 0;
		$start = 0;
	}
	else	{
		$actualbeg[0] = ($eventtimes1[0]-$regval)*.001;
	        $start =1;
	}
}
$active=1;
for($i=$start; $i < $numevents; $i++ )       {
	$lookat = $events1[$i];
	if($active == 1 )	{
		next if($lookat eq 'StopSkip' );
		$active=0;
		$actualend[$actual-1] = ($eventtimes1[$i]-$regval)*.001;
	}
	else	{
		next if($lookat eq 'StartSkip' );
		$active=1;
		$actualbeg[$actual] = ($eventtimes1[$i]-$regval)*.001;
		++$actual;
	}
}
if( $active=1 )	{ # End is 5 seconds more than indicated
	$actualend[$actual-1] = $endtime+5;
}
#
$clip = 'tmp/tempclip';
$cliplog = 'tmp/tempcliplog';
system("rm $clip");
system("rm $cliplog");
$com="/usr/npac/bin/rapaste $clip";
for( $i=0; $i < $actual; $i++ )	{
	system("rm $clip$i");
	system("/usr/npac/bin/racut $clip$i $absrafile $actualbeg[$i] $actualend[$i] 2>>$cliplog >>$cliplog");
	$com .= " $clip$i";
}
#
system("$com");
system("cp $clip $absrafile");
if( defined($realaudiodirectory) && ($realaudiodirectory ne '') )	{
	$absrealaudiofile = $realaudiodirectory . $rafile;
	system("cp $clip $absrealaudiofile");
}
#
if( defined($ramdirectory) && ($ramdirectory ne '') )       {
	open(RAMFILE,'>'.$ramfile) || &dataerror("Cannot Open RAM File $ramfile");
	print RAMFILE $realaudioserverurl,"\n";
	close(RAMFILE);
}
#
$today =`date`;
chomp($today); # Today's date captured from UNIX
#
print <<EOF; # Generate the HTML responding page starting with HTTP line
Content-Type: text/html

<html>
<head>
<title>Editraframe0.html Modified with Update on File Editing</title>
EOF
#
$source = 'Editraframe0.html';
open(OLDEDIT,$source) || die("\nSorry Could not open ",$source," \n");
$copy =0;
while( $line=<OLDEDIT>) {
        chomp($line);
        print "$line\n" if( $copy );
        if($line eq '<!-- STARTCOPY -->' )      {
                $copy =1;
                print "$line\n";
                next;
        }
        if( $line eq '<!-- STARTMESSAGE -->' )       {
                &printmessage();
                next;
        }
}
exit; # End Program
#
sub printmessage	{ # Print What was done!

	print "<h2>File <font color=red >$rafile</font> Was Edited</h2>\n";
	for($i=0; $i < $actual; $i++)	{
		print "<b>Keep Region $actualbeg[$i] to $actualend[$i] Seconds</b><br>\n";
	}
	return;
}	# End printmessage
#
sub dataerror	{
	my($errmess) = @_;
#
	print <<EOF; # Start the HTML responding page beginning with HTTP line
Content-Type: text/html

<html>
<head>
<title>Data Input Error!</title>
</head>
<body bgcolor="white" >
<h2>There was a Data Input Error in Form -- Sorry</h2>
<h2>Reason was: $errmess</h2>
</body>
</html>
EOF
        exit; # End Program
}
#
sub backupfile	{
	my($file) = @_;
#
	undef %indexsavefile;
	@listoffiles = `ls -tr $absrafile.save1 $absrafile.save2 $absrafile.save3`;
	$countoffiles=0;
        foreach $file  (@listoffiles)    {
		chomp($file);
	        next unless $file;
		next unless $file =~ m%\.save\d$%;
		$chompedfiles[$countoffiles] = $file;
		$indexsavefile{$file} =  1;
		++$countoffiles;
	}
	if( $countoffiles == 3 )	{
		$touse = $chompedfiles[0];
	}
	else	{
		foreach $key ($absrafile . '.save1',$absrafile . '.save2',$absrafile . '.save3') {
			next if(defined($indexsavefile{$key}));
			$touse = $key;
			last;
		}
	}
	$com = "cp $absrafile $touse";
	$retval = system($com);
	if($retval > 0 )	{
		return 0;
	}
	return 1;
}	# End backupfile
