#!/usr/bin/perl
#
use File::Temp qw/tempfile/;
{
  do "acqPATHs.pl";
  $str = $ENV{"QUERY_STRING"};
  ($dir, $fnm, $spec, $ncc, $np, $mp,
   $axs, $ayw, $axn, $aye, $ams) = split(/\+/, $str);
  if ($mp eq "1") { $ams = "-1"; }
  if ($dir ne "") { $dir .= "/"; }
  $path = "$DATAPATH/$dir$fnm";
#
  $err = 0;
  if (-f $path) {
    if (open(IN, "bin/darea $ncc $spec $path |")) {
      $_ = <IN>;
      if (/^OK/) {
        $_ = <IN>; ($ixs, $iys, $xsz, $ysz) = split;
        $sz = ($xsz > $ysz) ? $xsz/360: $ysz/360; $fs = 1;
        while ($sz > 50) { $fs *= 10; $sz /= 10; }
        if ($sz <= 10) { $sd = $fs*10; }
        elsif ($sz <= 20) { $sd = $fs*20; }
        elsif ($sz <= 25) { $sd = $fs*25; }
        else { $sd = $fs*50; }
        $xm = $ixs + $xsz/2; $xm = int($xm/$sd) * $sd; $xl = $xm - $sd*200;
        $ym = $iys + $ysz/2; $ym = int($ym/$sd) * $sd; $yl = $ym - $sd*200;
        close(IN);
#-----------------------------------------------------------------------------
#   Remove temporary file "$HTMLPATH/fout/AMXS.*.png" older than 1H.
        @files = glob("$HTMLPATH/fout/AMXS.*.png"); $now = time();
        foreach $f(@files) {
          if (($now-(stat($f))[9]) > 3600) { unlink $f; }
        }
#-----------------------------------------------------------------------------
#   Generate a temporary file "$HTMLPATH/fout/AMXS.XXXXXX.png".
#-----------------------------------------------------------------------------
        ($fh, $file) = tempfile("AMXS.XXXXXX", SUFFIX=>'.png',
                                DIR=>"$HTMLPATH/fout");
        binmode($fh); $name = substr($file,length("$HTMLPATH/fout/"));
#-----------------------------------------------------------------------------
#       ########################################################
#       #  Generate PNG image (stdout) from Grid-data ($path)  #
#       #        (  mktpng ncc frm spec infile [outfile]  )    #
#       #        (    (ncc) nc[:iorg:korg]  (frm) llx:lly:msz  #
#       #        (    (spec) ift:igr[:llu:p1:p2]               #
#       ########################################################
        if (open(IN, "bin/mktpng $ncc $xl:$yl:$sd $spec $path |")) {
          binmode(IN); $len = sysread(IN,$buf,80);
          if (substr($buf,1,3) ne "PNG") { $err = 1; $msg = "***** $buf"; }
          else {
            while ($len) {
              $lout = syswrite($fh,$buf,$len);
              if (defined($lout)) {
                $len = sysread(IN,$buf,1024);
                unless (defined($len)) 
                  { $len = 0; $err = 1; $msg = "SYSREAD fail"; }
              }
              else { $len = 0; $err = 1; $msg = "SYSWRITE fail"; }
            }
          }
          close(IN);
        } else {
          $err = 1; $msg = "setgpr.cgi: mktpng start fail.";
        }
        close($fh);
      } else {
        close(IN);
        $err = 1; $msg = $_;
      }
    } else {
      $err = 1; $msg = "setgpr.cgi: darea start fail.";
    }
  } else {
    $err = 1; $msg = "setgpr.cgi: $path not found.";
  }
  if ($err == 1) {
    print "Content-type: text/html; charset=iso-8859-1\n\n";
####
    $htmlbody =<<EOM;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<link rel="stylesheet" type="text/css" href="/AMXS/amxs.css">
<title>AMXS setgpr</title>
<script type="text/javascript">
<!--
function cancel() { opener.focus(); window.close(); }
//-->
</script>
</head>
<body bgcolor="ivory" style="margin: 4px 7px;">
<!-- [Parameters received] -->
<!--  dir=$dir, fnm=$fnm, spec=$spec, ncc=$ncc, np=$np, mp=$mp -->
<!--  axs=$axs, ayw=$ayw, axn=$axn, aye=$aye, ams=$ams -->
<!-- [Command-line calling "darea"] -->
<!--  "bin/darea $ncc $spec $path |" -->
<!-- [Returned values from "darea"] -->
<!--  ixs=$ixs, iys=$iys, xsz=$xsz, ysz=$ysz -->
<!--   (then,) sz=$sz, fs=$fs, sd=$sd, xm=$xm, xl=$xl, ym=$ym, yl=$yl -->
<!-- [Command-line calling "mktpng"] -->
<!--  "bin/mktpng $ncc $xl:$yl:$sd $spec $path |" -->
<form><font color="red"><b>ERROR:</b></font> &nbsp; &nbsp; &nbsp; &nbsp;
<input type="button" value="OK" onclick="cancel()"><br>
__MESG__ 
</form>
</body>
</html>
EOM
####
    $htmlbody =~ s/__MESG__/$msg/;
    print $htmlbody;
  } else {
    print "Content-type: text/html; charset=iso-8859-1\n\n";
####
    $htmlbody =<<EOM;
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<link rel="stylesheet" type="text/css" href="/AMXS/amxs.css">
<title>AMXS setgpr</title>
<script type="text/javascript" src="/AMXS/forms/apsetgp.js"></script>
<script type="text/javascript">
function retval(key) {
  if (key == 1) {
    opener.document.FM.___1___.value = getXS();
    opener.document.FM.___2___.value = getYS();
    if (document.btsetgp.krng.value == "1") {
      opener.document.FM.___3___.value = getXR();
      opener.document.FM.___4___.value = getYR();
    } else {
      opener.document.FM.___3___.value = getMS();
      opener.document.FM.___4___.value = getNX();
      opener.document.FM.___5___.value = getMS();
      opener.document.FM.___6___.value = getNY();
    }
  }
  opener.focus(); window.close();
}
//-->
</script>
</head>
<body bgcolor="ivory" style="margin: 4px 7px;" onload="init()">
<!-- [Parameters received] -->
<!--  dir=$dir, fnm=$fnm, spec=$spec, ncc=$ncc, np=$np, mp=$mp -->
<!--  axs=$axs, ayw=$ayw, axn=$axn, aye=$aye, ams=$ams -->
<!-- [Command-line calling "darea"] -->
<!--  "bin/darea $ncc $spec $path |" -->
<!-- [Returned values from "darea"] -->
<!--  ixs=$ixs, iys=$iys, xsz=$xsz, ysz=$ysz -->
<!--   (then,) sz=$sz, fs=$fs, sd=$sd, xm=$xm, xl=$xl, ym=$ym, yl=$yl -->
<!-- [Command-line calling "mktpng"] -->
<!--  "bin/mktpng $ncc $xl:$yl:$sd $spec $path |" -->
<table align="center">
  <tr><td bgcolor="wheat" width="80%"><small><b>(Using Canvas API)</b>
      Drag mouse along the desired diagonal, then the parameters are set
      automatically. &nbsp; If acceptable, click "OK" button.<br>
      The parameters can be adjusted by
      <img src="/AMXS/forms/arrow.png" alt="arrow"> or by
      <font color="blue">dragging corner/side</font> of the area.</small></td>
    <td align="center" valign="middle">
      <form name="btsetgp">
      <input type="button" value="Cancel" onclick="retval(0)"><br><br>
      <input type="button" value="  OK  " onclick="retval(1)">
      <input type="hidden" name="Fnam" value="__TFN__">
      <input type="hidden" name="Ncc"  value="__NCC__">
      <input type="hidden" name="Sllx" value="__LLX__">
      <input type="hidden" name="Slly" value="__LLY__">
      <input type="hidden" name="Smsz" value="__MSZ__">
      <input type="hidden" name="GPxs" value="__GPXS__">
      <input type="hidden" name="GPyw" value="__GPYW__">
      <input type="hidden" name="GPxn" value="__GPXN__">
      <input type="hidden" name="GPye" value="__GPYE__">
      <input type="hidden" name="GPms" value="__GPMS__">
      <input type="hidden" name="krng" value="__KRNG__">
      </form></td></tr>
  <tr><td colspan=2>
      <img src="/AMXS/fout/__TFN__" width=651 height=441
       style="position:absolute; z-index:0">
      <canvas id="map" width=651 height=441
       style="position:absolute; z-index:1"></canvas>
      </td></tr>
</table>
</body>
</html>
EOM
####
    for ($i=1; $i<7; $i++) {
      $pstr = "___" . $i . "___"; $rstr = sprintf("P%02d", $np++);
      $htmlbody =~ s/$pstr/$rstr/g;
    }
    $htmlbody =~ s/__KRNG__/$mp/;
    $htmlbody =~ s/__TFN__/$name/g;
    $htmlbody =~ s/__NCC__/$ncc/;
    $htmlbody =~ s/__LLX__/$xl/; $htmlbody =~ s/__LLY__/$yl/;
    $htmlbody =~ s/__MSZ__/$sd/;
    $htmlbody =~ s/__GPXS__/$axs/; $htmlbody =~ s/__GPYW__/$ayw/;
    $htmlbody =~ s/__GPXN__/$axn/; $htmlbody =~ s/__GPYE__/$aye/;
    $htmlbody =~ s/__GPMS__/$ams/;
    print $htmlbody;
  }
}
