#! /usr/bin/perl

require "$ENV{HOME}/share/lib/bcwlib.pl";

$wordreq = 0;
$wordcnt = 999;
$nextreq = 0;
$totaled = 0;

while ($wordreq < $wordcnt) {
	$info  = LoadHttp("http://www.wordcount.org/dbquery.php?toFind=$wordreq&method=SEARCH_BY_INDEX");
	$$info =~ s/^.*\n\s*\n//;
	foreach ($$info =~ m/&(\w+=[^&]+)/g) {
		($key,$val) = m/(\w+)=(\S+)/;
#		print "found: key=$key; val=$val (wordreq=$wordreq; nextreq=$nextreq)\n";
		if ($key =~ m/^word(\d+)$/) {
			$curword = $val;
			$curindx = $1;
		} elsif ($key =~ m/^freq(\d+)$/) {
			die "error: frequency doesn't match word ($1 vs $curindx)\n" unless ($1 eq $curindx);
			$nextreq = $wordreq + int($curindx);
			print "$curword=$val\n";
		} elsif ($key eq "wordFound") {
			die "error: word not found ($val)\n" unless ($val eq "yes");
		} elsif ($key eq "rankOfRequested") {
			die "error: word index mismatch ($val vs $wordreq)\n" if ($val ne $wordreq);
		} elsif ($key eq "totalWords") {
			$wordcnt = $val;
		}
	}
#	last if ($wordreq != 0);
	$wordreq = $nextreq + 1;
	sleep(1);
}
