#!/usr/local/bin/perl5 -w
#  List .ra Audio Files
#
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
        $radirectory = $formdata{"radirectoryname"}; # The input ra directory
}
else    { # Error Found!
	&dataerror('System Error');
}
#
$pwd = `pwd`;
chomp($pwd);
$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 Latest File List</title>
EOF
#
&getlist(); # Get file list 
#
$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 '<!-- STARTSELECTLIST -->' )	{
		&printlist();
		next;
	}
}
exit; # End Program
#
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 getlist     {
#
	chdir $radirectory;
        @listoffiles = `ls  *.ra`;
        $countoffiles=0;
        foreach $file  (@listoffiles)    {
                chomp($file);
                next unless $file;
                $chompedfiles[$countoffiles] = $file;
		$file =~ m%(\d*).ra$%;
		$val = $1;
		if($val eq '')	{
			$sortnum{$file} = -1;
		}
		else	{
			$sortnum{$file} = $val;
		}
                $countoffiles++;
        }
	@chompedfiles = sort sortfunc @chompedfiles;
	chdir $pwd;
}	# End getlist of RA files
#
sub sortfunc	{
	if(($sortnum{$a} <0) && ($sortnum{$b}<0) )	{
		return $a cmp $b;
	}
	elsif(($sortnum{$a} <0) && ($sortnum{$b}>=0) )	{
		return -1;
	}
	elsif(($sortnum{$a} >=0 ) && ($sortnum{$b} <0) )	{
		return 1;
	}
	else	{
		return $sortnum{$a} <=> $sortnum{$b};
	}
}

#
sub printlist     {
#
	print "parent.bigboss.numrafiles = $countoffiles;\n";
	for($i=0;$i<$countoffiles;$i++)	{
		print "parent.bigboss.filelist[$i] = '$chompedfiles[$i]'\n";
	}
}
