#!/usr/bin/perl -w
#################################################################
#
# myrseism.cgi
#
# Plottar skjálfta í Mýrdals- og Eyjafjallajökli
#
# 1999-11-12 gg
#################################################################

use CGI qw(:standard :html3);
use POSIX 'strftime';
use CGI::Carp;
use GD;
use Image::Size;
use strict;
use constant CATEQ => "/home/sil/bin/cateq";
use constant GETTREM => '/home/sil/bin/gettrem';
use constant GNUPLOT => "/usr/bin/gnuplot";

$| = 1;
$^T=time;
 
my @oldgif=<m_*.gif>;
my $gif;
 
# Delete those gif files that are older than ~2.880 min (0.002*24*60)
foreach $gif (@oldgif) {
    unlink $gif unless -M $gif < .003 ;
}

my @eqlist;
my @loctype  = qw/ auto manual /;
my @ndays    = qw/ 1 2 3 4 5 6 7 8 10 14 20 30 60 90/;
my $ymd;
my $periodstr="";
my @stn = qw/mid skh snb hvo/;
my @xstn=(43,342,518,435);
my @ystn=(163,337,97,275);
my $stndata="";
my $pltstr="";

my $q = new CGI;

print $q->header('text/html');

print $q->start_html( "-title"=>'Skjálftakort',
                     -author=>'gg@vedur.is',
                     -bgcolor=>"FFFFFF",
		     -charset=>"iso-8859-1");

print table( {-align=>'center',-cellpadding=>'1',
           -cellspacing=>'1', -width=>'60\%'},
       TR(
         td({-align=>'center'},
            a({-href=>'../ja/index.html'},"\[Til baka\]")),
         ),
);

#print a({-href=>'/ja/jar_inn/myrdalsj.html'},"\[Til baka\]");
printForm();

if ($q->param()) {
   my $loctype = $q->param("loctype");
   my $quality = $q->param("quality");
   my $ndays   = $q->param("ndays");

   my $eqpath = "/sk1";
   my $eqfile="";

   my ( $x, $y ) = ( $q->param('SIL.x'), $q->param('SIL.y')); 

   if (!$x) { 
      if ( $loctype eq "auto" ) {
         $eqfile = "aut.mag";
      }else{
         $eqfile = "lib.mag";
      }
      getToDay($ndays);
      catEq("$ndays","$ymd","$eqfile","$eqpath");
      plotGif(\@eqlist,$eqfile,$periodstr);
      printTable(\@eqlist,$eqfile);

      print "<p>";
      print table( {-align=>'center',-cellpadding=>'1',
                    -cellspacing=>'1', -width=>'90\%'},
          TR(
             td({-align=>'center'},
                strong("Athugið: ")."Ml stærðir þeirra skjálfta sem eru austan við ".
                "-19.45\260 er búið að hækka upp um 0.3"),
          ),
      );
   }else{
      $periodstr="";
#      my $xrange = " \[ \"19991021000000\" : \"19991023000000\" \]";
      plotGif(\@eqlist,$eqfile,$periodstr);
      my $station=getLoc(\@xstn,\@ystn,\@stn,$x,$y);
      if (defined($station)) {
          $ndays=1;
          my $xrange = "";
          getTremData($station,$ndays);
          if ( $stndata ) {
             pltTremGif(\$stndata,\$xrange,\$pltstr,$station);
             print table( {-align=>'center',-cellpadding=>'1',
                       -cellspacing=>'1', -width=>'60\%'},
                TR(
                    td({-align=>'center'},
                       a({-href=>'/ja/jar_inn/myrdalsj.html'},"\[Til baka\]")),
                    td({-align=>'center'},
                       a({-href=>'http://www.vegag.is/faerd/linurit/st029.html'},
                              "\[Veður undir Eyjafjöllum\]")),
                    td({-align=>'center'},
                       a({-href=>'http://www.vegag.is/faerd/linurit/st006.html'},
                              "\[Veður á Mýrdalssandi\]")),
                ),
             );
          }else{
             print table( {-align=>'center',-cellpadding=>'1',
                    -cellspacing=>'1', -width=>'90\%'},
                TR(
                   td({-align=>'center'},
                     strong("Engin óróagögn til fyrir $station")),
                ),
             );
          }
      }
   }

   print "<hr>";

   


}
printTail();

print $q->end_html;

##################### Subroutines #####################

sub printForm {
  print $q->start_form(-name=>'form1'),
   table( {-align=>'center',-cellpadding=>'1',
           -cellspacing=>'1', -border=>'',-width=>'60\%'},
      TR(
         th({-align=>'CENTER',-valign=>'BOTTOM',-colspan=>'3',-bgcolor=>'blue'},
            [font({-size=>"+1",-color=>"white"},
             "Skjálftavirkni undir Mýrdals- og Eyjafjallajökli")]),
      ),
      TR(th({-valign=>'BOTTOM',-bgcolor=>'F0F0F0'},
        ['Sjálfvirk/Handvirk','Dagafjöldi','']),
      ),
      TR(
         td({-align=>'center'},
            $q->popup_menu(-name=>'loctype',
                       -value=>\@loctype,
                       -valign=>'top',
                       -default=>'auto')),
         td({-align=>'center'},
            $q->popup_menu(-name=>'ndays',
                      -value=>\@ndays,
                      -override=>0,
                      -valign=>'top',
                      -default=>'2')),
         td({-align=>'center'},
            $q->submit(-name=>"submit",
                       -value=>' Plotta')),
      ),
   ),
   end_form;
}

sub getToDay {
   my ($n)=@_;
   $n=$n-1;
   my $year=strftime("%y",gmtime(time));
   my $month=strftime("%m",gmtime(time));
   my $day=strftime("%d",gmtime(time));

   my $year0=strftime("%y",gmtime(time-$n*86400));
   my $month0=strftime("%m",gmtime(time-$n*86400));
   my $day0=strftime("%d",gmtime(time-$n*86400));

   my $Year0=$year0+1900;
   my $Year=$year+1900;

   $periodstr="$Year0-$month0-$day0 til $Year-$month-$day";
#   print h4({-align=>"center"},"$year0-$month0-$day0 til $year-$month-$day");
   $ymd="$year $month $day";

   return $ymd,$periodstr; 
}

sub catEq {
   my ($ndays,$yymmdd,$eqfile,$eqpath) = @_;
   my $i=0;
   @eqlist=();
   $ENV{'EQPATH'} = "$eqpath";
   open (MAG,CATEQ." -n $ndays -d $yymmdd $eqfile |") || 
         die "Can not open $eqfile: ($!)";
   while (<MAG>) {
     chomp;
     $_=~s/^\s+//g;
     unless ( /cannot/ ) {
        my ($nr,$date,$time,$lat,$lon,$junk)=split;
        if ( $lon >= -20.0 && $lon <= -18.5 &&
             $lat >= 63.35 && $lat <= 63.85 ) { 
            $eqlist[$i]=$_;
            $i++;
        }
     }
   }
   close(MAG);
   return @eqlist;
}

sub getTremData {
    my ($stn,$numdays)= @_;
    my $contents="";
    my @comp= ('Z 0.5-1.0 Hz', 'N', 'E',
               'Z 1.0-2.0 Hz','N','E',
               'Z 2.0-4.0 Hz','N','E'); 
    my $using="";
    my $i;
    $stndata="";

#    print "$stn $numdays\n";
 
    for $i ( 0,3,6 ) {
#       print "$i\n";
       my $gettremstr=" -s$stn -b$numdays -c$i";
       local *F;
       open(F,GETTREM."$gettremstr"."|" ) ||  die "Shit";
       local $/ = undef;
       $contents = <F>;
       close F;
       if ($contents) {
          $stndata .= "$contents"."e\n";
          $using .= " '-' using 1:2 t \'$stn $comp[$i]\' with line,";
       }
    }
    chop($using);
    $pltstr="plot "."$using";
#    print "$stndata";
    return $stndata,$pltstr;
}


sub printTable {
   my ($r_eqlist,$eqfile) = @_;

   my @colhead0= qw/Dags. Tími Breidd Lengd Dýpi Mw Ml/;
   my @colhead1= qw/Dags. Tími Breidd Lengd Dýpi Ml Gæði/;
   my @colhead=();

   if ( $eqfile eq 'aut.mag' ) {
      @colhead=@colhead1;
   }else{
      @colhead=@colhead0;
   }
   
   my $eq;
   my @rows=();
   my @data;
   my @data1;
   foreach $eq (@$r_eqlist) {
      @data = split(/\s+/,$eq);
      if ( $data[4] > -19.45 && $eqfile eq 'aut.mag' ) {
         $data[6]=sprintf("%4.1f",$data[6]+0.3);
      } 
      if ( $data[4] > -19.45 && $eqfile eq 'lib.mag' ) {
         $data[7]=sprintf("%5.2f",$data[7]+0.3);
      }
      @data1=@data[ 1 .. 7 ];
      push(@rows,td({-align=>'center'},\@data1));
   }

   @rows= reverse (@rows);

   print table({-align=>'center',-cellpadding=>'1',
                -cellspacing=>'1', -border=>'',-width=>'60\%'},
              TR([th({-bgcolor=>'F0F0F0'},\@colhead),@rows])
         );

}


sub plotGif {
   my ($r_eqlist,$eqfile,$periodstr)=@_; 
   my ($gifwidth, $gifheight) = imgsize("/heim/gg/www/sil/images/me.gif");
   my $lon0=-20.0;
   my $lon1=-18.5;
   my $lat0=63.35;
   my $lat1=63.85;
   my $giffile="m_$$.gif";

   open(GIF,"/heim/gg/www/sil/images/me.gif") || die "Shit";
      my $im = newFromGif GD::Image("GIF") || die "Shit";
   close GIF;

   open(GIFOUT,">$giffile") || die "Shit";

   my $white=$im->colorAllocate(255,255,255);
   my $red=$im->colorAllocate(255,0,0);
   my $black=$im->colorAllocate(0,0,0);

   $im->transparent($white);
   $im->interlaced('true');

   my $eq;
   my $size;
   my ($nr,$date,$time,$lat,$lon,$dep,$mw,$ml,$q,$junk);
   foreach $eq (@$r_eqlist) {
      if ( $eqfile eq "aut.mag" ) {
         ($nr,$date,$time,$lat,$lon,$dep,$ml,$q,$junk)=split(/\s+/,$eq);
         if ( $lon > -19.45 ) { $ml=$ml+0.3;}
      }else{
         ($nr,$date,$time,$lat,$lon,$dep,$mw,$ml,$junk)=split(/\s+/,$eq);
      }
      if ( $lon > -19.45 ) { $ml=$ml+0.3;}
      my $x=xInt(($gifwidth-1)*($lon-$lon0)/($lon1-$lon0));
      my $y=xInt(($gifheight-1)*($lat1-$lat)/($lat1-$lat0));

      if ( $ml > 0 ) {
         $size=xInt(4*$ml+3);
      }else{
         $size=2;
      }
      $im->arc($x,$y,$size,$size,0,360,$red);
   }
   $im->string(gdSmallFont,20,335,"$periodstr",$black);

   binmode STDOUT;
   print GIFOUT $im->gif;
   close GIFOUT;

   if ( -s $giffile ) {
       my $q1 = new CGI; 
       print $q1->start_form(-name=>'form2'),
          table( {-align=>'center',-cellpadding=>'1',
                     -cellspacing=>'1', -border=>'',-width=>'60\%'},
             TR(
                 td({-align=>'center'},
                    image_button( -name=>'SIL',
                                  -alt=>'Mýrdals- og Eyjafjallajökull',
                                  -border=>'0',
                                  -src=>"$giffile",
                                  -width=>568,
                                  -height=>426)),
             ),
          ),
       end_form;
   }
}

sub pltTremGif {
   my ($r_allstndata, $r_xrange, $r_pltstr,$stn) = @_;
   my $giftremfile="m_t$$.gif";
   my %stn = ( mid => 'Mið-Mörk',
               skh => 'Skammadalshóli',
               hvo => 'Lágu Hvolum',
               snb => 'Snæbýli' ); 
 
   open (GP,'|'.GNUPLOT) || die "Shit";
   print GP "set xdata time\n";
   print GP "set timefmt \"\%Y\%m\%d\%H\%M\%S\"\n";
   print GP "set encoding iso_8859_1\n";
   print GP "set terminal gif transparent interlace small size 560,400\n";
   print GP "set out \'$giftremfile\'\n";
   print GP "set grid\n";
   print GP "set key right\n";
   print GP "set format x \"\%y-\%m-\%d\\n\%H:\%M\"\n";
#   print GP "set xrange"."$$r_xrange\n";
 
   if ( $stn eq "skh" ) {
       print GP "set yrange \[ 0 \: 60 \]\n"; 
   }else{
       print GP "set yrange \[ 0 \: 40 \]\n"; 
   }
 
   print GP "$$r_pltstr"."\n $$r_allstndata \n";
   close(GP);
 
   if ( -s $giftremfile ) {
       print table( {-align=>'center',-border=>'',-width=>'60\%'},
          TR(
             th({-align=>'center',-bgcolor=>'green'},
                 [font({-size=>"+0",-color=>"white"},
                 "Óróaplott á $stn{$stn} ($stn)")]
             ),
          ),
          TR(
             td({-align=>'center'},
                img {-src=>"$giftremfile",-align=>'CENTER',
                   -alt=>"Órói",
                   -width=>'570',-height=>'400'}
             ),
          ),
       );
   }
}
 
sub getLoc {
  my ($r_xstn,$r_ystn,$r_stn,$x,$y)=@_;
  my $radius=15;
  for ( my $i = 0; $i < @$r_stn ; $i++ ) {
     my $dist = int(sqrt(($r_xstn->[$i]-$x)*($r_xstn->[$i]-$x)+
                         ($r_ystn->[$i]-$y)*($r_ystn->[$i]-$y)));
     if ( $dist < $radius ) {
        return $r_stn->[$i];
     }
  }
  print table( {-align=>'center',-cellpadding=>'1',
                -cellspacing=>'1', -width=>'90\%'},
     TR(
        td({-align=>'center'},
           strong("Smelltu á SIL stöð til að fá óróaplott")),
     ),
  );
  return undef;
}

sub xInt {
  my $x;
  ($_[0] >= 0) ? ($x=int($_[0]+0.5)) : ( $x=int($_[0]-0.5));
  return $x;
}

sub printTail {
    print font({-size=>"-1",-color=>"blue"},address("Veðurstofa Íslands, gg\@vedur.is"));
}
