#!/usr/bin/perl

    # calculates km and miles from a path
    # in a google earth kml or kmz file.
    # Idea and formula by Heiko Braak,
    # programming by Jochen Puchalla (c) 2007-2012
    # mail at puchalla dash online dot de
    # License: GPL V2

if ($#ARGV eq 1)
{
	print STDOUT "usage: kml2length.pl file1.kml [file2.kml ...]\n";
	exit(0);
}

# Version 0.2

my $pi=3.141592;

foreach $file (@ARGV)
{
	if (! open(INPUT,"<$file") )
	{
		print STDERR "Can't open input file $file\n";
		next;
	}

	print STDOUT "$file:";

	my $ext = ($file =~ m/([^.]+)$/)[0];
# 	print $ext;

	if ($ext eq "kmz")
	{
		system("unzip -q -o $file");
		$file="doc.kml";
	}

	$ext = ($file =~ m/([^.]+)$/)[0];

	if ($ext ne "kml")
	{
		print STDERR "$file is not a kml file\n";
		next;
	}

	open(INPUT,"<$file");

	while ($line=<INPUT>)
	{
		if ($line =~ /coordinates/)
		{
			$sum=0; $n=0; $convert=""; $newline="";
			until ( $line =~ m/<\/coordinates>/i )
			{
				$line=<INPUT>; chomp $line;
#print $line;
				$line =~ s/\ \ /\ /g;
				$line =~ s/\ \ /\ /g;
				$line =~ s/\ \ /\ /g;
				$line =~ s/\ \ /\ /g;
				$line =~ s/\ \ /\ /g;
				$line =~ s/\ \ /\ /g;
				$newline= "$newline" . "$line";
			}
			$newline =~ s/<\/coordinates>//g;
			$newline =~ s/,/\ /g;
			$newline =~ s/^\ //g;
			$newline =~ s/\ $//g;
# print $newline . "end ";
			@values = split(/\s/, $newline);
# print length($newline) . " characters ";
			$vals = split(/\s/, $newline);
# print " $vals values";
			for ($n=0 ; $n<$vals-4 ; $n=$n+3)
			{
				$sum = $sum + sqrt((($values[$n+4]-$values[$n+1])*$pi*6371/180)*(($values[$n+4]-$values[$n+1])*$pi*6371/180)+(6371*cos($pi/180*$values[$n+4])*$pi*($values[$n+3]-$values[$n])/180)*(6371*cos($pi/180*$values[$n+4])*$pi*($values[$n+3]-$values[$n])/180));
# print sqrt((($values[$n+4]-$values[$n+1])*$pi*6371/180)*(($values[$n+4]-$values[$n+1])*$pi*6371/180)+(6371*cos($pi/180*$values[$n+4])*$pi*($values[$n+3]-$values[$n])/180)*(6371*cos($pi/180*$values[$n+4])*$pi*($values[$n+3]-$values[$n])/180)); print "\n";
# print "$sum\n";
# print "$n\n";
# print "$values[$n] \n";
# print "$values[$n+1] \n";
# print "$values[$n+3] \n";
# print "$values[$n+4] \n";
			}
  			print $convert = sprintf "  %5.3f km  %5.2f miles  (%i waypoints)\n" , $sum, $sum*0.62137, $n/3+1;
		}
	}
	close INPUT;
	if ($file eq "doc.kml") { system("rm doc.kml"); }
}
exit(0);
