#!/usr/bin/env perl

## vhf/uhf freespace loss / approximate receive power level

## This file Copyright 2000 <contact@gbppr.org> under the GPL
## NO WARRANTY. Please send bug reports / patches / reports.

print "\n\n\t\tVHF/UHF Free Space Loss \\ Received Power Level Calculator\n\n";

while (!m/^([0-9.]+)(ft|FT|m|M|km|KM|mi|MI+)$/) {
	undef $_; undef $dis; undef $unit;
      	print "\nft = feet\n".
              "m  = meters\n".
              "km = kilometers\n".
              "mi = miles\n\n".
              "Enter distance between antennas  [value][ft,m,km,mi]: ";
	chomp($_ = <STDIN>);
}

if (m/^([0-9.]+)(ft|FT|m|M|km|KM|mi|MI+)$/) {
	$dis = $1;
        $unit = $2;
}              

if ($unit =~ /ft/i) {
	$unit = "feet";
	$dist = $dis / 5280;
}

elsif ($unit eq "m" or $unit eq "M") {
	$unit = "meter";
	$dist = $dis * 0.00062137119;
}

elsif ($unit =~ /km/i) {
	$unit = "kilometer";
	$dist = $dis * 0.62137119;
}

elsif ($unit =~ /mi/i) {
	$unit = "mile";
	$dist = $dis;
}

print "\n";

while (!$frq) {
	print "Enter frequency (in MHz): ";
	chomp($frq = <STDIN>);
	$frq =~ tr/0-9.//csd;
}

print "\n";

while (!$pwr) {
	print "Enter transmitter power (in watts): ";
	chomp($pwr = <STDIN>);
	$pwr =~ tr/0-9.//csd;
}

print "\n";

while (!$txant) {
	print "Enter transmitter antenna gain (in dB): ";
	chomp($txant = <STDIN>);
	$txant =~ tr/0-9.-//csd;
}

print "\n";

while (!$rxant) {
	print "Enter receive antenna gain (in dB): ";
	chomp($rxant = <STDIN>);
	$rxant =~ tr/0-9.-//csd;
}

print "\n";

while (!$imp) {
        print "Enter receive antenna impedance (in ohms): ";
        chomp($imp = <STDIN>);
        $imp =~ tr/0-9.-//csd;
}

$dbloss = 36.6 + (20 * ((log $frq) / (log 10))) + (20 * ((log $dist) / (log 10)));
$pwrdb = 10 * ((log ($pwr / 1)) / (log 10));
$dbloss = $dbloss - ($pwrdb + ($txant + $rxant));
$a = 1 / (10 ** ($dbloss / 10));
$v = sqrt ($imp * $a);

print "\n\n--------\n\n";
printf "          Antenna spacing : %s %s%s\n", $dis, $unit, ($dis == 1) ? "" : "s";
printf "        Transmitter power : %s Watts\n".
       "    Transmitter frequency : %s MHz\n".
       " Transmitter antenna gain : %s dB\n".
       "     Receive antenna gain : %s dB\n\n", $pwr, $frq, $txant, $rxant;
printf "          Receive voltage : %.3f millivolts\n", $v * 1000;
printf "                            %.3f microvolts\n", $v * 1000000;
printf "            Receive power : %.9f milliwatts\n", $a * 1000;
printf "                            %.6f microwatts\n", $a * 1000000;
printf "                            %.3f picowatts\n", $a * 1000000000000; 
printf "   Free space attenuation : %.3f dB\n\n", $dbloss;
