#!/usr/bin/perl

# vzaca.pl (Virtual Zaca) (C) 2002 Angel Ortega <angel@triptico.com>
#
# Takes one user's messages from an mbox and
# returns another one mangled using the Markov algorithm.
#
# This software is covered by the GPL license. NO WARRANTY.
#
# Version 0.1

use locale;

$wanted = shift(@ARGV);
$wanted ||= "batalla";

$w1 = $w2 = "#";

sub store_word { push(@{$words{"${_[0]}-${_[1]}"}}, $_[2]); }
sub rotate_words { (${$_[0]}, ${$_[1]}) = (${$_[1]},$_[2]); }
sub random_word { ${$words{$_[0]}}[rand scalar(@{$words{$_[0]}})]; }

sub store_and_rotate { store_word(${$_[0]}, ${$_[1]},$_[2]);
	rotate_words($_[0], $_[1], $_[2]); }

while(<>)
{
	chop;

	unless(/^From\s+/ .. /^$/)
	{
		next unless $store;

		foreach (split(/[^\w\d\.\,\:\;\'\"\(\)\-\@\!\?\Ą\ż]+/))
		{
			store_and_rotate(\$w1, \$w2, $_);
		}
	}
	else
	{
		if(/^From:\s+/)
		{
			if($store)
			{
				store_and_rotate(\$w1, \$w2, "#");
				store_and_rotate(\$w1, \$w2, "#");
			}

			$store = (/${wanted}/i);
		}
	}
}

exit(0) unless scalar(keys(%words));

$w1 = "#";
$w2 = random_word("#-#");

while(not ($w1 eq "#" and $w2 eq "#"))
{
	my $w3 = random_word("$w1-$w2");

	if($w3 =~ /^[-_][-_]+$/)
	{ print "\n$w3\n" }
	else { print "$w3 "; }

	rotate_words(\$w1, \$w2, $w3);
}
