#!/usr/bin/perl

use Getopt::Std;
getopt ('io');

if ($opt_i eq "" or $opt_o eq "") {
	print "You must specify an input and output file with the -i and -o options\n";
	exit;
	}
	
print "input is $opt_i\n";
print "output is $opt_o\n";

open INPUTFILE, "$opt_i" or die "Error is: $! for input file\n";
open TEMPFILE2, ">tempfile2" or die $!;
open TEMPFILE3, ">tempfile3" or die $!;
open OUTPUTFILE, ">$opt_o" or die "Error is: $! for output file\n";

for (1..2) {$temp = (<INPUTFILE>); print OUTPUTFILE $temp;}

$count = 0;
while (<INPUTFILE>) {
	if (index($_, "<node id=\"") == 1) {
		$start1 = index($_, "=") + 2;
		$end1 = index($_, " ", $start1) - 1;
		$start2 = index($_, "=", $end1) + 2;
		$end2 = index($_, " ", $start2) - 1;
		$start3 = index($_, "=", $end2) +2;
		$end3 = index($_, " ", $start3) - 1;
		$nodeid = substr($_, $start1, $end1 - $start1);
		$lat = substr($_, $start2, $end2-$start2);
		$lon = substr($_, $start3, $end3-$start3);
		$newlat = sprintf("%.7f", $lat);
		$newlon = sprintf("%.7f", $lon);
		$linetowrite = "<node id=\"$nodeid\" lat=\"$newlat\" lon=\"$newlon\"/>\n";
		print TEMPFILE2 "$linetowrite";
		if ($count == 0) {
			$minlat = $newlat;
			$maxlat = $newlat;
			$minlon = $newlon;
			$maxlon = $newlon;
		} 
		if ($maxlat < $newlat) {$maxlat = $newlat};
		if ($minlat > $newlat) {$minlat = $newlat};
		if ($maxlon < $newlon) {$maxlon = $newlon};
		if ($minlon > $newlon) {$maxlon = $newlon};
		$count++;
	}
	else {
		print TEMPFILE3 "$_";
	}
}

close INPUTFILE;
close TEMPFILE2;
close TEMPFILE3;

print OUTPUTFILE "<bounds minlat=\'$minlat\' minlon=\'$minlon\' maxlat=\'$maxlat\' maxlon=\'$maxlon\'/>\n";

open INPUTFILE, "tempfile2" or die $!;
while (<INPUTFILE>) {
	print OUTPUTFILE "$_";
}
close INPUTFILE;

open INPUTFILE, "tempfile3" or die $!;
while (<INPUTFILE>) {
	print OUTPUTFILE "$_";
}
close INPUTFILE;

close OUTPUTFILE;

`rm -f tempfile2`;
`rm -f tempfile3`;

exit;
