#!/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.
#
# Generate the UK-wide thumbnail image, from corners.csv, and other similar
#  bits of magic

#my $mode = "rectangle";
my $mode = "thumb";


use Image::Magick;

my $out = Image::Magick->new(size => '700x700');

$out ->ReadImage('xc:white');
   
open FH, "<corners.csv" or die "Can't open corners $!";

while(<FH>) {
    chomp;
    ($tile, $x, $y) = split /,/, $_;
    my ($x1, $y1) = ($x, $y);
    my ($x2, $y2) = ($x+39, ($y-44));

    print "$x,$y2,$x2,$y\n";

    if (($mode eq "rectangle") || (! -f (glob "${tile}_*.jpg")[0])) {    
       print $out->Draw(primitive => 'rectangle', fill => 'red', points =>"$x1,$y1,$x2,$y2");
    } else {
        if (! -f "thumbs/${tile}.jpg") {
           my $in = Image::Magick->new();
           $in -> Read((glob "${tile}_*.jpg")[0]);
           $in -> Sample("160x180");
           $in -> Write("jpg:thumbs/${tile}.jpg");
        }
        my $in = Image::Magick->new();
        $in -> Read("thumbs/${tile}.jpg");
        $in -> Sample("40x45");
        $in->Flip();
        print $out->Composite(image=>$in, x=>$x1, y=>$y2); 
    }
}

close FH;

$out->Flip();
print $out->Write("jpg:thumbnail.jpg") ;
