#!/usr/bin/perl -w

use strict;

my $is_active;

my ($min_x, $min_y, $min_z) = (-1, -1, -1);
my ($max_x, $max_y, $max_z) = (0, 0, 1);

my $y = 0;
while (<>) {
	chomp;
	my $x = 0;
	for (split //) {
		$is_active->{"$x,$y,0"} = 1
			if $_ eq '#';
		print "Active $x,$y,0\n";
		$x++;
	}
	$max_x = $x;
	$y++;
}
$max_y = $y;

my $iter = 0;
while ($iter < 6) {
	my $new_active;
	my ($new_min_x, $new_min_y, $new_min_z) = ($max_x, $max_y, $max_z);
	my ($new_max_x, $new_max_y, $new_max_z) = ($min_x, $min_y, $min_z);
	print "iter $iter x=$min_x:$max_x, y=$min_y:$max_y, z=$min_z:$max_z\n";
	for my $z ($min_z .. $max_z) {
	for my $y ($min_y .. $max_y) {
	for my $x ($min_x .. $max_x) {
		# print "Trying $x,$y,$z\n";
		my $count = 0;
		for my $neigh (
			[-1, -1, -1], [-1, -1, 0], [-1, -1, 1],
			[-1, 0, -1 ], [-1, 0, 0],  [-1, 0, 1],
			[-1, 1, -1 ], [-1, 1, 0],  [-1, 1, 1],
			[0,  -1, -1], [0,  -1, 0], [0,  -1, 1],
			[0,  0, -1 ],              [0,  0, 1],
			[0,  1, -1 ], [0,  1, 0],  [0,  1, 1],
			[1,  -1, -1], [1,  -1, 0], [1,  -1, 1],
			[1,  0, -1 ], [1,  0, 0],  [1,  0, 1],
			[1,  1, -1 ], [1,  1, 0],  [1,  1, 1],) {
			my ($nx, $ny, $nz) = @$neigh;
			$nx += $x; $ny += $y; $nz += $z;
			$count++ if $is_active->{"$nx,$ny,$nz"};
		}
		# print "$count neighbours\n";
		if (($is_active->{"$x,$y,$z"} && ($count == 2 || $count == 3))
			|| (!$is_active->{"$x,$y,$z"} && $count == 3)) {
			$new_active->{"$x,$y,$z"} = 1;
			# print "new active: $x, $y, $z\n";
			$new_min_x = $x if $x < $new_min_x;
			$new_min_y = $y if $y < $new_min_y;
			$new_min_z = $z if $z < $new_min_z;
			$new_max_x = $x if $x > $new_max_x;
			$new_max_y = $y if $y > $new_max_y;
			$new_max_z = $z if $z > $new_max_z;
		}
	} } }
	$min_x = $new_min_x-1;
	$min_y = $new_min_y-1;
	$min_z = $new_min_z-1;
	$max_x = $new_max_x+1;
	$max_y = $new_max_y+1;
	$max_z = $new_max_z+1;

	$is_active = $new_active;
	$iter++;
}

print "Acive: ", scalar keys %$is_active, "\n";

