#!/usr/bin/perl
#
# Display ARDEC 5 min data
#
# $Id: $
#
use strict;
use POSIX;
use PGPLOT;
use CGI qw(:cgi-lib);
use DBI;
use Date::Calc qw(:all);
use CGI::Carp qw(fatalsToBrowser);
require "coag_common.pl";
require "common_html.pl";

my $DATADIR="/home/ardec/data";
my $DATAFILE = "$DATADIR/ftc035min.dat";

my @five_min_params =  qw(volt tmean rh vp sr ws wind_vec wind_std pp 
                      st5 st15 gust gusttm gustdir etgage);
my @display =  qw(tmean rh dp vp sr ws wind_vec pp st5 st15 
                  gust gusttm gustdir volt);
my $id = 'ftc03';
my @station_list = ();
my %station_info = ();
my %name; my %mult; my %offset; my %lower; my %upper; my %format;

my @params = qw (tmax tmin pp etr_asce);

rd_param_info('5min', \%name, \%mult, \%offset, 
              \%lower, \%upper, \%format);
rd_station_info(\%station_info, \@station_list);

my %in = ();
my $host = `hostname --fqdn`; chomp $host;

&ReadParse(\%in);

plot() if $in{action} eq 'plot';
simple() if $in{action} eq 'simple';
table() if $in{action} eq '';

exit();

# Subroutines


sub simple
{

    my $dbh = DBI->connect("DBI:mysql:database=Coag;host=localhost",
                           "coag_admin","in2ccdbs",
                           { RaiseError => 1});
    my $query = "SELECT datetime,";
    $query .= join ',', @five_min_params;
    $query .= " FROM ardec_5min ORDER BY datetime DESC LIMIT 25";
    my $sth = $dbh->prepare($query);
    $sth->execute;

    print "Content-type: text/plain\n\n";
    print "    Date  Time  ";
    foreach my $param (@display) {
        my $label = $param;
        $label = 'wd' if $param eq 'wind_vec';
        $label = 'gtime' if $param eq 'gusttm';
        $label = 'gdir' if $param eq 'gustdir';
        printf "%6s", $label;
    }
    print "\n";

    while (my @row = $sth->fetchrow_array()) {
        my %data = ();
        my $datetime = shift(@row); 
        $datetime =~ s/\:00$//;
        my ($date, $time) = split ' ', $datetime;
        foreach my $param (@five_min_params) {
            my $val = shift(@row);
            $data{$param} = $val;
        }
        
        $data{dp} = dewpt($data{tmean}, $data{rh});
        my $gusthr = int($data{gusttm}/60);
        my $gustmn = $data{gusttm} % 60;
        $data{gusttm} = sprintf "%02d:%02d", $gusthr, $gustmn; 
        
        print "$date $time";
        foreach my $param (@display) {
            $data{$param} = $data{$param} * $mult{$param} + $offset{$param}
            unless $param =~ m/gusttm/;
            my $val = sprintf "$format{$param}", $data{$param};
            print $val;
        }
        print "\n";
    }
}


sub table
{
    header("ARDEC Weather Station");

    my ($name, $loc, $lat, $lon, $elev, $windht, $fmt, $active) = 
        split (":", $station_info{$id});

    print "<HR><TABLE border=0>
    <TR><TH align=left>Station:</TD<TD>$name</TD><TR> 
    <TR><TH align=left>Location:</TD<TD>$loc</TD><TR> 
    <TR><TH align=left>Elevation:</TD<TD>$elev</TD><TR> 
    <TR><TH align=left>Longitude:</TD<TD>$lon</TD><TR> 
    <TR><TH align=left>Latitude:</TD<TD>$lat</TD><TR> 
    </TABLE><HR>";

    my $dbh = DBI->connect("DBI:mysql:database=Coag;host=localhost",
                           "coag_admin","in2ccdbs",
                           { RaiseError => 1});
    my $query = "SELECT datetime,";
    $query .= join ',', @five_min_params;
    $query .= " FROM ardec_5min ORDER BY datetime DESC LIMIT 25";
    my $sth = $dbh->prepare($query);
    $sth->execute;

    print "<table border=0>\n";
    print "<CAPTION><EM>ARDEC 5 Minute Data</EM></CAPTION>\n";
    print "<tr><th width=10% align=right>Date</th>\n";
    print "<th width=6% align=right>Time</th>\n";
    foreach my $param (@display) {
        print "<th width=6% align=right>$name{$param}</th>\n";
    }
    print "</tr>\n";
    
    print "<tr><td align=right></td> <td align=right>MST</td> " .
        "<td align=right>&deg;F</td> <td align=right>%</td>" .
        "<td align=right>&deg;F</td>" .
        "<td align=right>mb</td> <td align=right>ly/min</td> " .
        "<td align=right>mph</td> <td align=right>&deg;</td>" .
        "<td align=right>in.</td> <td align=right>&deg;F</td> " .
        "<td align=right>&deg;F</td> <td align=right>mph</td>" .
        "<td align=right>MST</td> <td align=right>&deg;</td> " .
        "<td align=right>volts</td>\n";

    while (my @row = $sth->fetchrow_array()) {
        my %data = ();
        my $datetime = shift(@row); 
        $datetime =~ s/\:00$//;
        my ($date, $time) = split ' ', $datetime;
        foreach my $param (@five_min_params) {
            my $val = shift(@row);
            $data{$param} = $val;
        }
        
        $data{dp} = dewpt($data{tmean}, $data{rh});
        my $gusthr = int($data{gusttm}/60);
        my $gustmn = $data{gusttm} % 60;
        $data{gusttm} = sprintf "%02d:%02d", $gusthr, $gustmn; 
        
        printf "<tr><td align=right>$date</td><td align=right>$time</td>\n";
        foreach my $param (@display) {
            $data{$param} = $data{$param} * $mult{$param} + $offset{$param}
            unless $param =~ m/gusttm/;
            my $val = sprintf "$format{$param}", $data{$param};
            print "<td align=right>$val</td>\n";
        }
        print "</tr>\n";
    }
    print "</table>\n";
    print <<EOD; 
    </td></tr><tr><td colspan=2><p>&nbsp;</p><p><hr><center>
        <a href="http://ccc.atmos.colostate.edu/~ardec/index.pl?action=plot">
        <h3>Plots for last week.</h3></a>
        </td></tr><tr><td colspan=2><center>
        <a href="http://www.colostate.edu/Orgs/ARDEC/index.html">
        <h3>ARDEC Home</h3></a>

        </td></tr><tr><td colspan=2><center><hr>
        <h3>DISCLAIMER</h3>

        Authorized use of this data is limited to the academic, administrative,
        research Colorado State University and its Cooperative and Extension
        facilities.

        Use is NOT authorized for operational or commercial purposes.
        
        The data are provided "as is", and in no event shall the providers be
        liable for any damage or loss due to missing data or misinterpretation
        of its content.
EOD

    footer();
}


sub plot
{
    my $limit = 300;

    header("ARDEC Weather Station");

    my $age = time() - (stat("wxtmp.png"))[9];
    print "Age = $age\n";
    my $ret = 0;
    $ret = system("/home/ardec/public_html/plot_week.pl")
        if $age > $limit;

    print <<EOD;
    <hr width="50%"><img src="wxtmp.png" alt="CoAgMet Home Page">
    <hr width="50%"><img src="wxhum.png" alt="CoAgMet Home Page">
    <hr width="50%"><img src="wxws.png" alt="CoAgMet Home Page">
    <hr width="50%"><img src="wxwd.png" alt="CoAgMet Home Page">
    <hr width="50%"><img src="wxprec.png" alt="CoAgMet Home Page">

    </td></tr><tr><td colspan=2><p>&nbsp;</p><p><hr><center>
    <a href="http://ccc.atmos.colostate.edu/~ardec/index.pl">
    <b>Data table.</b></a>
    </td></tr><tr><td colspan=2><center>
    <a href="http://www.colostate.edu/Orgs/ARDEC/index.html">
    <b>ARDEC Home</b></a>
    <hr>
  </td></tr><tr><td colspan=2><center>
  <h3>DISCLAIMER</h3>

  Authorized use of this data is limited to the academic, administrative,
  research Colorado State University and its Cooperative and Extension
  facilities.

  Use is NOT authorized for operational or commercial purposes.

  The data are provided "as is", and in no event shall the providers be
  liable for any damage or loss due to missing data or misinterpretation
  of its content.
  
EOD

    footer();
}


my $MISSING = -9999;

sub dewpt
{
    my ($t, $rh) = @_;
    my $es = 6.112 * exp(17.67 * $t / ($t + 243.5));
    my $e = $rh * $es;
    my $loge = log($e/6.112) if $e > 0;
    my $dp = 243.5 * $loge/(17.67 - $loge);
}


sub c2f
{
  my($t) = $_[0];
  return ($MISSING) if $t ==  $MISSING;
  (($t)*9.0/5.0 + 32.0);
}
