#! /usr/bin/perl -w

# $ENV{LD_LIBRARY_PATH} = "/usr/local/gcc/lib";

use Date::Calc qw(:all);
use Getopt::Long;
use GD;

require "/mnt/remote/cig/home/derek/library/perl/myperl.pl";
require "/mnt/remote/cig/home/derek/library/perl/writetext.pl";

print "Content-type: text/html\n\n";

  geoMeso(\%geo_lat, \%geo_lon, \%geo_longname, \%geo_city, \%geo_range, \%geo_azimuth, \%geo_county, \%geo_cd);

  &initialize;
  &parseForm;
  &getVariables;


  $begse = $endse = 0;
  printf("BEG TIME OF %04d-%02d-%02d %02d:%02d %s<br>\n", $begyr,$begmo,$begda, $beghr,$begmi,$tz);
  printf("END TIME OF %04d-%02d-%02d %02d:%02d %s<br>\n", $endyr,$endmo,$endda, $endhr,$endmi,$tz);
  printf("   becomes<br>\n");
  if ($tz =~ m/CST/) {
    ($useyr,$usemo,$useda, $usehr,$usemi,$usese) = Add_Delta_DHMS($endyr,$endmo,$endda, $endhr,$endmi,$endse, 0,6,0,0);
  } elsif ($tz =~ m/CDT/) {
    ($useyr,$usemo,$useda, $usehr,$usemi,$usese) = Add_Delta_DHMS($endyr,$endmo,$endda, $endhr,$endmi,$endse, 0,5,0,0);
  } elsif ($tz =~ m/GMT|UTC/) {
    ($useyr,$usemo,$useda, $usehr,$usemi,$usese) = ($endyr,$endmo,$endda, $endhr,$endmi,$endse);
  } else {
    printf("CRASH! NO TIME ZONE<br>\n");
    exit(-1);
  }
  $usedate = sprintf("%04d-%02d-%02d", $useyr,$usemo,$useda);
  printf("USE TIME OF %04d-%02d-%02d %02d:%02d UTC<br>\n", $useyr,$usemo,$useda, $usehr,$usemi);

  $useobs = ($usehr*12 + $usemi/5);
  printf(" ... and we'll use observation number: %d<br>\n", $useobs);

  my $result = 0;

  my $syscall = sprintf("%s/slavegram %s %s %d", $progdir, $usedate, $usestid, $useobs);
  $result = `$syscall`;
  # print "result (1) of $syscall was: $result <br>\n";

  $syscall = sprintf("/usr/X11R6/bin/convert tmp.gif tmp.png");
  $result = `$syscall`;
  # print "result (2) of $syscall was: $result <br>\n";

  unlink("tmp.gif");
  $orig = GD::Image->newFromPng("tmp.png");
  $img = $orig->clone;
  unlink("tmp.png");


  ## --- Draw time ticks and local hour identifiers where appropriate
    # -- We're going to make some assumptions here
    # -- essentially, we're assuming the metogram is laid out in the traditional way
    # -- (60-pixel left margin, temp box of predictable height, etc.)

    $horz_offset=60;
    $vert_offset=60;

    ($curyr,$curmo,$curda, $curhr,$curmi,$curse) = ($begyr,$begmo,$begda, $beghr,$begmi,$begse);

    for ($n=0; $n<288; $n++) {
      # printf("  %3d current time: %04d-%02d-%02d %02d:%02d %s<br>\n", $n, $curyr,$curmo,$curda, $curhr,$curmi, $tz);

      if ($curmi == 0) {
        my $hor = $horz_offset + 2*$n;

        my @uppers=(60,240,440,560,680);
        my @lowers=(220,420,540,660,780);

        for ($panel=0; $panel<5; $panel++) {

          my $upr=$uppers[$panel];
          my $lwr=$lowers[$panel];

          if ($curhr%3 == 0) {
            my $tmpstr2 = sprintf("%02d", $curhr);
            $clr = $img->colorResolve(102,102,102);
            writeText($img,$clr,"arial",8,0,$hor,$upr-8,$tmpstr2,"TC") if ($n > 6 && $n < 288-6);
               # don't print if we're too close to the edge

            $clr=$img->colorResolve(153,153,153);
            if ($curhr==0) {
              $img->line($hor,$upr,$hor,$lwr,$clr);
            } else {
              $img->line($hor,$upr,$hor,$upr+10,$clr);
              $img->line($hor,$lwr,$hor,$lwr-10,$clr);
            }

          } else {
            $clr=$img->colorResolve(153,153,153);
            $img->line($hor,$upr,$hor,$upr+5,$clr);
            $img->line($hor,$lwr,$hor,$lwr-5,$clr);
          }
        }
      }

      ($curyr,$curmo,$curda, $curhr,$curmi,$curse) = Add_Delta_DHMS($curyr,$curmo,$curda, $curhr,$curmi,$curse, 0,0,5,0);
    }


  printf ("Writing title and copyright information ...<br>\n");

  ## --- Now write a title and some copyright information

    # -- Title

        $tmpstr = sprintf("%s 24-Hour Mesonet Meteogram", $geo_longname{$usestid});
        $clr = $img->colorResolve(  0,  0,  0);
        writeText($img,$clr,"arial",14,0,$horz_offset,2,$tmpstr,"UL");

      if ($endhr >= 12) {
        $ampm="pm";
        $tmphr = $endhr-12;
      } else {
        $ampm="am";
        $tmphr = $endhr;
      }
      if ($tmphr==0) { $tmphr=12; }

      $tmpstr = sprintf("for the period ending %d:%02d %s %s %s %d, %d\n", $tmphr,$endmi, $ampm,$tz, $shortnames[$endmo],$endda,$endyr);
      writeText($img,$clr,"arial",14,0,$horz_offset,20,$tmpstr,"UL");


    # -- Copyright

      my $clr = $img->colorResolve(153,153,102);
      writeText($img,$clr,"arialn",8,0,$horz_offset+288+288,785,$gCopy,"UR");


  ## --- We're done ... write the final image

  if (! -d $destdir) {
    printf ("Creating output directory $destdir.\n");
    mkdir ($destdir);
    chmod 0775, $destdir;
  }

  $pngtitle = sprintf("%s/%s.png", $destdir, $rootName);
  printf("Writing to %s<br>\n", $pngtitle);
  $pngout = $img->png;
  open (DISPLAY,">$pngtitle") || die $!;
  print DISPLAY $pngout;
  close DISPLAY;
  chmod 0774, $pngtitle;


  printf("<br><p><br>\n");
  printf("<b>Your final image is available at: <font size=\+1><a href=\"%s/%s.png\">%s.png</a></font></b><br>\n", $desturl, $rootName, $rootName);

  exit;

## --- End of Main Program



sub initialize {
  @shortnames = ("junk","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

  ($nowyr,$nowmo,$nowda, $nowhr,$nowmi,$nowse) = Today_and_Now();
  $destdir   = sprintf("/home/httpd/htdocs/tmpdata/meteograms");
  $desturl   = sprintf("http://cig.ocs.ou.edu/tmpdata/meteograms");
  $progdir   = sprintf("/ocsdata/processes/mesonet/meteograms");

  $gCopy = sprintf("Copyright (c) %d Oklahoma Climatological Survey. All rights reserved.", $nowyr);
}


sub getVariables {
  if (exists($ENV{'REQUEST_METHOD'}) && $ENV{'REQUEST_METHOD'} eq 'POST') {
    #foreach $key (sort keys %FORM) {
    #  print "$key ... $FORM{$key}<br>\n";
    #}

    $endyr = (exists($FORM{'endyr'}) ? $FORM{'endyr'} : $nowyr);
    $endmo = (exists($FORM{'endmo'}) ? $FORM{'endmo'} : $nowmo);
    $endda = (exists($FORM{'endda'}) ? $FORM{'endda'} : $nowda);
    $endhr = (exists($FORM{'endhr'}) ? $FORM{'endhr'} : $nowmo);
    $endmi = (exists($FORM{'endmi'}) ? $FORM{'endmi'} : $nowmi);

    $endyr+=0; $endmo+=0; $endda+=0; $endhr+=0; $endmi-=($endmi%5);

    $tz = (exists($FORM{'timezone'}) ? $FORM{'timezone'} : "GMT");
    $usestid = (exists($FORM{'usestid'}) ? uc($FORM{'usestid'}) : "NONE");
    $rootName = (exists($FORM{'rootname'}) ? $FORM{'rootname'} : "temp");

  } else {
    $endyr = 2003;
    $endmo = 3;
    $endda = 5;
    $endhr = 10;
    $endmi = 00;
    $enddate = sprintf("%04d-%02d-%02d", $endyr,$endmo,$endda);

    $tz = "CST";
    $rootName = "dekey";
    $usestid = "MANG";
  }

  $enddate = sprintf("%04d-%02d-%02d", $endyr,$endmo,$endda);

  ($begyr,$begmo,$begda) = Add_Delta_Days($endyr,$endmo,$endda, -1);
  ($usehr,$usemi) = ($endhr,$endmi);

  ($usehr,$usemi) = ($endhr,$endmi);
  ($beghr,$begmi) = ($endhr,$endmi);
}


sub parseForm {
  if ($ENV{'REQUEST_METHOD'} eq 'GET') {
    # Split the name-value pairs
    @pairs = split(/&/, $ENV{'QUERY_STRING'});
  } elsif ($ENV{'REQUEST_METHOD'} eq 'POST') {
    # Get the input
    read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});

    # Split the name-value pairs
    @pairs = split(/&/, $buffer);
  }

  foreach $pair (@pairs) {
    ($name, $value) = split(/=/, $pair);

    $name =~ tr/+/ /;
    $name =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    $value =~ tr/+/ /;
    $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;

    # If they try to include server side includes, erase them, so they
    # arent a security risk if the html gets returned.  Another
    # security hole plugged up.

    $value =~ s/<!--(.|\n)*-->//g;

    # Create two associative arrays here.  One is a configuration array
    # which includes all fields that this form recognizes.  The other
    # is for fields which the form does not recognize and will report
    # back to the user in the html return page and the e-mail message.
    # Also determine required fields.

    if ( $name eq 'redirect'  && ($value)) {
      $CONFIG{$name} = $value;
    } elsif ($value) {
      $FORM{$name} = $value;
    }
  }
}

