# This perl script generates band occupancy maps from RBN
# data. For details, see http://fkurz.net/ham/stuff.html?bandoccupancy
#
# 2014-09-27 - Fabian Kurz, DJ1YFK <fabian@fkurz.net>
# 
# This file is in the public domain.

use strict;
use warnings;

my %skimmers = ( 'HB9DCO' => 1, 'ON5KQ' => 1, 'OH6BG' => 1 );

my @busy;
my @a;
my $date = "(error)";
my $validspots = 0;

# 96 time slots a 15 minutes - 10100 - 10150 kHz (change for other bands)
foreach my $x (0..95) {
	foreach my $y (100..150) {
		$busy[$x][$y] = 0;
	} 
}

# array:   busy[0][134] ==> 0th time interval (each 15 min), 10134 kHz

while (chomp(my $line = <>)) {
	my @a = split(/,/, $line);
#	if (defined($skimmers{$a[0]}) and $a[4] eq "30m" and $a[12] eq "CW") {
	if ($a[4] eq "30m" and $a[12] eq "CW") {
		my $interval = t2i($a[10]);
		my $freq = $a[3] - 10000;
		$busy[$interval][$freq]++;
		$date = substr($a[10],0,10);
		$validspots++;
	}
}


my $max = 0;

#  print "ascii map"
foreach my $fr (100..150) {
	print "$fr: "; 
	foreach my $in (0..95) {
		if ($busy[$in][$fr] > 0) {
			$max = ($busy[$in][$fr] > $max) ? $busy[$in][$fr] : $max;
			print "X";
		}
		else {
			print " ";
		}
	}
	print "\n";
}

open GP, ">plot-$date";

#$max = 75;
print GP '
set terminal png
set output "plot-'.$date.'.png"
set title "30m band activity on '.$date.' as seen by RBN ('.$validspots.' spots)"
unset key
set tic scale 0
# Color runs from white to green
#set palette rgbformula -7,2,-7
set cbrange [0:'.log($max).']
set cblabel "Spots"
unset cbtics

set xrange [-0.5:95.5]
set yrange [-0.5:49.5]
set ylabel "freq / kHz" 
set xlabel "15 min segments" 

set view map
';
print GP "splot '-' matrix with image\n";

foreach my $fr (100..150) {
	foreach my $in (0..95) {
		my $z = $busy[$in][$fr];
		print GP log($busy[$in][$fr]+0.0001)." ";
	}
	print GP "\n";
}

print GP "e
e
";

close GP;

system("gnuplot plot-$date");







sub t2i {
my $time = shift;

$time =~ /\s([0-9]{2}):([0-9]{2}):[0-9]{2}$/;

my $hr = $1;
my $min = $2;

if ($min < 15) {
return $hr * 4;
}
elsif ($min < 30) {
return ($hr * 4)+1;
}
elsif ($min < 45) {
return ($hr * 4)+2;
}
else {
return ($hr * 4)+3;
}

}
