#!/usr/bin/perl
#
# Create an animation showing a standing wave, by 
#    1) generating a set of datafiles, one per snapshot in time,
#           showing the shape of the wave
#    2) combining all the datafiles into an animated GIF
#
# MWR 3/29/2019

$mypi = 3.14159;

$datadir = "./datafiles";

$num_snapshots = 123;
$speed = 0;
$xmin = -10.0;
$xmax = 10.0;
$A = 1.0;
$period = 3.0;
$omega = 2.0*$mypi/($period);
$dx = 0.1;
$t_start = 0;
$t_end = 10.0;
$dt = ($t_end - $t_start) / $num_snapshots;

# step one: create one datafile per snapshot
for ($i = 0; $i < $num_snapshots; $i++) {
  $datafile[$i] = sprintf "%s/snapshot_%02d.dat", $datadir, $i;
  open(DATAFILE, ">$datafile[$i]") || die("can't open file $datafile[$i]");

  $t = $t_start + ($i*$dt);

  # change the amplitude with each snapshot
  $amp = $A*cos($omega*$t);


  for ($x = $xmin; $x <= $xmax; $x += $dx) {
    $y = $amp*cos($x - $speed*$t);
    printf DATAFILE "%lf %lf \n", $x, $y;
  }
  close(DATAFILE);

}


  


# step two: plot each datafile to create an animated GIF image 

  my($output_file, $term_options);

  $output_file = "standing_a.gif";
  $term_options = "gif animate delay 30  ";

  $cmdfile = "gnuplot.in";
  
  open (CMDFILE, ">$cmdfile") || die("can't open $cmdfile for writing");
  printf CMDFILE "set output '$output_file' \n";
  printf CMDFILE "set term $term_options \n";

  # revert to some oldish default colors
  printf CMDFILE "set style line 1 lt rgb 'red' lw 3  \n";
  printf CMDFILE "set style line 2 lt rgb 'green' lw 3  \n";
  printf CMDFILE "set style line 3 lt rgb 'blue' lw 3  \n";
  printf CMDFILE "set style line 4 lt rgb 'cyan' lw 3  \n";
  printf CMDFILE "set style line 5 lt rgb 'violet' lw 3  \n";


  printf CMDFILE "set grid \n";
  printf CMDFILE "set key top right \n";
  printf CMDFILE "set xrange [$xmin:$xmax]  \n";
  printf CMDFILE "set yrange [0-($A*1.1):0+($A*1.1)]  \n";
  printf CMDFILE "set xlabel 'X position (m)  '  \n";
  printf CMDFILE "set ylabel 'Y position (m) ' \n";
  printf CMDFILE "set title 'Standing wave ' \n"; 

  for ($i = 0; $i < $num_snapshots; $i++) {
    printf CMDFILE "    plot '$datafile[$i]' using 1:2 with lines ls 1  t '' \n ";
  }

  printf CMDFILE "$cmd \n";


  printf CMDFILE "set output \n";
  printf CMDFILE "quit \n";
  close(CMDFILE) ;
  
  $retval = `gnuplot < $cmdfile`;



exit 0;



