#!/usr/local/bin/perl
#
# Autofeed: generate Chainsaw-compatible commands to move food from an excess
# food (and mobility) sector to sectors that need it.
#
# Usage: set a (single) warehouse or other distribution point to territory
# 98, do a dump of an area contiguous to it into file "dump", and put the
# output of "ver" in file "ver"... then say "autofeed".
#
# Only the last-noticed territory 98 sector is used for the moves.
#
# Jim Gillogly, 9 Jan 94

open(ver, "ver")  || die("Can't open the version file \"ver\".\n");
while (<ver>)
{
	$fcrate = $2 / $1 if /^(\S*) civilians will harvest (\S*) /;
	$obrate = $2 / $1 if /^(\S*) civilians.*birth to (\S*) /;
	$uwbrate = $2 / $1 if /^(\S*) uncomp.*birth to (\S*) /;
	$eatrate = $2 / $1 if / (\S*) people eat (\S*) /;
	$babyeat = $2 / $1 if /^(\S*) babies eat (\S*) /;
	$fgrate = $1 if /can grow (\S*) /;
	$etu = $1 if /consists of (\S*) empire/;
}
close(ver);

open(foo, "dump") || die("Can't open the dump file \"dump\".\n");

$n = 0;

<foo>;  # dump # */
<foo>;  # date
<foo>;  # DUMP SECTOR
<foo>;  # header (we really ought to read this to see where the fields are)

$wx = $wy = 99999;

while (<foo>)
{
	last if /sectors/;

	($x[$n], $y[$n], $fert[$n], $work[$n],
	   $terr[$n], $civ[$n], $mil[$n], $uw[$n], $food[$n]) =

#           x      y  ds sds ef mb  *  off min gld fert  ocn ura work  avl terr   civ   mil   uw   food
	/^(\S+) (\S+) \S \S \S+ \S+ \S \S+ \S+ \S+ (\S+) \S+ \S+ (\S+) \S+ (\S+) (\S+) (\S+) (\S+) (\S+) /;

	if ($terr[$n] == 98)
	{
#               print "Distribution centre is $x[$n],$y[$n]\n";
		$wx = $x[$n];
		$wy = $y[$n];
	}
	$n++;
}
close(foo);

$wx != 99999 || die("No distribution centre (territory 98) specified.\n");

for ($i = 0; $i < $n; $i++)
{
	next if ($x[$i] == $wx) && ($y[$i] == $wy);

	$oldfood = $food[$i];
	$dd = $etu * $fert[$i] * $fgrate / 100;
	$dtemp = $work[$i] * $fcrate;
	$dd = $dtemp if ($dtemp < $dd);
	$foodtmp = $food[$i] + $dd;
	$dd = $etu * ($civ[$i] + $mil[$i] + $uw[$i]) * $eatrate;

	$food = $foodtmp - $dd;
	$q = $etu * $civ[$i] * $obrate;

	if ($q > $food / (2 * $babyeat))
	{
		$need = 5 + $q * 2 * $babyeat - $food;
		printf "mov f $wx,$wy %d $x[$i],$y[$i]\n", $need;
	}
}
