#!perl -w
use strict;
use List::Util qw(first);

my @lines= map { s/\s*[\r\n]+$//; $_ } <>;

my @articles= ParsePrijsLijst(@lines);

# in the [mb] section the memory and 'dane-elec' low pp are relevant.
for my $key (qw(mb gb speed)) {
    printf("%-19s %7s[%-5s]%7s %-s\n", "type", "pp", $key, "price", "desc");
    print "-" x 77, "\n";

    my $psec;
    print map { 
        my $sep= ($psec && $psec ne $_->{section})?"-" x 77 . "\n" : "";
        $psec= $_->{section};
        sprintf("%s%-19s %7.2f %5d %7.2f %s\n", 
            $sep,
            $_->{section},
            pp($_, $key),
            $_->{$key},
            $_->{price}, 
            $_->{desc});
        } 
        sort { $a->{section} cmp $b->{section} || pp($a,$key) <=> pp($b, $key) } 
        grep { $_->{$key} } @articles;
}
exit(0);

sub pp {
    my ($entry, $key)= @_;

    return $entry->{price}/$entry->{$key};
}

sub ParsePrijsLijst {
    my @lines= @_;

    my @headers= grep { $lines[$_] =~ /^\*{20,}$/ } (0..$#lines);

    my @articles;

    for my $linenr (@headers) {
        my $endline= first { $lines[$_] eq "" } ($linenr..$#lines);

        my $section= $lines[$linenr-3];
        if ($section eq "Dane-Elec Memory")
        {
            $section= "Geheugen";
        }

        push @articles, map { my($artnr, $desc, $price)= /^(\d+)\s+(.*?)\s+(\S+)$/; {section=>$section, nr=>$artnr, desc=>$desc, price=>$price, ParseDescription($desc)} } @lines[$linenr+1..$endline-1];
    }

    return @articles;
}

sub ParseDescription {
    my ($desc)= @_;

    my %info;

    if ($desc =~ /([0-9.]+)\s*GHz\b/i) { $info{speed}= $1*1000; }
    if ($desc =~ /([0-9]+)\s*MHz\b/i) { if (exists $info{speed}) { $info{speed}= $1; } else { $info{busspeed}= $1; } }
    if ($desc =~ /Athlon\s+[MX]P\s*([0-9]+)\b/i) { $info{speed}= $1; }

    if ($desc =~ /(\d+)\s*GB\b/i) { $info{gb}= $1; }
    if ($desc =~ /(\d+)\s*MB\b/i) { if (!exists $info{mb} || $1>$info{mb}) { $info{mb}= $1; } }
    #if ($desc =~ /(\d+)\s*rpm\b/i) { $info{speed}= $1; }
    if ($desc =~ /\bPC(\d+)/) { $info{speed}= $1; }

    # todo: for hd this is 1000
    if (!exists $info{mb} && exists $info{gb} ) { $info{mb}= $info{gb}*1024; }

    return %info;
}

