#!/usr/bin/perl -w

use v5.16;

my @map = [ map { chomp; [ split // ] } <> ];

my $min;
my $levels = 0;
while (1) {
	say "After ", ++$min, ":";
	my $count = 0;
	my @nm;
	$levels += 2;
	for my $l (0 .. $levels) {
		say "Depth ", $l - $min;
	for my $y (0 .. 4) {
	for my $x (0 .. 4) {
		my $sum = 0;
		my @pts;
		for my ($dx, $dy) (1, 0, 0, 1, -1, 0, 0, -1) {
			my $nx = $x + $dx;
			my $ny = $y + $dy;
			if ($nx < 0) {
				push @pts, [$l-2, 2, 1]; # L Y X
			} elsif ($ny < 0) {
				push @pts, [$l-2, 1, 2];
			} elsif ($nx > 4) {
				push @pts, [$l-2, 2, 3];
			} elsif ($ny > 4) {
				push @pts, [$l-2, 3, 2];
			} elsif ($nx == 2 && $ny == 2) {
				if ($x == 1) {
					push @pts, [$l, $_, 0] for 0 .. 4;
				} elsif ($y == 1) {
					push @pts, [$l, 0, $_] for 0 .. 4;
				} elsif ($x == 3) {
					push @pts, [$l, $_, 4] for 0 .. 4;
				} elsif ($y == 3) {
					push @pts, [$l, 4, $_] for 0 .. 4;
				}
			} else {
				push @pts, [$l-1, $ny, $nx];
			}
		}
		for my $pt (@pts) {
			my ($nl, $ny, $nx) = @$pt;
			next if $nl < 0 || $nl > $levels-2;
			$sum++ if $map[$nl][$ny][$nx] eq '#';
		}
		if ($x == 2 & $y == 2) {
			$nm[$l][$y][$x] = '?';
		} elsif ($l > 0 && $l <= $levels-1 && $map[$l-1][$y][$x] eq '#') {
			$nm[$l][$y][$x] = $sum == 1 ? '#' : '.';
		} else {
			$nm[$l][$y][$x] = $sum == 1 || $sum == 2 ? '#' : '.';
		}
		print $nm[$l][$y][$x];
		$count++ if $nm[$l][$y][$x] eq '#';
	}
		print "\n";
	}
		print "\n";
	}
	@map = @nm;
	print "==== $count ====\n";
	last if $min >= 200;
}

