#!/usr/bin/perl
#
use File::Temp qw/tempfile/;
{
  do "acqPATHs.pl";
  $str = $ENV{"QUERY_STRING"};
  ($dir, $fnm, $np, $mp, $axs, $ayw, $axn, $aye, $ams) = split(/\+/, $str);
  if ($dir ne "") { $dir .= "/"; }
  $path = "$DATAPATH/$dir$fnm";
#
  $err = 0;
  if (-f $path) {
    if (open(IN, "< $path")) {
      $_ = <IN>; while (/^#/) { $_ = <IN>; }
      $area = substr($_,0,8);
      $nc1 = substr($_,8,4); $nc2 = substr($_,12,4);
      if ($nc2 eq "    ") {
        $ncc = $nc1-0;
        if (($ncc<0) || ($ncc>=400)) { $ncc = -1; }
        elsif ($ncc<200) { $ncc += 800; }
        else { $ncc -= 200; }
      } else { $ncc = $nc2-0; }
      $_ = <IN>;
      ($ixs, $iys, $mszx, $mszy, $mx, $my, $dmy) = split;
      $xsz = ($mx-1) * $mszx; $ysz = ($my-1) * $mszy;
      $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)  #
#     #       (  mkmpng llx:lly:msz [infile [outfile]]  )    #
#     ########################################################
      if (open(IN, "bin/mkmpng $xl:$yl:$sd $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 = "Unexpected SYSREAD error"; }
            }
            else { $len = 0; $err = 1; $msg = "Unexpected SYSWRITE error"; }
          }
        }
        close(IN);
      } else {
        $err = 1; $msg = "setgp.cgi: mkmpng start fail.";
      }
      close($fh);
#
    } else {
      $err = 1; $msg = "setgp.cgi: $path open fail.";
    }
  } else {
    $err = 1; $msg = "setgp.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 setgp</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, area=$area, ncc=$ncc, np=$np, mp=$mp -->
<!--  axs=$axs, ayw=$ayw, axn=$axn, aye=$aye, ams=$ams -->
<!--   (then,) sz=$sz, fs=$fs, sd=$sd, xm=$xm, xl=$xl, ym=$ym, yl=$yl -->
<!-- [Command-line calling "mkmpng"] -->
<!--  "bin/mkmpng $xl:$yl:$sd $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 setgp</title>
<script type="text/javascript" src="/AMXS/forms/apsetgp.js"></script>
<script type="text/javascript">
<!--
function retval(key) {
  if (key == 1) {
    opener.document.FM.___0___.value = __NCC__;
    opener.document.FM.___1___.value = getXS();
    opener.document.FM.___2___.value = getYS();
    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, area=$area, ncc=$ncc, np=$np, mp=$mp -->
<!--  axs=$axs, ayw=$ayw, axn=$axn, aye=$aye, ams=$ams -->
<!--   (then,) sz=$sz, fs=$fs, sd=$sd, xm=$xm, xl=$xl, ym=$ym, yl=$yl -->
<!-- [Command-line calling "mkmpng"] -->
<!--  "bin/mkmpng $xl:$yl:$sd $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__">
      </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
####
    if ($mp == 0) { $mp = $np; }
    $rstr = sprintf("P%02d", $mp); $htmlbody =~ s/___0___/$rstr/;
    for ($i=1; $i<7; $i++) {
      $pstr = "___" . $i . "___"; $rstr = sprintf("P%02d", $np++);
      $htmlbody =~ s/$pstr/$rstr/;
    }
    $htmlbody =~ s/__TFN__/$name/g;
    $htmlbody =~ s/__NCC__/$ncc/eg;
    $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;
  }
}
