#!/usr/bin/perl -T
$ENV{"PATH"} = "";

my $recip = 'nw7us.heliophile@hfradio.org';
my $bcc = $recip;
my $esubject = "";

my $mail_prog = '/usr/lib/sendmail';

my $html_header = "Content-type: text/html\n\n";

my $rootDir     = "/home/hfradio";
my $databaseDir = $rootDir . "/database/resources";
my $logDir      = $rootDir . "/logs";
my $logFile     = $logDir . "/prefix_lookup.log";
my $logLock     = $logDir . "/pll.lck";

my ($pageTitle) = "Amateur Radio Callsign Prefix Search / Lookup :: HFRadio.org";

my $menuFile    = $rootDir . "/html/includes/propmenu.txt";

require "/home/hfradio/html/cgi-bin/database_engine.pl" || die "Could not require /hfradio/html/cgi-bin/database_engine.pl - $!\n";

use CGI ;
my $query = new CGI;
my (@names) = $query->param;

my $solarReport = "";
&doSolarData;

my $theForm =  "<form action=\"http://hfradio.org/cgi-bin/prefix\" method=\"POST\">\n";
$theForm .= "<b>Look up an Amateur Radio Callsign  prefix:</b><br />\n";
$theForm .= "<input type=\"text\" name=\"prefix\" maxlength=\"15\" size=\"7\"> &nbsp; <input type=\"submit\" value=\"Find Country\">\n";
$theForm .= "<br />\n";
$theForm .= "<small>Try the whole call first, like TX0DX,<br />or then try just a prefix, like 9M6 or BD</small>\n";
$theForm .= "</form>\n";

my $theSearch = "http://en.wikipedia.org/wiki/_KEY_";

# Get the input

if (defined($query->param('prefix'))) {

   # shorten prefix to make sure we are not hacked...

   #$query->param('prefix') =~ m|^([a-zA-Z0-9]{3,10})|;
   $query->param('prefix') =~ m|^([a-zA-Z0-9]{1,10}).*$|;

   my ($trueSearch) = $1;

print STDERR "Prefix True search: [" . $trueSearch . "]\n";

   my $prefix = $trueSearch;
	$prefix =~ s/^\s*(.+?)\s*$/$1/;

print STDERR "Prefix 1 search: [" . $prefix . "]\n";

	if (length($prefix) > 0) {
		$prefix =~ tr/[a-z]/[A-Z]/;
		$originalSearch = $prefix;

print STDERR "Prefix cleaned originalSearch: [" . $originalSearch . "]\n";

#		if ($prefix =~ m|^([A-Z][A-Z]\d)|) {
#			$prefix = $1;
#		} elsif ($prefix =~ m|^(\d[A-Z]\d)|) {
#			$prefix = $1;
#		}
		$noKey = 0;
	} else {
		$noKey = 1;
	}
} else {
	$noKey = 1;
}

if ($noKey) {
	$prefix = "";
	$originalSearch = "";
print STDERR "Prefix has noKey??\n";

}

use Date::Manip;

&Date_Init();

my $shortdate = &UnixDate("today","%D %H:%M:%S");
$shortdate =~ tr/\n\r//d;

if ($noKey) {
	$thePrompt = "";
} else {

&setDBfileName("$databaseDir/prefix.dat",$_PREFIX);

print STDERR "Search: " . $originalSearch . "\n";

&open_db_dup_read($_PREFIX);
@testList = ();
&getAllRecFromKey($_PREFIX,$originalSearch,\@testList);
$numFound = @testList;
$found = 0;
if ($numFound == 0) {

	$cycleKey = $originalSearch;
	$done = 0;

	while (!$done) {

		$cycleKey =~ s/^(.+?).$/$1/;
		if (length($cycleKey) == 1) {
			$done = 1;
		}
		@testList = ();
print STDERR "Prefix cycle search: [" . $cycleKey . "]\n";
		&getAllRecFromKey($_PREFIX,$cycleKey,\@testList);
		$numFound = @testList;
		if ($numFound) {
			$found = 1;
			$done = 1;
		} else {
			$found = 0;
		}
	}
} else {
	$found = 1;
}
&close_db($_PREFIX);

print STDERR "Prefix found? [" . $numFound . "]\n";

if ($found) {

	$thePrompt =  "You searched for <b>$originalSearch</b>,<br />with the <b>$prefix</b> prefix.<br /><br />Result:<br />\n";
	$thePrompt .= "<ul>\n";
	$prevLine = "";

	foreach $pLine (sort (@testList)) {

		if ($prevLine ne $pLine) {

			&logThis("[$shortdate] $originalSearch = $pLine");

			$prevLine = $pLine;
			$pLine =~ s/I\./Island/ig;
			$pLine =~ s/Is\./Island/ig;
			$sKey = $pLine;
			#$sKey =~ s/west |east |south |north //ig;
			$mySearch = $theSearch;
			$mySearch =~ s/_KEY_/$sKey/ig;
			$mySearch =~ s/ /_/g;
			$thePrompt .= "<li><a href=\"$mySearch\" target=\"lookWin\">$pLine</a><br />\n";
		}

	}
	$thePrompt .= "</ul>\n";
	$thePrompt .= "(Click on the result to see information<br />on the country... from <a href=\"http://en.wikipedia.org/wiki/\" target=\"lookWin\">http://en.wikipedia.org/wiki/</a>)<br />\n";
} else {
	&logThis("[$shortdate] $originalSearch did not match");
	$thePrompt  = "<b>You searched for $originalSearch.<br />Nothing was found for $prefix prefix.</b>\n";
	$thePrompt .= "<br /><br />\n";
	$thePrompt .= "Try a partial prefix (for instance,<br />\n";
	$thePrompt .= "instead of 9M6TTT, try 9M6 or <br />instead of YL3,\n";
	$thePrompt .= "try YL...)<br />\n";
}

} # end of test for noKey

$theMainMenu = "";
open (INMENU, "$menuFile") || die "Could not read [$menuFile] :: $!\n";
while (<INMENU>) {
	$theMainMenu .= $_;
}
close (INMENU);


print $html_header;

print <<H1;

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
	<title>$pageTitle</title>


	<link rel="stylesheet" href="http://hfradio.org/includes/standard_hfradio.css" type="text/css" />

<meta name="DESCRIPTION" content="High frequecy and VHF radio propagation data, solar and geomagnetic real-time and historic data, as well as forecasts.  A comprehensive propagation resource compiled by Tomas Hood, editor of the propagation columns of CQ, CQ VHF, Popular Communications, and Monitoring Times magazines.  Solar Weather, Geomagnetic, Aurora, Ionospheric reports via eAlerts and webpage.  WAP phone access.  Live and educational resources, and more.">

<meta http-equiv="Description" content="High frequecy and VHF radio propagation data, solar and geomagnetic real-time and historic data, as well as forecasts.  A comprehensive propagation resource compiled by Tomas Hood, editor of the propagation columns of CQ, CQ VHF, Popular Communications, and Monitoring Times magazines.  Solar Weather, Geomagnetic, Aurora, Ionospheric reports via eAlerts and webpage.  WAP phone access.  Live and educational resources, and more.">

<meta http-equiv="Keywords" content="high frequency radio propagation design analysis line-of-sight diffraction RF wireless Ham Radio HF progagational data solar sun sunspots communications geomagnetic ionospheric conditions events flares paths f-layer e-layer ionosphere long path short path transmit amateur radio progagational forcasts space weather flux coronal holes radiation ionizing refraction transmission transmit">

<meta name="KEYWORDS" content="high frequency radio propagation design analysis line-of-sight diffraction RF wireless Ham Radio HF progagational data solar sun sunspots communications geomagnetic ionospheric conditions events flares paths f-layer e-layer ionosphere long path short path transmit amateur radio progagational forcasts space weather flux coronal holes radiation ionizing refraction transmission transmit">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">

<meta http-equiv="Content-Style-Type" content="text/css" />

<link rel="shortcut icon" href="http://hfradio.org/favicon.ico">

<script language="JavaScript" type="text/javascript">
<!--

function setinitialStatus() {
  window.status = "This is the NW7US Prefix Database.";
}
// end -->
</script>

</head>

<body onLoad="setinitialStatus();" bgcolor="#FFFFFF">

<a name="top"> </a>
<div>

<table width="100%" cellspacing="1" cellpadding="1">
	<tr>
		<td valign="top" colspan="2">
			<table width="100%" border="1" cellspacing="1" cellpadding="6" bgcolor="#F2F8FF">
				<tr bgcolor="#F2F8FF">
					<td valign="top" align="center" bgcolor="#F2F8FF">
						<div>
						<b>Amateur Radio Callsign Prefix Lookup :: HFRadio.org</b>
						</div>
						<div class="smaller">
						(what country is that prefix from?)
						</div>
					</td>
				</tr>
			</table>
		</td>
	</tr>
	<tr>
		<td valign="top" width="33%">
			<div>
			<table width="100%" border="1" cellspacing="1" cellpadding="6" bgcolor="#F2F8FF">
				<tr bgcolor="#F2F8FF">
					<td valign="top" bgcolor="#F2F8FF">
						<div class="smaller">
						+ <b><a href="http://sunspotwatch.com/">Main Propagation Center</a></b>
						</div>
						<br /><hr noshade>
						$theMainMenu
					</td>
				</tr>
			</table>
			</div>
		</td>
		<td valign="top" width="66%">
			<table width="100%" border="1" cellspacing="1" cellpadding="6" bgcolor="#F2F8FF">
				<tr bgcolor="#F2F8FF">
					<td valign="top" bgcolor="#F2F8FF" width="66%">
						<div class="smenu" align="center">

<!-- ------------------- here ----------------------- -->
						<table width="100%" cellpadding="4" cellspacing="2" border="0" align="center">
							<tr>
								<td valign="top">
									<div class="smenu">
									$thePrompt
									</div>
								</td>
								<td valign="top">
									<div class="smenu">
									$theForm
									</div>
								</td>
							</tr>
							<tr>
								<td colspan="2" align="center">
									<div class="smenu" align="center">
									<hr noshade width="300">
									<br />
									Prefix not found? Perhaps the prefix has been retired. Check here: <a href="http://www.country-files.com/cty/history.htm" target="cWin">History of CTY.DAT revisions</a>.<br /><br />
									Comments?  Bug Report?  Please <a href="http://hfradio.org/commentform.html" title="Comment form - send feedback to NW7US">e-mail me</a>.
									<br />
									</div>
								</td>
							</tr>
						</table>
						</div>
					</td>
				</tr>
			</table>
			<table width="100%" border="1" cellspacing="1" cellpadding="6" bgcolor="#F2F8FF">
				<tr bgcolor="#F2F8FF">
					<td valign="top" bgcolor="#F2F8FF" width="66%">
						<div class="smaller" align="center">
						$solarReport
						</div>
					</td>
				</tr>
			</table>
			<table width="100%" border="1" cellspacing="1" cellpadding="6" bgcolor="#F2F8FF">
				<tr bgcolor="#F2F8FF">
					<td valign="top" bgcolor="#F2F8FF" width="66%">
						<div align="center">
						<table width="400" cellspacing="1" cellpadding="4" border="1">
							<tr>
								<td>
									<table width="500" cellpadding="6" cellspacing="6" border="0">
										<tr>
											<td valign="top">
<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="10215973">
<input type="image" src="https://www.paypal.com/en_US/i/btn/btn_donateCC_LG.gif" border="0" name="submit" alt="PayPal - The safer, easier way to pay online!">
<img alt="" border="0" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>

											</td>
											<td valign="top">
												<div align="center" class="smenu">
												<b>I need your help to keep this service up and running.</b>
												<br /><br />
												Your help keeps the NW7US Propagation and DX Resource Center alive and well.
												<br /><br />
												Thank you.
												</div>
											</td>
										</tr>
									</table>
								</td>
							</tr>
							<tr bgcolor="#F2F8FF">
								<td valign="top" align="center" bgcolor="#F2F8FF">
									<div class="smaller" align="center">
<a href="http://hfradio.org/" title="NW7US Amateur Radio">HFRadio.org</a> ::
<a href="http://sunspotwatch.com/" title="HF (VHF) Radio Propagation Resource Center with Live Space Weather Data">Propagation Center</a> ::
<a href="http://forums.hfradio.org/" title="Amateur radio, Shortwave Radio, Propagation Forums and Chat">Forums</a>

									<br />
<a href="http://shortwave.hfradio.org/" title="Shortwave Listening Resources and Information">Shortwave Resources</a> ::
<a href="http://hfradio.org/swbc/" title="Search an HF (SW) frequency to see scheduled International Shortwave Broadcasters">SWL Frequency Search</a> ::
									<br />
<a href="http://hfradio.org/about.html" title="Want to know more about Tomas Hood, NW7US?">About NW7US</a> ::
<a href="http://hfradio.org/swp_course/" title="Take the Award-winning Space Weather and Propagation Education Course, today!">Award-Winning Space Weather and Propagation Education Course</a>
									</div>
								</td>
							</tr>
							<tr>
								<td valign="top" bgcolor="#F2F8FF">
									<br />
									<div class="smenu">
									I write the <B>propagation columns</B> for the following magazines:
									<br /><br />
									<a href="http://www.amazon.com/exec/obidos/ASIN/B00006KAIS/theunofficiall0f" target="oWin"><img src="http://hfradio.org/graphics/books/cq_mag_sm.jpg" width="43" height="60" border="1" align="left" alt="CQ Magazine" hspace="8" vspace="3"></a> <a href="http://www.amazon.com/exec/obidos/ASIN/B00006KAIS/theunofficiall0f" target="oWin">CQ Magazine</a> America's fastest growing magazine for the active ham radio operator.  CQ is the world's leading independent magazine devoted to amateur radio. For more than a half-century, CQ has been on ham radio's leading edge -- the first to promote mobile operating (in the 1950s), semiconductors (in the 1960s) and packet radio -- the original e-mail (in the 1980s). The amateur satellite program got its start with an idea in the pages of CQ!
									<br clear="all" /><br />

									<a href="http://www.amazon.com/exec/obidos/ASIN/B00009PRZQ/theunofficiall0f" target="oWin"><img src="http://hfradio.org/graphics/books/cqvhf_mag.jpg" width="47" height="60" border="1" align="left" alt="CQ VHF Magazine" hspace="8" vspace="3"></a> <a href="http://www.amazon.com/exec/obidos/ASIN/B00009PRZQ/theunofficiall0f" target="oWin">CQ VHF Magazine</a> It is back! May 2002 saw the return of this quarterly magazines that focuses on amateur radio above 50 MHz.  Articles and columns target both the beginner as well as the expert.
									<br clear="all" /><br />

									<a href="http://www.amazon.com/exec/obidos/ASIN/B00006LDEW/theunofficiall0f" target="oWin"><img src="http://hfradio.org/graphics/books/popcom_mag.jpg" width="45" height="60" border="1" align="left" alt="Popular Communications Magazine" hspace="8" vspace="3"></a> <a href="http://www.amazon.com/exec/obidos/ASIN/B00006LDEW/theunofficiall0f" target="oWin">Popular Communications Magazine</a> Exciting reading for the shortwave and scanner listener.  It features authoritative information on scanner monitoring of police, fire, utility and aircraft transmissions as well as short wave listening, monitoring short wave digital, fax and teletype broadcasts, cb radio, alternative radio, clandestine radio, telephones and wiretapping, bugging, surveillance, pirate broadcasters, military communications, amateur radio, satellite tv reception, radio history and nostalgia.
									<br clear="all" /><br />

									</div>
								</td>
							</tr>
						</table>
						</div>
					</td>
				</tr>
			</table>
		</td>
	</tr>
</table>
</div>

<hr noshade='1' />
<div class="smaller" align="center">
Copyright, 1998 - 2011 <a href="http://hfradio.org/commentform.html" title="Comment form - send feedback to NW7US">Tomas Hood</a> (NW7US), all rights reserved.
<br /><br />
developed by NW7US (Tomas)
</div>
<br /><br />

<div align="center">
<script type="text/javascript"><!--
google_ad_client = "pub-0587229305754679";
google_ad_width = 728;
google_ad_height = 90;
google_ad_format = "728x90_as";
google_color_border = "B0E0E6";
google_color_bg = "FFFFFF";
google_color_link = "000000";
google_color_url = "336699";
google_color_text = "333333";
//--></script>
<script type="text/javascript"
  src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>
<br /><br />

</body>
</html>
H1

exit;


#===== subs =====

sub logThis {

	my ($msg) = @_;

	my ($reties) = 15;
	my ($delay) = 3;
	my ($done) = 0;

	# do locking

	while (!$done) {
		if (-e $logLock) {
			if ($retries) {
				$retries--;
				$done = 0;
				sleep($delay);
			} else {
				print STDERR "Could not lock!\n";
				$done = 1;
			}
		} else {

			open(LOCK, "> $logLock") || print STDERR "Could not create $logLock: $!\n";
			close(LOCK);

			open(LOG, ">>$logFile") || print STDERR "Could not append to $logFile: $!\n";
			print LOG "$msg\n";
			close (LOG);
			unlink($logLock);
			$done = 1;
		}
	}
}

sub doSolarData {

	$solarReport = "";

	$solarReport = "<small>| Current Solar Flux: <b>";
	open (PIN, "/hfradio/html/prop/.flux.txt") || die "Could not open /hfradio/html/prop/.flux.txt : $!\n";
	my ($line) = "";
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> |<br />\n| A-index: <b>";
	open (PIN, "/hfradio/html/prop/.aindex.txt") || die "Could not open /hfradio/html/prop/.aindex.txt : $!\n";
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> | K-index: <b>";
	open (PIN, "/hfradio/html/prop/.kindex.txt") || die "Could not open /hfradio/html/prop/.kindex.txt : $!\n";
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> | Aurora: <b>";
	open (PIN, "/hfradio/html/prop/.aurora_level.txt") || die "Could not open /hfradio/html/prop/.aurora_level.txt : $!\n";
	while (<PIN>) {
		$line = $_;
		$line =~ tr/\n\r\t//d;
		$solarReport .= $line;
	};
	close(PIN);
	$solarReport .= "</b> | <a href=\"http://hfradio.org/propagation.html\">more...</a> |</small>\n";

}

