#! /usr/bin/perl

# translating proxy web service script
#
#     MUGL REST request => NDFD REST request => DWML => MUGL
#
# use like: ndfd.cgi?lonlat=-82.35,35.51&var=temp&q=200909010000,200910010000/1,1

use CGI;
use XML::XPath;

#
# get and scrub the lon,lat
#
$lonlat = CGI::param('lonlat');
($lon,$lat) = split(',', $lonlat);
$lon = Scrub($lon);
$lat = Scrub($lat);

#
# get and scrub the name of the variable to fetch
#
$var = Scrub(CGI::param('var'));

#
# get and scrub the REST parameters
#
$q = CGI::param('q');
$q =~ s|^/||;
$q =~ s|/$||;
($daterange,$buffer) = split('/', $q);
($begin,$end)        = split(',', $daterange);
$begin = NdfdDateFormat(ScrubDate($begin));
$end   = NdfdDateFormat(ScrubDate($end));

#
# Construct the url for the ndfd request. See
#     http://www.weather.gov/forecasts/xml/rest.php
# for documentation. Also, see comment at the end
# of this file for list of possible variables.
#
$ndfdurl = "http://www.weather.gov/forecasts/xml/sample_products/browser_interface/ndfdXMLclient.php"
    . "?lat=$lat"
    . "&lon=$lon"
    . "&product=time-series"
    . "&begin=$begin"
    . "&end=$end"
    . "&$var=$var";

#
# make the ndfd request
#
$xmlresponse = `wget -q -O - '$ndfdurl'`;

#
# parse the ndfd response
#
my $xp = XML::XPath->new(xml => $xmlresponse);

#
# save the list of times in an array
#
@times = ();
foreach my $start_valid_time ($xp->find('//data/time-layout/start-valid-time')->get_nodelist){
    push(@times, $start_valid_time->string_value);
}

#
# save the list of values in an array
#
@values = ();
foreach my $value ($xp->find('//parameters/*/value')->get_nodelist){
    push(@values, $value->string_value);
}

#
# send the mugl response
#
print("Content-type: text/xml\n\n");
print("<mugl><data><values>\n");
for ($i=0; $i<=$#times; ++$i) {
    printf("%s,%s\n", MuglDateFormat($times[$i]), $values[$i]);
}
print("</values></data></mugl>\n");

#
# done!
#

#################################################################################

sub MuglDateFormat {
    my $date = shift;
    $year = substr($date, 0, 4);
    $mon  = substr($date, 5, 2);
    $day  = substr($date, 8, 2);
    $hour = substr($date, 11, 2);
    $min  = substr($date, 14, 2);
    $sec  = substr($date, 17, 2);
    return sprintf("%04d%02d%02d%02d%02d",
		   $year, $mon, $day, $hour, $min);
}

sub NdfdDateFormat {
    my $date = shift;
    $year = substr($date, 0, 4);
    $mon  = substr($date, 4, 2);
    $day  = substr($date, 6, 2);
    $hour = substr($date, 8, 2);
    $min  = substr($date, 10, 2);
    $sec  = substr($date, 12, 2);
    return sprintf("%04d-%02d-%02dT%02d:%02d:%02d",
		   $year, $mon, $day, $hour, $min, $sec);
}

sub ScrubDate {
    my $date = shift;
    my $year = substr($date, 0,  4);
    my $mon  = substr($date, 4,  2);
    my $day  = substr($date, 6,  2);
    my $hour = substr($date, 8,  2);
    my $min  = substr($date, 10, 2);
    return sprintf("%04d%02d%02d%02d%02d00",
		   $year, $mon, $day, $hour, $min);
}

sub Scrub {
    my $x = shift;
    $x =~ s/[^A-Za-z0-9_\.-]//g;
    return $x;
}

### NDFD variables:
###
### maxt                    Maximum Temperature
### mint                    Minimum Temperature
### temp                    3 Hourly Temperature
### dew                     Dewpoint Temperature
### appt                    Apparent Temperature
### pop12                   12 Hour Probability of Precipitation
### qpf                     Liquid Precipitation Amount
### snow                    Snowfall Amount
### sky                     Cloud Cover Amount
### rh                      Relative Humidity
### wspd                    Wind Speed
### wdir                    Wind Direction
### wx                      Weather
### icons                   Weather Icons
### waveh                   Wave Height
### incw34                  Probabilistic Tropical Cyclone Wind Speed >34 Knots (Incremental)
### incw50                  Probabilistic Tropical Cyclone Wind Speed >50 Knots (Incremental)
### incw64                  Probabilistic Tropical Cyclone Wind Speed >64 Knots (Incremental)
### cumw34                  Probabilistic Tropical Cyclone Wind Speed >34 Knots (Cumulative)
### cumw50                  Probabilistic Tropical Cyclone Wind Speed >50 Knots (Cumulative)
### cumw64                  Probabilistic Tropical Cyclone Wind Speed >64 Knots (Cumulative)
### wgust                   Wind Gust
### conhazo                 Convective Hazard Outlook
### ptornado                Probability of Tornadoes
### phail                   Probability of Hail
### ptstmwinds              Probability of Damaging Thunderstorm Winds
### pxtornado               Probability of Extreme Tornadoes
### pxhail                  Probability of Extreme Hail
### pxtstmwinds             Probability of Extreme Thunderstorm Winds
### ptotsvrtstm             Probability of Severe Thunderstorms
### pxtotsvrtstm            Probability of Extreme Severe Thunderstorms
### tmpabv14d               Probability of 8- To 14-Day Average Temperature Above Normal
### tmpblw14d               Probability of 8- To 14-Day Average Temperature Below Normal
### tmpabv30d               Probability of One-Month Average Temperature Above Normal
### tmpblw30d               Probability of One-Month Average Temperature Below Normal
### tmpabv90d               Probability of Three-Month Average Temperature Above Normal
### tmpblw90d               Probability of Three-Month Average Temperature Below Normal
### prcpabv14d              Probability of 8- To 14-Day Total Precipitation Above Median
### prcpblw14d              Probability of 8- To 14-Day Total Precipitation Below Median
### prcpabv30d              Probability of One-Month Total Precipitation Above Median
### prcpblw30d              Probability of One-Month Total Precipitation Below Median
### prcpabv90d              Probability of Three-Month Total Precipitation Above Median
### prcpblw90d              Probability of Three-Month Total Precipitation Below Median
### precipa_r               Real-time Mesoscale Analysis Precipitation
### sky_r                   Real-time Mesoscale Analysis GOES Effective Cloud Amount
### td_r                    Real-time Mesoscale Analysis Dewpoint Temperature
### temp_r                  Real-time Mesoscale Analysis Temperature
### wdir_r                  Real-time Mesoscale Analysis Wind Direction
### wwa                     Watches, Warnings, and Advisories
### wspd_r                  Real-time Mesoscale Analysis Wind Speed