#!/usr/bin/perl

use warnings;

use CGI;

use HTML::HeadParser;
use LWP::UserAgent;
use HTTP::Request::Common qw(GET);
my $cgi=new CGI;
$specificword = $cgi->param('word');
my $ua = new LWP::UserAgent;
$ua->agent("Grumpy " . $ua->agent);
$wordfile="/usr/share/dict/words";



open (WORDFILE,"$wordfile");
srand;
rand($.) < 1 && ($line = $_) while <WORDFILE>;
close(WORDFILE);

chomp($line);

if (defined $specificword) {
   $word = $specificword;
   }
else {
   $word = $line;
   }


if ($word =~ tr/;<>*|`&$\#![]{}:'"//) {
print "Content-type: text/html \n\n";
print "<html><head><title>Error</title></head><body>";
print "<h1>Invalid Word</h1></body></html>";}

else {
 my $url = "http://images.google.com/images?q=$word&btnI=I";

 print "Content-type: text/html \n\n";
 print "<html><head><title>wordimage: $word</title></head><body>";
 print "<h1>$word</h1>";


 my $grab = GET $url;

 my $reply = $ua->request($grab);
 my $html = $reply->content;

 $p = HTML::HeadParser->new;
 $p->parse($html);
 $imageurl = $p->header("title");
 $imageurl =~ s/Google Image Result for//g;
 $imageurl =~ s/^ //;
 $httpimageurl = "http://$imageurl";
 #print "http://$imageurl";

 print "<img src=\"$httpimageurl\"><br>";
 print "<a href=\"$httpimageurl\">$httpimageurl</a><br>";
 print "<a href=\"http://photonhunter.co.uk/cgi-bin/wordimage.pl?word=$word\">http://photonhunter.co.uk/cgi-bin/wordimage.pl?word=$word</a><br>";
 print "Reload for a different wordimage.";
 print "</body></html>";
}
