#!/usr/bin/perl

use strict;
use warnings;
use Image::Magick;

sub to_x {
	my $base = shift;
	$base = '0b' . $base . '0' x (19 - length($base));
	$base =~ s/[qt]/0/g;
	$base =~ s/[rs]/1/g;
	return oct($base);
}

sub to_y {
	my $base = shift;
	$base = '0b' . $base . '0' x (19 - length($base));
	$base =~ s/[qr]/0/g;
	$base =~ s/[ts]/1/g;
	return oct($base);
}

$| = 1;

my $top_left = 'trtrsqqrrssr';
my $width = 512;

my $min_y = to_y $top_left;
my $min_x = to_x $top_left;

my @pixels;
for (my $i = 0; $i < $width; $i++) {
	$pixels[$i] = [];
}

sub parse_input {
	while (<>) {
		chomp;
		my $size = 2 ** (19 - length);
		my $x = to_x($_) - $min_x;
		my $y = to_y($_) - $min_y;
		my $xx = $x + $size;
		my $yy = $y + $size;

		# print "$x $y - ${size}x${size}\n";

		for (my $i = $x; $i < $xx; $i++) {
			for (my $j = $y; $j < $yy; $j++) {
				if (defined $pixels[$i][$j]) {
					$pixels[$i][$j]++;
				}
				else {
					$pixels[$i][$j] = 1;
				}
			}
		}
	}
}

sub gen_pixels {
	for (my $i = 0; $i < $width; $i++) {
		for (my $j = 0; $j < $width; $j++) {
			my $color = defined $pixels[$i][$j] ? $pixels[$i][$j] : 0;
			print $color;
		}
	}
}

sub gen_img {
	my $str;
	my $img = Image::Magick->new(
		colorspace => 'RGB',
		depth => 8,
		size => "${width}x${width}",
		verbose => 'True',
		);
	$img->Read('xc:white');

	for (my $i = 0; $i < $width; $i++) {
		for (my $j = 0; $j < $width; $j++) {
			my $color = defined $pixels[$i][$j] ? $pixels[$i][$j] : 0;
			$color = int($color * 255.0 / 8);
			die if $color > 255;
			$str = $img->Set("pixel[$i,$j]" => sprintf("#%2.2x%2.2x%2.2x", $color, $color, $color));
			$str && warn $str;
		}
	}

	$str = $img->Display();
	$str && warn $str;
	return $img;
}

parse_input;
my $img = gen_img;
$img->write('gmap-coverage.png');

# qr
# ts
# 
# ab 
# 7890
#  456
#  123
# 
# a trtrsqqrrssr + qqqqqqq <--- top-left
# 7 trtrsqqrrsss
# 0 trtrsqrqqtst
# b trtrsqrqqttq
# 9 trtrsqrqqtts
# 8 trtrsqrqqttt
# 4 trtrsqrqtqqq
# 5 trtrsqrqtqqr + qqqqqqq <--- center
# 2 trtrsqrqtqqs
# 1 trtrsqrqtqqt
# 6 trtrsqrqtqrq
# 3 trtrsqrqtqrt + sssssss <--- bottom-right

