#!/usr/bin/perl
#

$debug = 1;

$pi = 3.14159;


# create a simple gaussian curve centered on zero
#  with width 1 or so
$datafile = "./make_plots.dat";
open(DATAFILE, ">$datafile") || die("can't open file $datafile");
$sigma = 1.0;
$center = 0.0;
$start_x = -10;
$end_x = 10;
$dx = 0.01;
for ($x = $start_x; $x <= $end_x; $x += $dx) {
  $arg = (($x - $center)*($x - $center))/(2.0*$sigma*$sigma);
  $y = (1.0/(2.0*$pi*$sigma))*exp(0.0 - $arg);
  printf DATAFILE "%12.4f %12.4f \n", $x, $y;
}
close(DATAFILE);


# graph showing the gaussian
$title = "Distribution of momenta for electrons which passed through slit";
$cmdfile = "./make_plots.gnu";
$psfile = "./make_plots.ps";
open(CMDFILE, ">$cmdfile") || die("can't open $cmdfile");
printf CMDFILE "set output '$psfile' \n ";
printf CMDFILE "set term postscript color enhanced 18 \n";
printf CMDFILE "set grid \n";
printf CMDFILE "set key top right \n";
printf CMDFILE "set xlabel 'Momentum in y-direction, units of (h / 2 {/Symbol p} d)'  \n";
printf CMDFILE "set ylabel 'Percent of electrons'  \n";
printf CMDFILE "set title '$title'  \n";
printf CMDFILE "plot [-4:4][-1:20] ";
printf CMDFILE "  '$datafile' using (\$1):(\$2*100) ";
printf CMDFILE "            t '' pt 1 ps 0.6 lw 2";
printf CMDFILE " \n";
printf CMDFILE "quit \n";
close(CMDFILE);

$cmd = "gnuplot $cmdfile ";
printf "cmd is ..$cmd.. \n";
$ret = `$cmd`;
$giffile = $psfile;
$giffile =~ s/.ps/.gif/;
$cmd = "convert -rotate 90 $psfile $giffile";
printf "cmd is ..$cmd.. \n";
$ret = `$cmd`;



exit 0;



##################################################################
# PROCEDURE: fill_if_empty
#
# DESCRIPTION: We look at the given file, which holds data
#              we want to plot with GnuPlot.  If the file
#              is empty, the GnuPlot will throw an error
#              and terminate the script.  That's bad.
#              So, here we check: if the file is empty, 
#              we place into it a single line which is just
#              a whole bunch of columns, all full of values
#              -99.0  .... which should always fall off plots.
#
# RETURNS:
#         nothing
#
sub fill_if_empty {
  my($filename);
  my($cmd);
  my($i);
  my($line_count);

  $filename = $_[0];

  open(FILENAME, "$filename") || die("fill_if_empty: can't open file $filename");
  $line_count = 0;
  while (<FILENAME>) {
    $line_count++;
  }
  close(FILENAME);

  if ($line_count > 0) {
    # do nothing
    if ($debug > 0) {
      printf "fill_if_empty: do nothing to file $filename \n";
    }
    return;   
  }

  # oops, let's add a line to this empty file
  if ($debug > 0) {
    printf "fill_if_empty: must add dummy line to file $filename \n";
  }
  open(FILENAME, ">$filename") || die("fill_if_empty: can't open file $filename for writing");
  for ($i = 0; $i < 60; $i++) {
    printf FILENAME " 99.0 ";
  }
  printf FILENAME "\n";
  close(FILENAME);

}
