#!/usr/bin/perl -w
# NAME: distance.pl
# AIM: Use perl trib function for distance London to Tokyo...
# from : http://perldoc.perl.org/Math/Trig.html
use strict;
use warnings;
use Math::Trig qw(great_circle_distance great_circle_direction deg2rad rad2deg);
 # Notice the 90 - latitude: phi zero is at the North Pole
sub NESW { deg2rad($_[0]), deg2rad(90 - $_[1]) }
# 1 knots = 1.85200 kph
my $K2KPH = 1.85200;

my $lonlon = -0.5;
my $lonlat = 51.3;
my $toklon = 139.8;
my $toklat = 35.7;
my $g_ias = 80; # Knots - c152-c172
my $g_speed = $g_ias * $K2KPH; # Kilometers/Hour

sub get_hhmmss($) {
    my ($hours) = @_;
    my $hrs = int($hours);
    my $mins = ($hours * 60) - ($hrs * 60);
    my $min = int($mins);
    my $secs = ($mins * 60) - ($min * 60);
    my $days = 0;
    if ($hrs >= 24) {
        $days++;
        $hrs -= 24;
    }
    $min = ($min < 10) ? "0$min" : $min;
    $secs = int( $secs + 0.5 );
    $secs = ($secs < 10) ? "0$secs" : $secs;
    $hrs = ($hrs < 10) ? "0$hrs" : $hrs;
    my $stg = '';
    $stg .= "Days $days, " if ($days);
    $stg .= "$hrs:$min:$secs";
    return $stg;
}

my ($rkm,$heading,@L,@T,$km,$degs,$argc,$hours,$hms);
$argc = scalar @ARGV;
if ($argc == 4) {
    $lonlon = $ARGV[0];
    $lonlat = $ARGV[1];
    $toklon = $ARGV[2];
    $toklat = $ARGV[3];
    @L = NESW( $lonlon, $lonlat);
    @T = NESW( $toklon, $toklat);
    $km = great_circle_distance(@L, @T, 6378); # About 9600 km.
    $degs = rad2deg(great_circle_distance(@L, @T));
    $heading = rad2deg(great_circle_direction(@L, @T));
    $heading = int(($heading * 10) + 0.05) / 10;
    $hours = $km / $g_speed;
    $hms = get_hhmmss($hours);
    $rkm = int($km + 0.5);
    #$degs = int($degs + 0.5);
    #$degs = int($degs + 0.5);
    $degs = sprintf("%0.6f",$degs);
    print "From (lon,lat) $lonlon,$lonlat to $toklon,$toklat is about -\n";
    print "Distance: $rkm kilometers ($km)\n";
    print "Heading : $heading, for $degs degs\n";
    print "ETA     : $hms, at $g_ias Knots\n";
    # print "km $km / spd $g_speed = $hours\n";
} else {
    print "ERROR: Need 4 arguments, not $argc!\n" if ($argc);
    print "Given two pairs of longitude, latitude, and will calculate the distance, and heading...\n";
    @L = NESW( $lonlon, $lonlat);
    @T = NESW( $toklon, $toklat);
    $km = great_circle_distance(@L, @T, 6378); # About 9600 km.
    $degs = rad2deg(great_circle_distance(@L, @T));
    $heading = rad2deg(great_circle_direction(@L, @T));
    $heading = int(($heading * 10) + 0.05) / 10;
    $rkm = int($km + 0.5);
    $hours = $km / $g_speed;
    $hms = get_hhmmss($hours);
    #$degs = int($degs + 0.5);
    $degs = sprintf("%0.6f",$degs);
    print "EG: From (lon,lat) London $lonlon,$lonlat to Tokyo $toklon,$toklat\n is approx. ";
    print "$rkm kilometers ($km)... Heading $heading, for $degs degs, eta $hms, at $g_ias Knots\n";
    #print "$km kilometers... on heading $heading, for $degs degs... $hms\n";
}

# eof - distance.pl
