#!/usr/bin/perl -w
# webfetch.pl
# Fetch content of a URL and save it to file (without any modification).

use strict;
use LWP::Simple;
use LWP::UserAgent;
use HTTP::Request;
use HTTP::Response;

# ---------------------------------------------------------------------------
# Subroutine to prompt user for variables in the next section

sub ask_user {
  print "$_[0] [$_[1]]: ";
  my $rc = <>;
  chomp $rc;
  if($rc eq "") { $rc = $_[1]; }
  return $rc;
}

my $url = ask_user("URL", "http://egret.psychol.cam.ac.uk/code/index.html");
my $filename = ask_user("Filename", "temp.html");

print "Requesting data via HTTP...\n";
my $browser = new LWP::UserAgent();
my $request = new HTTP::Request('GET', $url);
my $response = $browser->request($request);
if ($response->is_error()) {
  die "Error: %s\n", $response->status_line;
}
my $contents = $response->content();

print "Storing data to disk...\n";
open(OUTFILE, ">$filename");
binmode OUTFILE; # prevent CR/LF translations
print OUTFILE $contents;

print "Done.\n";
