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

#
# Author: Slaven Rezic
#
# Copyright (C) 2008,2009,2023 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 strict;
use warnings;

use FindBin;
use lib ("$FindBin::RealBin/..",
	 "$FindBin::RealBin/../lib",
	);

use Strassen::Core;
use Getopt::Long;

my @ignore_files = 
    qw(Berlin.coords.data Potsdam.coords.data kneipen-info add_str
       meta\..* temp_blockings opensearch.streetnames 
       GNUmakefile Makefile.* README .*\.yml
       add_plaetze ampelschaltung ampelschaltung-orig
       str_cont_ausnahme umsteigebhf
     );

my $debug = 1;
my $help;
my $dir;
my $stdignore;

sub usage () {
    die <<EOF;
usage: $0 [--debug=0..2] [--stdignore] [--help] bbdfiles ...
EOF
}

GetOptions(
           "debug=i" => \$debug,
           "help" => \$help,
           "dir=s" => \$dir,
	   "stdignore!" => \$stdignore,
          )
    or usage;

push(@ARGV, glob("$dir/*")) if $dir;

usage if ($help || !@ARGV);

my $max_length;
for (@ARGV) {
    $max_length = length $_ if !defined $max_length || length $_ > $max_length;
}

my $errors = 0;
FILE: for my $file (@ARGV) {
    my $file_label = sprintf "%-${max_length}s", "$file:";
    if (-d $file) {
	print "${file_label}directory, ignoring...\n" if $debug >= 2;
	next;
    }

    if ($stdignore && grep { $file =~ $_ } @ignore_files) {
	print "${file_label}in stdignore, skipping...\n" if $debug >= 2;
	next;
    }

    my $s = Strassen->new($file);
    $s->init;
    while (1) {
	my $r = $s->next;
	if (ref $r->[Strassen::COORDS] ne 'ARRAY') {
	    chomp(my $line = $s->{Data}[$s->{Pos}]);
	    warn "${file_label}wrongly formatted line $s->{Pos}: '$line'\n";
	    $errors++;
	    next FILE;
	}
	my @c = @{ $r->[Strassen::COORDS] };
	if (!@c) {
	    if ($s->pos != @{ $s->data }) {
		warn "${file_label}Mismatch in position " . $s->pos . " != " . @{ $s->data } . "\n";
		$errors++;
		next FILE;
	    } else {
		last;
	    }
	}

	my $coord_errors = 0;
	for my $c (@c) {
	    if ($c !~ m{^[-+]?\d+(?:\.\d+)?,[-+]?\d+(?:\.\d+)?$}) {
		if ($coord_errors == 0) {
		    warn "${file_label}Error in coordinate $c, position " . $s->pos . "\n";
		} elsif ($coord_errors == 1) {
		    warn "${file_label}More than one coordinate error, do not report any more...\n";
		}
		$coord_errors++;
	    }
	}

	if ($coord_errors) {
	    warn "${file_label}Found $coord_errors coordinate error(s)\n";
	    $errors++;
	    next FILE;
	}
    }

    print "${file_label}bbd OK\n" if $debug;
}

exit $errors;

__END__
