#!/usr/bin/perl -w

use strict;

# might need changes for the server
my $newtilepath = "/mnt/agami/openstreetmap/tah/Tiles/";
my $legacytilepath = "/mnt/agami/openstreetmap/tah/Tiles/";
my $oceans_db_file = "/var/www/tah/Tiles/oceantiles_12.dat";
my $layer = "tile";

sub tiletype { # tells type (land/see) of tile based on oceantiles.dat
    # ripped from lookup_handler in close-areas.pl in the T@h client
    my ($x, $y) = @_;
    my $tilex = $x*(2**12);
    my $tiley = $y*(2**12);
    my $tileoffset = ($tiley * (2**12)) + $tilex;
    my $fh;
    open($fh, "<", $oceans_db_file) or die "Can't open oceantiles.dat\n";
    seek $fh, int($tileoffset / 4), 0;
    my $buffer;
    read $fh, $buffer, 1;
    $buffer = substr( $buffer."\0", 0, 1 );
    $buffer = unpack "B*", $buffer;
    my $str = substr( $buffer, 2*($tileoffset % 4), 2 );
    close($fh);

    # $str eq "00" => unknown (not yet checked)
    # $str eq "01" => known land
    # $str eq "10" => known sea
    # $str eq "11" => known edge tile

    return $str;
}

sub is_legacy { # tells if tile is in legacy format
    my ($x, $y) = @_;
    my $filename = sprintf("%s/%s_%d/%04i/%i_%i", $legacytilepath, $layer, 12, $x, $x, $y);
    if ( -e $filename) {
        return 1;
    } else {
        return 0;
    }
}

sub is_new { # tells if tile is in new (non-legacy) format
    my ($x, $y) = @_;
    my $filename = sprintf("%s/%s/%02d/%03d/%03d/%03d/%03d.png", $newtilepath, $layer, 12, ($x/1000), ($x%1000), ($y/1000), ($y%1000));
    if ( -e $filename) {
        return 1;
    } else {
        return 0;
    }
}

#main
my $x;                # coords for the loop
my $y;
my $count_new = 0;    # count tiles in new format
my $count_legacy = 0; # count found legacy tiles
my $type;             # type according to oceantiles.dat

for($x = 0; $x < 2**12; $x++) {
    for($y = 0; $y < 2*12; $y++) {
        if(tiletype($x, $y) == "10") { # only look at sea tiles
            # Check for legacy format
            if(is_legacy($x, $y)) {
                $count_legacy++;
                if($count_legacy < 10) {
                    print "Tile x=$x, y=$y found to be in legacy format\n";
                }
            # Check for tiles in new format
            } elsif (is_new($x, $y)) {
                $count_new++;
                if($count_new < 10) {
                    print "Tile x=$x, y=$y found to be in new format\n";
                }
            # Should not happen AFAIK
            } else {
                print "Tile x=$x, y=$y found to be in unknown format\n";
                exit(1);
            }
        }
        # Seen enough to tell that the script works
        if(($count_legacy > 10) && ($count_new > 10)) {
            exit(0);
        }
    }
}
