#!/usr/bin/env perl

## frequency <=> wavelength calculator

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

while (!$ans || $ans > 2 || $ans =~ m/[a-z]/i) {
	print "\33[H\33[J".            
	      "1) Find frequency given wavelength\n".
              "2) Find wavelength given frequency\n\n".
              "Enter your selection: ";
	chomp($ans = <STDIN>);
}


if ($ans == 1) {

     while (!m/^([0-9.]+)(an|AN|mm|MM|cm|CM|m|M|km|KM|in|IN|ft|FT|mi|MI+)$/) {
     	print "\nan = angstroms\n".
              "mm = millimeters\n".
	      "cm = centimeters\n".
	      "m  = meters\n".
	      "km = kilometers\n".
	      "in = inches\n".
	      "ft = feet\n".
	      "mi = miles\n\n".
	      "Enter the wavelength  [value][unit]: ";
	chomp($_ = <STDIN>);
}

if (m/^([0-9.]+)(an|AN|mm|MM|cm|CM|m|M|km|KM|in|IN|ft|FT|mi|MI+)$/) {
	$wav = $1;
        $unit = $2;
}

if ($unit =~ /an/i) {
	$wavu = "angstroms";
	$frq = 2.99793E+18 / $wav;
}

elsif ($unit =~ /mm/i) {
	$wavu = "millimeters";
	$frq = 2.99793E+11 / $wav;
}

elsif ($unit =~ /cm/i) {
	$wavu = "centimeters";
	$frq = 2.99793E+10 / $wav;
}

elsif ($unit eq "m" or $unit eq "M") {
	 $wavu = "meters";
	 $frq = 2.99793E+08 / $wav;
}

elsif ($unit =~ /km/i) { 
	$wavu = "kilometers";
	$frq = 299793 / $wav;
}

elsif ($unit =~ /in/i) {
	$wavu = "inches";
	$frq = 1.180285E+10 / $wav;
}

elsif ($unit =~ /ft/i) {
	$wavu = "feet";
	$frq = 983570840 / $wav;
} 

elsif ($unit =~ /mi/i) {
	$wavu = "miles";
        $frq = 186280 / $wav;
}  

printf "\n\n  Frequency : %.9f Hz\n", $frq;
printf "            : %.6f kHz\n", $frq / 1000;
printf "            : %.6f MHz\n", $frq / 1000000;
printf "            : %.6f GHz\n\n", $frq / 1000000000;
printf " Wavelength : %s %s\n\n", $wav, $wavu;
}

elsif ($ans == 2) {

	while (!m/^([0-9.]+)(k|K|m|M|g|G|h|H+)$/) {
	  print "\nk = kilohertz\n".
	        "m = megahertz\n".
		"g = gigahertz\n".
		"h = just hertz\n\n".
		"Enter the frequency  [value][unit]: ";
          chomp($_ = <STDIN>);
}

if (m/^([0-9.]+)(k|K|m|M|g|G|h|H+)$/) {
        $frq = $1;
	$unit = $2;
}

if ($unit =~ /k/i) {
	$frqu = "kilohertz";
        $wav = 2.99793E+15 / $frq;
}

elsif ($unit =~ /m/i) {
	$frqu = "megahertz";
	$wav = 2.99793E+12 / $frq;
}

elsif ($unit =~ /g/i) {
	$frqu = "gigahertz";
	$wav = 2.99793E+09 / $frq;
}

elsif ($unit =~ /h/i) {
	$frqu = "hertz";
	$wav = 2.99793E+18 / $frq;
}

printf "\n\n Wavelength : %.12f mm\n", $wav / 1E+07;
printf "            : %.6f cm\n", $wav / 1E+08;
printf "            : %.6f m\n", $wav / 1E+10;
printf "            : %.6f km\n", $wav / 1E+13;
printf "            : %.9f in\n", $wav / 2.54E+08;
printf "            : %.6f ft\n", $wav / 3.048E+09;
printf "            : %.6f mi\n\n", $wav / 1.60934E+13;
printf "  Frequency : %s %s\n\n", $frq, $frqu;
}
