#!/usr/bin/perl
####################################################################
# weather.pl
# version 0.1, 2/9/2010
# version 0.1.1 2/10/2010
# Seth D. Galitzer, sgsax@ksu.edu
# Retrieve data from NOAA.gov website and format it for display.
# Uncomment all ## commented lines for debugging.

use strict;
use LWP::Simple;
use XML::Simple;
use Date::Manip;
##use Data::Dumper;

# User variables, change these to suit your location
# See http://www.weather.gov/xml/current_obs/ look up your local station id
my $station_id = "KMHK";
my $zip = 66502;

my $xml;
my $data;

# get the current conditions
# see http://www.weather.gov/xml/current_obs/ to get your own
my $url = "http://www.weather.gov/xml/current_obs/${station_id}.xml";
my $response = get($url);
$xml = new XML::Simple;
$data = $xml->XMLin($response);
##print Dumper($data);

# display current conditions
print "Weather data for $data->{location}\n";
print "$data->{observation_time}\n";
print "Temp: $data->{temp_f} F (Windchill: $data->{windchill_f} F)\n";
print "Current Conditions: $data->{weather}\n";
print "Wind: from the $data->{wind_dir} at $data->{wind_mph} gusting to $data->{wind_gust_mph} MPH\n";
print "Pressure: $data->{pressure_in}\"\tHumidity: $data->{relative_humidity}%\n";

# get forecast data
# see http://www.weather.gov/forecasts/xml/SOAP_server/ndfdXML.htm for building
#   your own data collection URL
my $begin = UnixDate(ParseDate("today midnight"), "%Y-%m-%d\T%H\:%M\:%S");
my $end = UnixDate(ParseDate("tomorrow midnight"), "%Y-%m-%d\T%H\:%M\:%S");
$url = "http://www.weather.gov/forecasts/xml/SOAP_server/ndfdXMLclient.php?whichClient=NDFDgenMultiZipCode&zipCodeList=${zip}&product=glance&begin=${begin}&end=${end}&maxt=TRUE&mint=TRUE&wx=TRUE&Submit=Submit";
$response = get($url);
$data = $xml->XMLin($response);
##print Dumper($data);

# display forecast data
# If you do not get useful data, you may need to adjust your latitude/longitude
#   values.  Try using the values returned when searching for your location
#   from the main NOAA site: http://www.noaa.gov/
print "Forecast: \u$data->{data}->{parameters}->{weather}->{'weather-conditions'}[0]->{value}->{coverage} $data->{data}->{parameters}->{weather}->{'weather-conditions'}[0]->{value}->{intensity} $data->{data}->{parameters}->{weather}->{'weather-conditions'}[0]->{value}->{'weather-type'}\n";
print "High: $data->{data}->{parameters}->{temperature}->{'Daily Maximum Temperature'}->{value} F\tLow: $data->{data}->{parameters}->{temperature}->{'Daily Minimum Temperature'}->{value} F\n";

