#!perl

$txtlen=2000;
$tailsize=3;
$initword="\"Òóð";

srand();

#load word list
while(<STDIN>){
	$_=~/^([^\t]+)\t(\d+)/;
	$words{$1}=$2;
}

#Initialize output string
$out=$initword;

for($l=0;$l<$txtlen;++$l){
# debug
	print STDERR "\nPos:".$l;

	# Take 3(or any number) last chars
	$tail=substr($out,length($out)-$tailsize,$tailsize);
# debug
	print STDERR "\tTail:".$tail;

	# Clean small hash
	undef %t_words;

	# Form small hash selecting all appropriate entries
	foreach $k (keys %words){
		if(substr($k,0,$tailsize) eq $tail){
			$t_words{$k}=$words{$k};
# debug
			print STDERR "\n!$tail\t".$k."\t".$t_words{$k};
		}
	}

	# Markup small hash
	@t_keys=keys %t_words;
	$sum=0;
	for($i=0;$i<@t_keys;++$i){
		$k=$t_keys[$i];
		$step=$t_words{$k};
		$sum+=$step;
		$t_words{$k}=$sum;
# debug
		print STDERR "\n!!$tail\t".$k."\t".$t_words{$k};
	}

	$w='';
	if(@t_keys<2){
#debug
		print STDERR "\nNO POINT";
		$w=$t_keys[0];
	}else{
		# Select random point
		$randpoint=rand($sum);
#debug
		print STDERR "\nPOINT:".$randpoint;

		# Find and apply this point
		for($i=0;$i<@t_keys;++$i){
			$k=$t_keys[$i];
			if( $randpoint<=$t_words{$k} ){
				$w=$k;
				$i=@t_keys+1;
			}
		}
	}
	$sw=substr($w, $tailsize, length($w)-$tailsize);
	print $sw;
	$out.=$sw;
}
