#!/usr/bin/perl -w

# $Id: merge.pl,v 1.3 2008-09-15 20:19:49 semik Exp $
#
# This code is public domain.
#
# Autor: Jan Tomasek <jan@tomasek.cz>
# Web: http://www.tomasek.cz/software/TrekBuddy-turisticka-navigace/index.html


use strict;
use Getopt::Std;
use Image::Magick;
use Data::Dumper;
use List::Util qw(min max);

$|=1;

my %opt;
getopts("d:q:",\%opt);
my $quality = $opt{'q'} || 100;
my $dir = $opt{'d'} || do {
  die "Usage: $0 -d <directory-with-map-titles> [-q <quality>]\n";
};

opendir(DIR, "$dir/set") or die "Directory '$dir' doesn't contain 'set' directory with titles: $!";
print "Loading dir: $dir\n";
my @files = grep { /\.png$/ && -f "$dir/set/$_" } readdir(DIR);
close(DIR);

if (@files == 0) {
  die "Directory '$dir/set' is empty?!\n"
};

my %files;
foreach my $file (@files) {
  if ($file =~ /(\d+)_(\d+).png$/) {
    $files{$2}{$1} = $file;
  } else {
    die "Can't parse filename: $file";
  };
};

my $err;

# get max width & height
my $height_max = max(keys %files);
my $width_max = max(keys %{$files{$height_max}});
my $im = new Image::Magick;
$err = $im->Read("$dir/set/".$files{$height_max}{$width_max});
die "$err\n" if ($err);

$height_max += $im->Get('height');
$width_max += $im->Get('width');

my $mim = Image::Magick->new();
$mim->Set(size => $width_max."x".$height_max);
$mim->ReadImage('xc:white');

# Compose image
my $counter;
foreach my $y (sort {$a <=> $b} keys %files) {
  foreach my $x (sort {$a <=> $b} keys %{$files{$y}}) {
    $counter++;
    printf "Loading files: %3d%%\r", 100.0*$counter/scalar(@files);
    my $file = "$dir/set/".$files{$y}{$x};
    my $im = new Image::Magick;
    $err = $im->Read($file);
    die "$err\n" if ($err);

    $mim->Composite(image => $im,
		    x => $x,
		    y => $y);
  };
};
printf "Loading files: done\n", 100.0*$counter/scalar(@files);

print "Writing $dir.png";
$mim->set(quality => $quality);
$err = $mim->Write("$dir.png");
die "$err\n" if ($err);
print "\n";
