#!/usr/bin/perl
#

$JDBASE = 2455000;

$date = "2014 Aug 28";
$target = "_asas14cv";
$filter = "clear";
$filter_lc = lc($filter);
$mag_offset = 0.0;
$aper = "4";
$suffix = sprintf "_%s.dat%d", $filter_lc, $aper;

# make the Postscript graph
make_graph($target . "_". $aper . "" . $filter . "_field_aug27.ps", "postscript color enhanced 'Helvetica,18' ");

# make a PNG graph
#make_graph("hs2331_" . $aper . "_field_jul23.png", "png color");

exit 0;



############################################################################
# create a file with GNUPLOT commands, then execute GNUPLOT to read
#   from that file.
#
# usage:  make_graph   outfile_file_name  set_term_options
#
sub make_graph {
  
  my($output_file, $term_options);

  # get the arguments
  $output_file = $_[0];
  $term_options = $_[1];

  $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";
  printf CMDFILE "set grid \n";
  printf CMDFILE "set key top right \n";
  printf CMDFILE "set ylabel 'Differential V-ish magnitude' \n";
  printf CMDFILE "set xlabel 'Julian Date - 2,455,000' \n";
  printf CMDFILE "set title 'ASASSN-14cv field, $filter $aper-pix diff mag, 12-inch, $date UT'\n", $aper;
  
  $cmd = "plot [1897.52:1897.78][7.0:0.5] 'starA$suffix' using (\$5-$JDBASE):(\$7-$mag_offset)   lt 1 pt 1 lw 4 t 'A' ";
  #$cmd = "plot [389.73:389.78][1.7:-0.3] 'starA.$suffix' using (\$5-$JDBASE):(\$7-$mag_offset)   lt 1 pt 1 lw 4";
  $cmd = $cmd . ", 'star14cv$suffix' using (\$5-$JDBASE):(\$7-$mag_offset) lt 2 pt 2 lw 4 t '14cv'";
  $cmd = $cmd . ", 'starB$suffix' using (\$5-$JDBASE):(\$7-$mag_offset) lt 3 pt 3  lw 4 t 'B'";
  $cmd = $cmd . ", 'starC$suffix' using (\$5-$JDBASE):(\$7-$mag_offset) lc 4 pt 5  lw 4 t 'C'";
  $cmd = $cmd . ", 'starD$suffix' using (\$5-$JDBASE):(0.0+\$7-$mag_offset) lc 5 pt 4  lw 4 t 'D'";
  $cmd = $cmd . ", 'starE$suffix' using (\$5-$JDBASE):(0.0+\$7-$mag_offset) lc 1 pt 6  lw 4 t 'E'";

  printf CMDFILE "$cmd \n";
  printf CMDFILE "set output \n";
  printf CMDFILE "quit \n";
  close(CMDFILE) ;
  
  $retval = `gnuplot < $cmdfile`;
  printf "retval is ..%s..\n", $retval;
  
  if ($term_options =~ /postscript/) {
    $psfile = $output_file;
    $giffile = $psfile;
    $giffile =~ s/.ps/.png/;
    $cmd = "convert -rotate 90 $psfile $giffile";
    printf "cmd is ..$cmd.. \n";
    $ret = `$cmd`;
  }

}
