#!/usr/bin/perl
# 
# Copyright (c) 2006 David Sheldon and Nick Burch
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
#
# Takes a directory full of tile images, and assembles them back into a
#  single large image.
# Normally run against a map tiles directory, eg 107-tiles-1947

use strict;
use Image::Magick;

# How big an image do we want?
my @files = glob("tile-*.jpg");
my @eastings  = sort map { /^tile-(\d+)-\d+\.jpg$/ } @files;
my @northings = sort map { /^tile-\d+-(\d+)\.jpg$/ } @files;
unless(@files) {
	die("Failed to find files of the form <tile-nnn-nnn.jpg> in the current directory\n");
}

my $min_easting = $eastings[0];
my $max_easting = $eastings[-1];
my $min_northing = $northings[0];
my $max_northing = $northings[-1];

my $num_easting = $max_easting - $min_easting + 1;
my $num_northing = $max_northing - $min_northing + 1;

my $size_x = $num_easting * 125;
my $size_y = $num_northing * 125;

# Start to assemble
my $out = Image::Magick->new(size => $size_x."x".$size_y);
$out ->ReadImage('xc:white');

my $count = 0;
foreach my $file (@files) {
	my ($e,$n) = ($file =~ /^tile-(\d+)-(\d+)\.jpg$/);
	my $rel_e = $e - $min_easting;
	my $rel_n = $n - $min_northing;
	my $bl_x = $rel_e * 125;
	my $bl_y = $rel_n * 125;

	my $in = Image::Magick->new();
	$in->Read($file);
	$in->Flip();
	print $out->Composite(image=>$in, x=>$bl_x, y=>$bl_y); 

	$count++;
	if($count % 100 == 0) {
		print "Done $count files\n";
	}
}
   
$out->Flip();
print $out->Write("jpg:joined.jpg") ;
