#!/usr/bin/perl
#
# Create an image which shows some specks of light
#   which (gradually) form an interference pattern.
#
# MWR 4/4/2003

$debug = 1;

# name of the output image
$outfile = "interf.fts";

# name of temp file used to store numbers
$tempfile = "test.tmp";

# first, create a blank image
if ($debug > 0) {
  printf "about to create blank image $outfile ... \n";
}
$nrow = 500;
$ncol = 500;
$cmd = "pstar nrow=$nrow ncol=$ncol sky=0 outfile=$outfile ";
$ret = `$cmd`;
if ($debug > 0) {
  printf "  ret is ..$ret..\n";
}

# now, create an image which contains just a little speck
$speckfile = "speck.fts";
if ($debug > 0) {
  printf "about to create little speck image $speckfile \n";
}
$speck_nrow = 10;
$speck_ncol = 10;
$mid = $speck_nrow/2.0;
$speck_fwhm = 3.0;
$speck_counts = 1000;
$cmd = "pstar nrow=$speck_nrow ncol=$speck_ncol sky=0 ";
$cmd .= "star=$speck_counts,$mid,$mid,$speck_fwhm outfile=$speckfile";
$ret = `$cmd`;
if ($debug > 0) {
  printf "  ret is ..$ret..\n";
}

#
# now comes the main part of the program, where we repeatedly add
#   the speck to the main image 
#

# get rid of the temp file; we'll start filling it now
unlink($tempfile);

for ($nspeck = 10; $nspeck < 10000; $nspeck *= 3) {

  open(TEMPFILE, ">>$tempfile") || die("can't open $tempfile");
for ($i = 0; $i < $nspeck; $i++) {

  # generate random row, but a col which is based on sin(15*x)
  #   so that over the interval [0,1], it has about 5 cycles
  $row = rand;
  $row *= $nrow;
  $col = rand;
  $delta = sin($col*30.0);
  $col = $col + (0.2*$delta) + (0.03*(rand(1) - 0.5));
  $col *= $ncol;
  printf TEMPFILE "next speck at %6.2f  %6.2f  \n", $row, $col;

if (0 == 1) {
  # implant a speck at this location
  $nice_row = sprintf "%.0f", $row;
  $nice_col = sprintf "%.0f", $col;
  $cmd = "implant $outfile $speckfile,$nice_row,$nice_col overlay";
  if ($debug > 0) {
    printf "  cmd is ..$cmd..\n";
  }
  $ret = `$cmd`;
  if ($debug > 0) {
    printf "  ret is ..$ret..\n";
  }
}

}
  close(TEMPFILE);

  # now make a PNG image of this situation
  $cmdfile = "test.cmd";
  $plotfile = sprintf "test_%d.png", $nspeck;
  open(CMDFILE, ">$cmdfile") || die("can't open $cmdfile for writing");
  printf CMDFILE "set noborder\n";
  printf CMDFILE "set noxtics\n";
  printf CMDFILE "set noytics\n";
  printf CMDFILE "set nokey\n";
  printf CMDFILE "set output '$plotfile' \n";
  printf CMDFILE "set term png \n";
  printf CMDFILE "plot [0:$nrow][0:$ncol] '$tempfile' using 5:4 lt 0 lw 5 ps 1.0 \n";
  printf CMDFILE "set output \n";
  printf CMDFILE "quit \n";
  $cmd = "gnuplot $cmdfile";
  $ret = `$cmd`;

  # now convert to monochrome GIF
  $giffile = $plotfile;
  $giffile =~ s/png/gif/;
  $cmd = "convert $plotfile $giffile ";
  $ret = `$cmd`;


}



exit 0;
