package Map;

use Astar;

use Data::Dumper;
@map=();
@scouts=(); # FORMAT : array of arrayrefs, each arrayref has 3 items : [0] = path, [1] = X coord, [2] = Y coord.
@lady_pos=();
@tv_pos=();

@danger=();

sub load
{
	my($file, $scouts) = @_;
	open F, $file or return IO_ERROR;
	
	my($i,$j)=(0,0);
	my(@row)=();
	@dimensions=split / /,<F>;
	chomp $dimensions[1];
	while(<F>)
	{
		chomp;
		s/\@/\./g unless $scouts; # ignore scouts unless we want them
		@row=();
		$i=0;
		while($i<length($_))
		{
			if(substr($_,$i,1) eq "@")
			{
				$j=$i+1;
				while(1)
				{
					my($l)=substr($_,$j,1);
					printf "pos %d, char '%s'\n",$j,$l;
					last unless ($l eq "<") || ($l eq ">") || ($l eq "^") || ($l eq "v");
					$j++;
				}
				push @row, scalar @scouts; # give the scout a number
				push @scouts, [substr($_,$i+1,($j-$i-1)), $i, scalar @map];
				substr($_,$i,($j-$i-1),"");
			}
			elsif(substr($_,$i,1) eq "&")
			{
				@lady_pos=($i,scalar @map);
				push @row,".";
			}
			else
			{
				@tv_pos=($i, scalar @map) if substr($_,$i,1) eq "#";
				push @row, substr($_,$i,1);
			}
			$i++;
		}
		push @map, [@row];		
	}
	close F;

	# Endangered squares.
	my($tempx,$tempy);
	my(@path)=();
	for($i=0;$i<@scouts;$i++)
	{
		@path=();
		$tempx=$scouts[$i]->[1];
		$tempy=$scouts[$i]->[2];
		push @danger, [$tempx,$tempy];
		push @path, [$tempx,$tempy];
		map
		{
			$tempy-- if $_ eq "^";
			$tempy++ if $_ eq "v";
			$tempx-- if $_ eq "<";
			$tempx++ if $_ eq ">";
			push @danger, [$tempx,$tempy];
			push @path, [$tempx,$tempy];
		} split //,$scouts[$i]->[0];
		pop @path;
		$scouts[$i]=[@path];
	}
}

sub draw
{
	my($turn)=@_;
	my(@lady)=($Astar::path[$turn]->[0], $Astar::path[$turn]->[1]);
	my(@scopos)=();
	my($i,$j,$k)=(0,0);
	for($i=0;$i<$dimensions[1];$i++)
	{
		for($j=0;$j<$dimensions[0];$j++)
		{
			if(($i==$lady[1]) && ($j==$lady[0]))
			{
				print "&";
			}
			else
			{
				print $Map::map[$i]->[$j];
			}
		}
		print "\n";
	}
}


42;
