#!/usr/bin/perl
@csv = ();
$lat0 = 0.0; $lon0 = 0.0; $cnt = 0;
while(<>) {
    s/[\n\r ]+$//;
    s/&/&amp;/g;
    s/\</&lt;/g;
    s/\>/&gt;/g;
    s/"/&quot;/g;
    s/'/&apos;/g;
    @line = split /\t/;
    print STDERR "Warning at ref $line[0]\n" if $#line < 5;
    if( $line[4] > 0 ) {
        $lat0 += $line[4];
        $lon0 += $line[5];
	$cnt++;
    }
    push @csv, [ @line ];
}
$lat0 /= $cnt;
$lon0 /= $cnt;

print "<?xml version='1.0' encoding='UTF-8'?>\n<osm version='0.6' generator='csv2osm.pl'>\n";
$id = -1;
@keys = ('ref', 'address', 'name', 'phone');

for $i (0 .. $#csv) {
    ($lat, $lon) = ($csv[$i][4], $csv[$i][5]);
    $lat = $lat0 if $lat < 1;
    $lon = $lon0 if $lon < 1;
    for $j (0 .. $i-1) {
	if( $lat == $csv[$j][4] && $lon == $csv[$j][5] ) {
	    $lat -= 0.0001;
	}
    }
    $csv[$i][4] = $lat;
    $csv[$i][5] = $lon;
    print "<node id='$id' lat='$lat' lon='$lon'>\n";
    print "\t<tag k='$keys[$_]' v='$csv[$i][$_]' />\n" for 0..$#keys;
    print "</node>\n";
    $id--;
}
print "</osm>";
