#!/usr/bin/perl

use strict;
use warnings;

use lib '/usr/local/lib/mpmasql/modules';

use EnhancedGrid;


my @maps;
while (@ARGV) {
	my $el = shift @ARGV;
	if (not $el =~ /^-/) {
		push @maps,$el;
	}
	elsif ($el =~ /^-v/ or $el =~ /^--version/ ) {
		print <<WC2;
mapbymap 1.0
(c)	Christian Troost, Universität Hohenheim, 2016
WC2
}	
			
	elsif ($el =~ /^-h/ or $el =~ /^-\?/ ) {
		print <<HELP;

Reads two raster maps in ESRI ASCII format and lists frequencies for all value combinations.

Usage: mapbymap <filename1>  <filename2> <options>

Options:
	-h or -? 	prints this help and exits
	-v, --version	version information

HELP
	exit 0;
	}
	
	
}



my $fnfst = $maps[1];
my $fnsoils = $maps[0];

my $soilgrid = EnhancedGrid->create_from_ascii($fnsoils);
my $fstgrid = EnhancedGrid->create_from_ascii($fnfst);


$soilgrid->reset_nodata_to(-1);
$fstgrid->reset_nodata_to(-1);
my $table = $soilgrid->tabulate_values_by_grid($fstgrid);

for my $i (sort {$a <=> $b } keys %$table) {
	for my $j (sort {$a <=> $b } keys %{$table->{$i}} ) {

		print join("\t", $i, $j, $table->{$i}->{$j}), "\n";
	}
} 
