#!/usr/bin/perl
#
##############################################
# BanderDyn
##############################################
# Simple script for measuring download
# speed, with some dynamical ability
# to end up as soon as 10s are crossed.
#
# It's time precision is 1s - 
# we only relay on system time ability
# and are not using require 'sys/syscall.ph';
# http://www.perldoc.com/perl5.8.0/pod/perlfaq8.html
#
# Bander, maintenance: Adam Pribyl, covex@lowlevel.cz
# Dyn: Petr Simandl, www.simandl.cz
###############################################

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

print "<HTML><HEAD><META HTTP-EQUIV=Pragma CONTENT=no-cache></HEAD><BODY>\n"; # nocache!

$kb = 1024;
@nkbp = (  10,  20,  70,    75,   150,  250,        250,       500,      1000,      2000);
$nkb = 0;
$lnkbp = $#nkbp;

@pism = ("aa","bb","cc","dddd","eeee","ffff","gggggggg","hhhhhhhh","iiiiiiii","jjjjjjjj","kk","ll");

$svrtimeout = 30; 	# httpd server timeout in seconds

$testtime = 10;		# maximum test time

$lospd = $nkbp[0]/$svrtimeout;

#print "<CENTER>\n";
printf "If no speed information is given then either your connection is too slow (< %1.2f kiB/s) or you are experiencing signal dropouts. <br>\n", $lospd;

print "Sending";

$tm2 = $tm1 = time;

for ($ii = 0; $ii <= $lnkbp; $ii++)   {
    if ( ($tm2-$tm1) < $testtime )
    {
          for ($f = 0; $f <= $nkbp[$ii]; $f++) {
                print "<!--";
                for ($g = 1; $g <= ($kb/2-(10/length($pism[$ii]))) ; $g++) { print "$pism[$ii]"; }
                print "-->. \n";
          }
          $tm2 = time;
          $nkb = $nkb + ($nkbp[$ii]*(length($pism[$ii])/2));
          print "$nkb"."kiB";
    }
}

print "<br>\n";

$adresa   = "$ENV{'REMOTE_ADDR'}";
$server   = "$ENV{'SERVER_NAME'}";

print "\n<P>";
$time = ($tm2-$tm1);
printf "Sent $nkb kiB from $server to $adresa in $time seconds<br>\n";
print "Approximate download bandwidth speed of your connection is:<br> ";
# to not divide accidentaly by zero we accept inacurrancy of 0.001s
$speed = $nkb*$kb/($time+0.001);
$speedkb = $speed/$kb;
$speedkbps = 8*$speed/$kb;
$speedMbps = $speedkbps/$kb;
$speedMBps = $speed/$kb/$kb;
printf "%.2f B/s = %.2f kib/s =  <b> %.2f Mbit/s</b><br> \n", $speed, $speedkbps, $speedMbps;
printf "%.2f B/s = %.2f kiB/s =  <b> %.2f MB/s</b><br> \n", $speed, $speedkb, $speedMBps;
$date = `date`;
print "<BR>$date\n<BR>";
print "<A HREF=\"http://sandbox.cz/~covex/czfree/index.html\#bander\">BanderDyn speed test</A>\n";

#print "</CENTER>\n";
print "</BODY></HTML>";
