#!/usr/bin/perl -w

use Getopt::Std;
use Math::Trig qw(great_circle_distance deg2rad);
use n8ur qw(round trim);


my $qth = "Snellville";
my $start_lon = 84.04138; 
my $start_lat = 33.87903;
my $distance = 30;

#my $qth = "Beaver Island";
#my $start_lon = 85.48999; 
#my $start_lat = 45.64346;
#my $distance = 150;

my $reading;

my $null;
my $call;
my $freq;
my $service;
my $channel;
my $antenna;
my $hours;
my $us_class;
my $int_class;
my $status;
my $city;
my $state;
my $country;
my $file_number;
my $erp_h;
my $erp_v;
my $haat_h;
my $haat_v;
my $facility_id;
my $latH;
my $latD;
my $latM;
my $latS;
my $lonH;
my $lonD;
my $lonM;
my $lonS;
my $lat;
my $lon;
my $licensee;
my $km_from_lat_lon;
my $miles_from_lat_lon;
my $azimuth_from_lat_lon;
my $rcamsl_h;
my $rcamsl_v;
my $dir_ant_id;
my $dir_ant_pattern_rotation;
my $ant_structure_registration;

my @fields;
my $j;
my $k;
my $i;
my $power_string;
my $haat_string;
my @tmp_array;
my $tmp1;
my $tmp2;
my $tmp3;

while ($reading=<STDIN>) {
@fields = "";
@fields = split(/\|/,$reading);
for ($i=0; $i<=$#fields; $i++) {
	$fields[$i] = trim($fields[$i]);
	}
(	
$null,
$call,
$freq,
$service,
$channel,
$antenna,
$hours,
$us_class,
$int_class,
$status,
$city,
$state,
$country,
$file_number,
$erp_h,
$erp_v,
$haat_h,
$haat_v,
$facility_id,
$latH,
$latD,
$latM,
$latS,
$lonH,
$lonD,
$lonM,
$lonS,
$licensee,
$km_from_lat_lon,
$miles_from_lat_lon,
$azimuth_from_lat_lon,
$rcamsl_h,
$rcamsl_v,
$dir_ant_id,
$dir_ant_pattern_rotation,
$ant_structure_registration
) = @fields;
$lat = round(6,$latD + $latM/60 + $latS/3600);
$lon = round(6,$lonD + $lonM/60 + $lonS/3600);
# Notice the 90 - latitude: phi zero is at the North Pole.
my @L = (deg2rad($start_lon), deg2rad(90 - $start_lat));
my @T = (deg2rad($lon),deg2rad(90 - $lat));
my $km = round(2,great_circle_distance(@L, @T, 6378));

@tmp_array = split(/ /,$erp_h);
$tmp1 = $tmp_array[0];
@tmp_array = split(/ /,$erp_v);
$tmp2 = $tmp_array[0];
$power = "ERP (H/V): $tmp1/$tmp2 KW";
if (substr($service,0,1) ne "F") { $power = "Power: $tmp1 kw"; }

if (substr($service,0,1) eq "A") { $haat = ""; }
if (substr($service,0,1) eq "F") { $haat = "HAAT (H/V): $haat_h/$haat_v M"; }
if (substr($service,0,1) eq "T") { $haat = "HAAT: $haat_h M"; }


if ( ($km <= $distance) && ($status eq "LIC") ) {
	print "$call $freq $city, $state, $country\n";
	print "Service: $service Channel: $channel\n";
	print "Class: $us_class Status: $status\n"; 
	print "Antenna: $antenna Hours: $hours\n";
	print "$power $haat\n";
	print "$latH$lat $lonH$lon\n";
	print "Licensee: $licensee\n";
	print "Distance from $qth: $km km\n";
	print "\n";
	}
}
