#!/usr/bin/perl

use strict;
use warnings;

use lib qw(/usr/local/lib/mpmasql/modules);
use EnhancedGrid;

my $out = "1.diff";
my ($tabulate_diff, $savediff, $list_diff) = (0,0,0);
my @inmaps;

for my $i (@ARGV) {
	if (not $i =~ /^-/) {
		push @inmaps, $i;
	}
	elsif ($i =~ /-O(.+)/) {
		$out = $1;
		$savediff = 1;
	}
	elsif ($i =~ /-t/) {
		$tabulate_diff = 1;
	}
	elsif ($i =~ /-l/) {
		$list_diff = 1;
	}
	elsif ($i =~ /-h/ or $i =~ /-\?/ ) {
		print <<HELP;

Compares two raster maps in ESRI ASCII format.

Usage: mapdiff <filename1> <filename2> <options>

Options:
	-h or -? 	prints this help
	-O<filename>	creates a new map that contains the result of substracting Map 2 from Map 1
	-t		tabulates the frequencies of all differences
	-l		lists all cells that show differences

You should at least specify one option, otherwise mapdiff won't produce any output.
HELP
	exit 0;
	}


}
die "You did not specify two maps!\n" unless $#inmaps >= 1;
print "You specified more than two maps, only the first two will be compared\n" if ($#inmaps > 1);

my $map1 = EnhancedGrid->create_from_ascii($inmaps[0]);
my $map2 = EnhancedGrid->create_from_ascii($inmaps[1]);
my $map0 = $map1->create_copy();
$map1->overlay("diff",$map2);


if ($tabulate_diff) {
	$map1->update_valuetable();
	print "Tabulation of the Diff-Map:\n";
	print "Value\tFrequency\n";
	$map1->print_valuetable();
}
if ($savediff) {
	$map1->save_as_ascii($out);
}

if ($list_diff) {
	my $ncols	= $map1->get_attribute("ncols");
	my $nrows	= $map1->get_attribute("nrows");
	print "List of different cells\n";
	print "X\tY\tMap1\tMap2\tDiff\n";
	for my $j (0..$nrows -1){
		for my $i (0..$ncols-1){
			my $x = $map1->get_cell($i,$j);
			if ($x) {
				print "$i\t$j\t".$map0->get_cell($i,$j)."\t".$map2->get_cell($i,$j)."\t$x\n";
			} 

		}
	

	}

}

