#!/usr/local/bin/perl

if (($ARGV[0] eq "about") or ($ARGV[0] eq "about")){
die "\n\nThis script runs the 9eqns executable once in each subdirectory indexed from Low to High.
This method stores output data in the directory whose values reflect those initial conditions.
The directory name also includes the value of the initial guess to differentiate between trials.
This script uses a constant initial guess, but can be easily modified with another for loop to
run multiple initial guesses.\n
Other command-line option described with -help\n\n";}

if (($ARGV[0] eq "help") or ($ARGV[0] eq "-help")){
    die "\nformat = [MultiplierLow] [MultiplierHigh] [Initialguess] [StartVar] [EndVar]\n\n";}

#define a few terms for future use
$MultiplierLow = $ARGV[0];
$MultiplierHigh = $ARGV[1];
$Initialguess = $ARGV[2];
$StVar = $ARGV[3];
$EndVar = $ARGV[4];

for (;$MultiplierLow <= $MultiplierHigh; $MultiplierLow =  $MultiplierLow + 1)
{
print "\n
***Hold on... 
creating directory $MultiplierLow full of data...***\n";

    $dir = "dat.multiplier.$MultiplierLow.guess.$Initialguess"; 
    `mkdir dat.multiplier.$MultiplierLow.guess.$Initialguess`;

    chdir $dir ||die "cd to $dir failed\n" ;

print "Running '9eqns $MultiplierLow $Initialguess'...";
    `../9eqns $MultiplierLow $Initialguess`;

#####################
#start distribute.pl#
#####################
    @buffer = `ls | grep output.`;
    $NumFiles = @buffer;
    $NumFiles = $NumFiles - 1;
    
$NumFrames = $NumFiles;
print "      took $NumFrames iterations to converge.\n";

#####################
#start mpeg_maker.pl#
#####################
 
#determines largest y bounds for each var for graphing each var
  @buffer = `cat output.$NumFiles`;
  for ($outer = 501; $outer >= 0; $outer = $outer - 1){
    @junk = split (/\s+/, pop(@buffer)); 
    for ($endvar = 8; $endvar >= 0; $endvar = $endvar - 1){
      $temp = abs(pop(@junk));
   	if ($temp > $yval[$endvar]){
	  $yval[$endvar] = sprintf("%.1f", $temp);
	}
    }
  }


print "Generating .pro file...";
#write RunPvWave.pro file
open (PRO, ">RunPvWave.pro"); 
print PRO "set_plot, 'ps'\n";

for ($filenum = 0; $filenum <= $NumFiles; $filenum = $filenum + 1) {
    $fileName = sprintf("output.%d",$filenum);
    print PRO "openr, 1, '$fileName'\n";
    print PRO "data = fltarr(9,501)\n"; # is 9x501 array correct?
    print PRO "readf, 1, data\n";

    for ($var = $StVar; $var <= $EndVar; $var = $var + 1) {
	$newFileName = sprintf("mpg.var.%d.frame.%03d.ps",$var,$filenum);
	print PRO "device, file=\"$newFileName\"\n";
        print PRO "plot,data($var,*),yrange=[-$yval[$var],$yval[$var]],xcharsize=2,ycharsize=2,zcharsize=2,xmargin=[2,1],ymargin=[1,2],title='Variable:$var  frame:$filenum'\n";
   
      	print PRO "device,/close\n";

    }
    print PRO "close, 1\n";
}
print PRO "quit\n";
close (PRO);

print "Generating graphs in PVWave from output files...\n";
#run wave with RunPvWave.pro file
`source /usr/local/setup/wvsetup`;
`/usr/local/app/vni/wave/bin/wave RunPvWave.pro`;

#Make mpegs for me!
print "Converting  post script files to ppm...\n";
#convert to better format
for ($x=$StVar; $x <= $EndVar;$x = $x + 1){
   `find . -name "mpg.var.$x.frame.*.ps" -exec pstopnm -xsize 640 -ysize 512 {} \\;`;
   `rm mpg.var.$x.frame.*.ps`;

#mpeg_encode steps

print "Generating mpeg_encode parameter file for variable $x...\n";
#start with parameter file
$PadNumFiles = sprintf("%03d",$NumFiles);

    open (TMPFL, ">par.param");

print TMPFL "PATTERN		IBBPBBPBBPBBPBB \n",
"OUTPUT		./anim$x.mpg                \n",
"FORCE_ENCODE_LAST_FRAME                        \n",
"BASE_FILE_FORMAT	PPM                     \n",
"YUV_SIZE	640x512                         \n",
"INPUT_CONVERT	 pnmscale -xysize 320 256 *     \n",
"GOP_SIZE	15                              \n",
"SLICES_PER_FRAME  1                            \n",
"INPUT_DIR	.                               \n",
"INPUT                                          \n",
"mpg.var.$x.frame.*001.ppm [000-$PadNumFiles]   \n",
"END_INPUT                                      \n",
"PIXEL		HALF                            \n",
"RANGE		10                              \n",
"PSEARCH_ALG	EXHAUSTIVE                      \n",
"BSEARCH_ALG	SIMPLE                          \n",
"IQSCALE		6                       \n",
"PQSCALE		6                       \n",
"BQSCALE		6                       \n",
"REFERENCE_FRAME	ORIGINAL                \n",
"PARALLEL_TEST_FRAMES	1                       \n",
"PARALLEL_TIME_CHUNKS	4                       \n";
close (TMPFL);
#end param file

#finally encode the mpeg
print "Encoding mpeg for variable $x...\n";
`mpeg_encode par.param`;

`rm mpg.var.$x.frame.*.ppm`;
}
#end mpeg_encode steps

print "Cleaning up after myself..\n";
`rm par.param`;
`rm RunPvWave.pro`;
`mv output.$NumFiles final.eigenval`;
`rm output.*`;

print "Isolating the eigen value...\n";
#isolate the eigenval from the last output file
@buffer = `cat final.eigenval`;
@junk = split (/\s+/, pop(@buffer));
$eigenval = pop(@junk);

##################################

    chdir '..'||die "cd to .. failed";

print "Renaming data directory to reflect the eigen value $eigenval...\n";
#change the dir name to reflect the eigen value
    `mv dat.multiplier.$MultiplierLow.guess.$Initialguess dat.multiplier.$MultiplierLow.guess.$Initialguess.eigen.$eigenval`;

print "\n...Done with directory $MultiplierLow.\n";
}
#end loop for current multiplier
print "\n\nCan you believed I'm finally finished? You should because I am.\n\n\n";