#!/usr/bin/perl

$num = 0;
$override_range = $ARGV[0];

# Go through the .csc file; find the transmission range and all the
# nodes' x and y coordinates.
while(<STDIN>) {
    if(/\<transmitting_range\>([\d.]+)\<\//) {
        $range = $1;
    }
    if(/\<success_ratio_rx\>([\d.]+)\<\//) {
        $success_ratio_rx = $1;
    }

    if(/\<x\>([\d.]+)\</) {
        $x[$num] = $1;
    }
    if(/\<y\>([\d.]+)\</) {
        $y[$num] = $1;
        $num++;
    }
}

if($override_range) {
    $range = $override_range;
}

$no_neighbors = 0;
$all_neighbors = 0;
$total_neighbors = 0;

# Go through all nodes, find how many are in their range and compute
# the average reception probability. Make sure we only count each neighbor once.
for($i = 0; $i < $num; $i++) {
    $neighbors = 0;
    for($j = 0; $j < $num; $j++) {
        if($i != $j) {
            $distance2 = ($x[$i] - $x[$j]) * ($x[$i] - $x[$j]) +
                ($y[$i] - $y[$j]) * ($y[$i] - $y[$j]);
            $range2 = $range * $range;
            if($distance2 <= $range2) {
                $neighbors++;

                $ratio = $distance2 / $range2;
                if($ratio > 1) {
                    $reception_probability = 0;
                } else {
                    $reception_probability = 1 - $ratio * (1 - $success_ratio_rx);
                }
                $reception_probability_sum += $reception_probability;
            }
        }
    }
    if($neighbors == 0) {
        $no_neighbors++;
    }
    if($neighbors == $num - 1) {
        $all_neighbors++;
    }
    $total_neighbors += $neighbors;
}

print "$num $range " . ($total_neighbors / $num) .
    " " . ($no_neighbors / $num) .
    " " . ($all_neighbors / $num) .
    " " . ($reception_probability_sum / $total_neighbors) .
    "\n";
print "# Range $range number of nodes $num override range $override_range\n";
print "# Num nodes $num, average neighbors " . ($total_neighbors / $num) .
    ", $no_neighbors nodes (" . (100 * $no_neighbors / $num) .
    "%) have no neighbors, $all_neighbors (" . (100 * $all_neighbors / $num) .
    "%) have all other nodes as neighbors\n";
print "# Average reception probability " .
    ($reception_probability_sum / $total_neighbors) . "\n";
