#!/usr/bin/perl -w
# -*- perl -*-

#
# $Id: simplify_streets,v 1.8 2009/02/06 21:45:01 eserte Exp $
# Author: Slaven Rezic
#
# Copyright (C) 2006 Slaven Rezic. All rights reserved.
# This program is free software; you can redistribute it and/or
# modify it under the same terms as Perl itself.
#
# Mail: slaven@rezic.de
# WWW:  http://www.rezic.de/eserte/
#

use FindBin;
use lib ("$FindBin::RealBin/..",
	 "$FindBin::RealBin/../lib",
	);
use BBBikeTrans;
use Strassen::Core;
use Strassen::Util;
use Getopt::Long;

our $medium_scale = 0.13; # same as in bbbike

my $algorithm = 'naive';
my $tolerance;
my $v;

GetOptions("simplify-coefficient=f" => \$medium_scale,
	   "algorithm=s" => \$algorithm,
	   "tolerance=f" => \$tolerance,
	   "v" => \$v,
	  )
    or die <<EOF;
usage: $0 [-algorithm naive|douglas-peucker]
          [-simplify-coefficient coeff] [-tolerance m]
          [-v] bbdfile

Default is "naive" algorithm. Note that this is really
only suitable (sort-of) for simplifying maps which
should appear on a low-resolution map like overview maps.

-simplify-coefficient is used for the naive algorithm
-tolerance is used for the Douglas-Peucker algorithm.
EOF

my $s = Strassen->new($ARGV[0]); # XXX PreserveComments is sort of buggy, commented out # , PreserveComments => 1);

*create_transpose_subs = \&old_create_transpose_subs_no_int;
create_transpose_subs();

if ($algorithm eq 'naive') {
    naive($s);
} elsif ($algorithm eq 'douglas-peucker' || $algorithm eq 'dp') {
    if (!defined $tolerance) {
	# 1px is ... meters in reality
	my($x1,$y1) = anti_transpose_ls_medium(0,0);
	my($x2,$y2) = anti_transpose_ls_medium(0,1);
	$tolerance = Strassen::Util::strecke([$x1,$y1], [$x2,$y2]);
	warn "Using tolerance=$tolerance...\n" if $v;
    }
    $s->simplify($tolerance);
    $s->write("-");
} else {
    die "Unhandled algorithm <$algorithm>, please try 'naive' or 'douglas-peucker'";
}

sub naive {
    my $s = shift;

    $s->init;
    while() {
	my $ret = $s->next;
	last if !@{ $ret->[Strassen::COORDS] };
	my @new_c;
	my($last_c);
	for my $c (@{ $ret->[Strassen::COORDS] }) {
	    my($x,$y) = split/,/,$c;
	    my($new_c) = join(",", map { int } anti_transpose_ls_medium(map { int } transpose_ls_medium($x,$y)));
	    if (!defined $last_c || $new_c ne $last_c) {
		push @new_c, $new_c;
	    }
	    $last_c = $new_c;
	}
	$ret->[Strassen::COORDS] = \@new_c;
	print Strassen::arr2line2($ret), "\n";
    }
}

__END__
