#!/usr/bin/perl
# 
# Copyright (c) 2006 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.
#
# Makes .wld files for NPE tiles

use strict;

my $scale = shift;
if($scale && $scale =~ /^\d+$/ && -d "scaled$scale") {
	# Good
} else {
	print "Use:\n";
	print "   make-scaled-wld.pl <scale>\n";
	print "\nWhere the directory scaled<scale>/ is a child of the current one\n";
	exit;
}

# Files are in:
#   scaled<scale>/<sc easting>/<sc northing>.jpg

# Loop over the scaled eastings
my @eastings = `cd scaled${scale} && find . -maxdepth 1 -type d | grep -v '^.\$' | sed s#./##`;

foreach my $e (@eastings) {
	chomp $e;
	print "Processing scaled${scale}/$e/\n";

	# Get northings
	my @files = `cd scaled${scale}/$e/ && find . -maxdepth 1 -type f -name '*.jpg' | sed s#./##`;
	foreach my $f (@files) {
		chomp $f;
		my ($n) = ($f =~ /^(.*?)\.jpg$/);
		##print "$e - $n - $f\n";

		# Note - Add 1 to northing, as y offset is -ve

		my ($easting, $northing) = ( (($e) * $scale), (($n+1) * $scale) );
		$easting *= 1000;
		$northing *= 1000;

		# Write the .wld file
		open(WLD, "> scaled${scale}/${e}/${n}.wld");

		# Images are 125x125, and cover one grid square at scale 1

		# size of pixel in x direction
		print WLD (1000 * $scale / 125)."\n";

		# rotation term for row - typically zero
		# rotation term for column - typically zero
		print WLD "0.000\n0.000\n";

		# size of pixel in y direction
		print WLD (-1000 * $scale / 125)."\n";

		# x coordinate of centre of upper left pixel in map units
		print WLD "$easting\n";

		# y coordinate of centre of upper left pixel in map units
		print WLD "$northing\n";

		close WLD;
	}
}

