#!/usr/bin/perl
####################################################################
# wunderground.pl
# version 0.1, 2/10/2010
# Seth D. Galitzer, sgsax@ksu.edu
# Retrieve data from wunderground.com website and format it for display.
# User can optionally pass in location as parameter (zip or airport code).
# Uncomment all ## commented lines for debugging.

use XML::Simple;
use LWP::Simple;
use URI::Escape;
##use Data::Dumper;

# User variable, change this to suit your location
my $location = 66502;
# Or just override with commandline parameter
if ($ARGV[0] ne "") { $location = $ARGV[0]; }

# format location string for passing to URL
$location = uri_escape($location);

# get the current conditions
my $output_current = get("http:\/\/api.wunderground.com\/auto\/wui\/geo\/WXCurrentObXML\/index.xml?query=$location");
# get forecast data
my $output_forecast = get("http:\/\/api.wunderground.com\/auto\/wui\/geo\/ForecastXML\/index.xml?query=$location");

if (not defined $output_current or not defined $output_forecast) {
    print "Error grabbing weather information :-(\n";
    exit;
}

# parse retrieved data and dump XML to hash reference
my $xml = new XML::Simple;
my $data_current = $xml->XMLin($output_current);
my $data_forecast = $xml->XMLin($output_forecast);
##print Dumper($data_current);
##print Dumper($data_forecast);

if ($data_current->{display_location}->{full} eq ", ") {
    print "Invalid location code: $location\n";
    exit
}

# display data
print "Current weather for $data_current->{display_location}->{full}\n";
print "$data_current->{observation_time}\n";
print "$data_current->{weather}, Temp: $data_current->{temp_f},";
if ($data_current->{heat_index_f} ne 'NA') {
    print " Heat Index: $data_current->{heat_index_f} F\n";
} else {
    print " Wind Chill: $data_current->{windchill_f} F\n";
};
print "Humidity: $data_current->{relative_humidity}, Pressure: $data_current->{pressure_in}\"\n";
print "Wind: $data_current->{wind_dir} $data_current->{wind_mph}mph\n";

print "Forecast: $data_forecast->{simpleforecast}->{forecastday}[1]->{conditions}\n";
print "High: $data_forecast->{simpleforecast}->{forecastday}[1]->{high}->{fahrenheit} F,";
print "$weather Low: $data_forecast->{simpleforecast}->{forecastday}[1]->{low}->{fahrenheit} F\n";
