#!/usr/bin/perl -w
# Checks OSM data for ways referencing non-existent nodes and relations
# referencing non-existing ways.

# Read filename of the osm file
my $filename=shift;
unless ($filename) {
    print "Usage: findBadReferences.pl <osm file>\n";
    exit;
}

# Open the osm file for reading
print "Reading $filename...\n";
unless(open(FILE,$filename)) {
    print "Can't find file $filename\n";
    exit;
}
my @lines = <FILE>;
close(FILE);
foreach $line (@lines) {
    if ($line =~ /<node id='(\d*)'/) {
    	$nodes{$1} = 1;
    }
    if ($line =~ /<way id='(\d*)'/) {
    	$ways{$1} = 1;
    }
}
foreach $line (@lines) {
    if ($line =~ /<nd ref='(\d*)'/) {
    	unless(exists($nodes{$1})) {
			print("Found reference to non-existent node with id $1\n");
		}
    }
    if ($line =~ /<member type='way' ref='(\d*)'/) {
    	unless(exists($ways{$1})) {
			print("Found reference to non-existent way with id $1\n");
		}
    }
}
