#!/usr/bin/perl
#-------------------------------------------------------------------
#	Erzeuge Imagemagick-convert Befehl,
#	der ein Koordinatenraster in eine Karten-Graphik zeichnet.
#
#	Setzt Merkator-Projektion voraus.
#-------------------------------------------------------------------

use strict;
use POSIX;

#-------------------------------------------------------------------
#	Parameter
#-------------------------------------------------------------------

my $INFILE	= "bigmap.jpg";
my $OUTFILE	= "bigmap_with_grid.jpg";

# Image

my $WIDTH	= 512;
my $HEIGHT	= 768;

# BBOX

my $MIN_LON	= -90;
my $MIN_LAT	= -66.51326;
my $MAX_LON	= 90;
my $MAX_LAT	= 85.051129;

# Rasterabstand

my $GRID_LON	= 10;
my $GRID_LAT	= 10;

# Rasterfarbe

my $GRID_COLOR	= "gray";

#-------------------------------------------------------------------
#	Merkator-Projektion
#-------------------------------------------------------------------

sub mercator {
	my ($lat) = @_;
	my $PI = 3.1415926535;
	my $lat_rad = $lat * $PI / 180.0;
	my $lat_mercator = log(tan($PI/4 + $lat_rad/2));
	return $lat_mercator;
}

#-------------------------------------------------------------------
#	Erzeuge Convert-Befehl
#-------------------------------------------------------------------

my @line;

push (@line, "convert");

# Lese Eingabedatei

push (@line, $INFILE);

# Setze Farbe

push (@line, "-fill", $GRID_COLOR);

# Erzeuge senkrechte Linien

my $min = ceil  ($MIN_LON / $GRID_LON);
my $max = floor ($MAX_LON / $GRID_LON);

for (my $i=$min; $i<=$max; $i++) {

	my $lon = $i * $GRID_LON;
	my $x = floor (($lon - $MIN_LON) / ($MAX_LON - $MIN_LON) * $WIDTH);

	push (@line, "-draw", "line $x,0 $x,$HEIGHT");
}

# Erzeuge waagrechte Linien

my $MIN_LAT_M = mercator($MIN_LAT);
my $MAX_LAT_M = mercator($MAX_LAT);

$min = ceil  ($MIN_LAT / $GRID_LAT);
$max = floor ($MAX_LAT / $GRID_LAT);

for (my $i=$min; $i<=$max; $i++) {

	my $lat_m = mercator ($i * $GRID_LAT);
	my $y = floor (($MAX_LAT_M - $lat_m) / ($MAX_LAT_M - $MIN_LAT_M) * $HEIGHT);

	push (@line, "-draw", "line 0,$y $WIDTH,$y");
}

# Schreibe Ausgabedatei

push (@line, $OUTFILE);

#-------------------------------------------------------------------
#	Zeige Convert-Befehl
#-------------------------------------------------------------------

warn join ("\n", @line, "");

#-------------------------------------------------------------------
#	Fuehre Convert-Befehl aus
#-------------------------------------------------------------------

system @line;

exit 0;
