#!/usr/bin/perl
# Script to emulate a browser for posting to a 
#   CGI program with method="POST".

# It's a good habit to always use the strict module.
use strict;

# Modules with routines for making the browser.
use LWP::UserAgent;
use HTTP::Request::Common;

# Specify the URL of the page to post to.
#my $URLtoPostTo = "http://flowto.info/cgi-bin/Dump.cgi";
#my $URLtoPostTo = "http://www.cryst.ehu.es/rep/sam.html";
my $URLtoPostTo = "http://www.cryst.ehu.es/cgi-bin/cryst/programs/nph-sam";

# If you want to specify a browser name, 
#   do so between the quotation marks. 
#   Otherwise, nothing between the quotes.
my $BrowserName = "Perl script";

# Create the browser that will post the information.
my $Browser = new LWP::UserAgent;
if($BrowserName) { $Browser->agent($BrowserName); }

for(my $i = 1 ; $i <= 230 ; $i++) {
	&Save($i);
}

sub Save
{
	my ($i) = @_;
	
# Specify the information to post, the form field name on 
#   the left of the => symbol and the value on the right.
	my %Fields = (
	   "sg"  => $i,
	   "sam" => "sam",
	);
# As seen above, "@" must be escaped when quoted.

# Post the information to the CGI program.
	my $Page = $Browser->request(POST $URLtoPostTo,\%Fields);

	my $s;
# Print the returned page (or an error message).
#	print "Content-type: text/html\n\n";
	if ($Page->is_success) {
		$s = $Page->content;
#		print $s;
	}
	else { 
		$s = $Page->message;
#		print $Page->message; 
	}
	
	my $OutFile = "$i.html";
	open(OUT, ">$OutFile") or die "$!: Cannot write to [$OutFile].\n";
	print OUT $s;
	close(OUT);
}

# end of script
