#!/usr/bin/perl

# Modified from a script generated from http://openstreetmap.gryph.de/bigmap.cgi/
# permalink for this map: http://openstreetmap.gryph.de/bigmap.cgi?xmin=19582&xmax=19607&ymin=29324&ymax=29337&zoom=16&scale=256&baseurl=http%3A%2F%2Ftile.openstreetmap.org%2Fmapnik
#
#use strict;

use LWP;
use GD;
use Time::Local;



#OK there *has* to be an easier way of doing this
@months = qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec);
@weekDays = qw(Sun Mon Tue Wed Thu Fri Sat Sun);
($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
$year = 1900 + $yearOffset;
$theTime = "$hour:$minute:$second, $weekDays[$dayOfWeek] $months[$month] $dayOfMonth, $year";

print STDERR "Running BigMap for Haiti at ", $theTime, "\n";

#defaults
$labelfilename = "label.gif";
$tileurl = "http://tile.openstreetmap.org/mapnik/";

#get command line args
foreach $argnum (0 .. $#ARGV) {
	$labelfilename=$ARGV[$argnum+1] if ($ARGV[$argnum] eq "--labelfile");
	$tileurl      =$ARGV[$argnum+1] if ($ARGV[$argnum] eq "--tileurl");
}

#prepare big image
my $img = GD::Image->new(6656, 3584, 1);
my $white = $img->colorAllocate(248,248,248);
my $ocean = $img->colorAllocate(181,208,208);
$img->filledRectangle(0,0,6656,3584,$ocean);

#prepare HTTP user agent
my $ua = LWP::UserAgent->new();
$ua->env_proxy;


print STDERR "Commencing tile fetch & stitch. tileurl='", $tileurl, "'\n";

for (my $x=0;$x<26;$x++)
{                                 
    for (my $y=0;$y<14;$y++)
    {
	    $xt=$x+19582;
	    $yt=$y+29324;
	    
	    if (($yt<29329 && $xt<19596) || ($xt>19592 && $xt<19595 && $yt<29332))  {
		    #skip ocean
	    } else {
		    
		$url = sprintf("%s16/%d/%d.png",$tileurl, $xt,$yt);
#		print STDERR $url , "\n";
	        my $resp = $ua->get($url);
	        die $resp->status_line unless $resp->is_success;
	        my $tile = GD::Image->new($resp->content);
	        next if ($tile->width == 1);
			
		$img->copy($tile, $x*256,$y*256,0,0,256,256); #place the tile image within the big image
	    }
    }
}

print STDERR "Done building map.  Adding lable from file '", $labelfilename , "'\n";

open(GIF, $labelfilename) || die;
my $labelimg = newFromGif GD::Image(GIF) || die;
$img->copy($labelimg, 10,10,0,0,726,100);
close GIF;

print STDERR "Done. Printing png to STDOUT\n";

binmode STDOUT;
print $img->png();
