#!/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=604&xmax=631&ymin=1216&ymax=1255&zoom=11&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(7168, 10240, 1);
my $white = $img->colorAllocate(248,248,248);
my $ocean = $img->colorAllocate(181,208,208);
$img->filledRectangle(0,0,7168,10240,$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<28;$x++)
{
    for (my $y=0;$y<40;$y++)
    {
	    $xt=$x+604;
	    $yt=$y+1216;
	    
	    if (($yt<1223 && $xt<616) || ($yt<1229 && $xt<615) || ($yt<1234 && $xt<614) || ($yt<1237 && $xt<613)  || ($yt<1247 && $xt<609)  || ($yt<1250 && $xt<607)  )  {
		    #skip ocean
	    } else {
		    
		$url = sprintf("%s11/%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();
