#!/usr/bin/perl
#
# Copyright (c) 2006-2007 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.
#
#
# This script reports how many different sheets were used for each
#  decade
#
use List::Util qw[min max];
use strict;

foreach my $decade (1900, 1910, 1920, 1930, 1940, 1950, 1960) {
    print "For the ${decade}s\n";

    my $decade_match = substr($decade,0,3)."?";
    my $dir_glob = "*-tiles-$decade_match";
    #print "\tFiles come from $dir_glob\n";

    my %sheets = ();
    my %tiles = ();
    my @files = glob("$dir_glob/tile-*.jpg");

    # Sort the tiles by directory name
    # (If we have two copies of the same tile, we want the newest one)
    @files = sort {
        my ($adate) = ($a =~ /^.*?\-(\d\d\d\d)\//);
        my ($bdate) = ($b =~ /^.*?\-(\d\d\d\d)\//);
        if(!$adate && !$bdate) { return $a cmp $b; }
        if($adate && !$bdate) { return 1; }
        if($bdate && !$adate) { return -1; }
        return $adate <=> $bdate;
    } @files;

    # Process the files into a hash, based on easting and northing
    foreach my $f (@files) {
      $f =~ m/-(\d+)-(\-?\d+)\./;
      my ($x, $y) = ($1 +0, $2 +0);
      $tiles{$x} ||= {};
      $tiles{$x}{$y} = $f;
    }

    # Now see what sheets (directories) we found
    foreach my $x (keys %tiles) {
        foreach my $y (keys %{$tiles{$x}}) {
            my $f = $tiles{$x}{$y};
            my ($dir) = ($f =~ /^(.*?-tiles-\d+)\//);

            unless($sheets{$dir}) {
                #print "$dir\n";
                $sheets{$dir} = $dir;
            }
        }
    }

    # Summarise
    my @s = keys %sheets;
    print "\t".(scalar @s)." sheet directories present\n";
}
exit;
