#!/usr/bin/perl -w
use strict;
use LWP::UserAgent;
use Net::HTTP;
use HTTP::Request::Common qw(POST);
use POSIX ":sys_wait_h";

print "Content-type: text/html\n\n";

my $ua= LWP::UserAgent->new;
$ua->agent("Spectrum");

#----------------------------------------
# Parse incoming data
#----------------------------------------
my $buffer;
my %params;
my $cmd = "";

if($ENV{REQUEST_METHOD} eq 'POST')
{
    read(STDIN, $buffer, $ENV{CONTENT_LENGTH});
    $buffer .= "&";
    $buffer .= $ENV{QUERY_STRING};
} 
else
{
    $buffer = $ENV{QUERY_STRING};
}
my @pairs = split(/&/, $buffer);
my $pair;

foreach $pair(@pairs)
{
    (my $key, my $value) = split(/=/, $pair);
    $value =~ tr/+/ /;
    $value =~ s/%0D%0A/"%0A"/eg;
    $value =~ s/%([A-Fa-f0-9]{2})/pack("C",hex($1))/eg;
    
    if (defined $params{$key})
    {
	$params{$key} .= "\t$value";
    } 
    else
    {
	$params{$key} = $value;
    }

    if( !($key eq "minfr") && !($key eq "maxfr") && !($key eq "stepfr") && !($key eq "said") && !($key eq "cmid") )
    {
	$cmd = "$cmd" . "$key=$value&";
    }
}

##############
# Parameters #
##############
my $SAID = $params{"said"} || 0;
my $CMID = $params{"cmid"} || 0;
my $BID = -1; # ignore this parameter
my $MinFr = $params{"minfr"} || 0;
my $MaxFr = $params{"maxfr"} || 0;
my $StepFr = $params{"stepfr"} || 0;
my $N = 301; # High priority

my $cf = $params{"cf"} || 0;
my $rf = $params{"rf"} || 0;
my $aqFreq = $params{"aqfrequency"} || 0;
my $isInverted = $params{"isinverted"} || 0; # false
my $measureType = 1; # by hands
my $lockID = $params{"lockid"} || 0;

my $pid = fork();
if($pid == 0)
{
    exec "../spectrum/SpectrumMonitoring/scanDiapason.pl", "$SAID", "$CMID", "$BID",
    "$MinFr", "$MaxFr", "$StepFr", "$N",
    "$cf", "$rf", "$isInverted", "$aqFreq", "$measureType", "$cmd", "$lockID";
}