# multidelay.pl - calculate time delay from each site and add to delay_xy.txt file

use Math::Round;
use Geo::Distance;
$geo = Geo::Distance->new();
$geo->formula('hsin');

# Open file with combined signal streanths
open (MULTXY, "multi_xy.txt") or die "Can't open multi_xy.txt! \n";

# Open file for writing combined data
open (DELAYXY, ">delay_xy.txt") or die "Can't open delay_xy.txt! \n";

# Format for future site_loc.txt
# First line: SITE 1 [Latitude decimal degrees] [Longitude decimal degrees]
# Following lines SITE # [Latitude decimal degrees] [Longitude decimal degrees]
# Sites must follow same order as field strengths listed in each line in multi_xy.txt
# open (SITES, "site_loc.txt") or die "Can't open "site_loc.txt! \n";

print "Calculating time delay from transmitter sites...\n";

# Temporary fixed data for testing delay calculation
# tx1 is KNBC Mount Wilson
# tx2 is Arco Tower, downtown Los Angeles

$tx1lat = 34.2254722222;
$tx1long = 0 - (118.065305556);

$tx2lat = 34.0508333333;
$tx2long = 0 - (118.263055556);


$idx = 1;
while (<MULTXY>) {
    $temp = $_;
    if ($idx > 2) {
        @data = split /\s/, $temp;
	$lat  = $data[0] / 1200 ;
	$long = 0 - ( $data[1] / 1200 ) ;
	$fs1  = round( $data[2] );
	if ( $fs1 < 0 ) { $fs1 = 0; };
	$fs2  = round( $data[3] ); 
	if ( $fs2 < 0 ) { $fs2 = 0; };
        if ( ($fs1 > 0) || ($fs2 > 0) ) {
            $tx1delay = $geo->distance( 'light second' , $tx1long , $tx1lat => $long , $lat );
	    $tx1delay = round( $tx1delay * 1000000 );
            $tx2delay = $geo->distance( 'light second' , $tx2long , $tx2lat => $long , $lat );
            $tx2delay = round( $tx2delay * 1000000 );
            $dataout = "$data[0] $data[1] $fs1 $fs2 $tx1delay $tx2delay";
	    print DELAYXY $dataout."\n";
	};
    }
    else {
        print DELAYXY $temp;
    };
    $idx++;
};

close MULTXY;
close DELAYXY;

exit;
