#!/usr/bin/env perl

use strict;

use Time::HiRes qw(time);
use Graphics::Framebuffer;

my $args = join('',@ARGV);

my $dev = 0;
if ($args =~ /(\d+)/) {
    $dev = $1;
}

my $f = Graphics::Framebuffer->new('FILE_MODE' => 0, 'FB_DEVICE' => "/dev/fb$dev");

my $fm = Graphics::Framebuffer->new('FILE_MODE' => 1, 'FB_DEVICE' => "/dev/fb$dev", 'SPLASH' => 0);

$f->cls('OFF');
my @t;
my $x     = $f->{'XRES'} / 2;
my $y     = $f->{'YRES'} / 2;
my $start = time;

$f->set_color({'red' => 255, 'green' => 0, 'blue' => 0});
for (my $radius = 10 ; $radius < $y ; $radius += 4) {
    $f->circle({'x' => $x, 'y' => $y, 'radius' => $radius, 'filled' => 1});
}

push(@t, sprintf('%.02f', time - $start));

$start = time;

$fm->set_color({'red' => 0, 'green' => 0, 'blue' => 255});
for (my $radius = 10 ; $radius < $y ; $radius += 4) {
    $fm->circle({'x' => $x, 'y' => $y, 'radius' => $radius, 'filled' => 1});
}

push(@t, sprintf('%.02f', time - $start));

$f->set_color({'red' => 255, 'green' => 255, 'blue' => 0});
$start = time;
for (my $xx = $y ; $xx >= 0 ; $xx--) {
    $f->box({'x' => $xx, 'y' => $xx, 'xx' => $f->{'XRES'} - $xx, 'yy' => $f->{'YRES'} - $xx});
}

push(@t, sprintf('%.02f', time - $start));

$fm->set_color({'red' => 0, 'green' => 255, 'blue' => 255});
$start = time;

for (my $xx = $y ; $xx >= 0 ; $xx--) {
    $fm->box({'x' => $xx, 'y' => $xx, 'xx' => $fm->{'XRES'} - $xx, 'yy' => $fm->{'YRES'} - $xx});
}

push(@t, sprintf('%.02f', time - $start));

$start = time;
$f->set_color({'red' => 0, 'green' => 255, 'blue' => 0});

foreach my $xx (0 .. $f->{'XRES'}) {
    $f->line({'x' => $xx, 'y' => 0, 'xx' => $xx, 'yy' => $f->{'YRES'}});
}
push(@t, sprintf('%.02f', time - $start));

$start = time;
$fm->set_color({'red' => 255, 'green' => 0, 'blue' => 255});

foreach my $xx (0 .. $f->{'XRES'}) {
    $fm->line({'x' => $xx, 'y' => 0, 'xx' => $xx, 'yy' => $f->{'YRES'}});
}
push(@t, sprintf('%.02f', time - $start));
$f->cls('ON');

print STDERR "CIRCLE STRING: $t[0]\n  CIRCLE FILE: $t[1]\n   BOX STRING: $t[2]\n     BOX FILE: $t[3]\n  LINE STRING: $t[4]\n    LINE FILE: $t[5]\n\n";

my $file_average   = ($t[1] + $t[3] + $t[5]) / 3;
my $string_average = ($t[0] + $t[2] + $t[4]) / 3;

print STDERR sprintf('Memory Mapped String Mode Average: %.02f',$string_average);
print STDERR sprintf('File Handle Mode Average: %.02f',$file_average),"\n\n";

if ($file_average > $string_average) {
    print STDERR "It is recommended you use the default Mmap string mode for your framebuffer device.\n";
} else {
    print STDERR "It is recommend you use the File Handle mode for your framebuffer device.\n";
}
