#!/usr/bin/perl -w
$| = 1;
my $failures = 0;

while (<>) {
    /^\s*([^ ]+) +([^ ]+) +([^ ]+) +(\[[^]]+\]) +("[^"]*") +([^ ]+) +([^ ]+) +([^ ]*) +\[([^]]*)\]/ && do {
        my ($ip,  $user,   $vhost,  $date,       $req,      $resp,   $bytes,             $header) = ($1, $2, $3, $4, $5, $6, $7, $9);

        my ($refer, $uagent) = qw(- -);

        $header =~ /Referr?er:\s*(.*?)\\r\\n/ && do {
            $refer = $1;
        };
        $header =~ /User-Agent:\s*(.*?)\\r\\n/ && do {
            $uagent = $1;
        };
        $uagent =~ s/%5b/[/g;
        $uagent =~ s/%5d/]/g;

        print "$ip $user $vhost $date $req $resp $bytes \"$refer\" \"$uagent\"\n";
        next;
    };
    $failures++;
}
if ($failures) {
    print STDERR "$failures records ignored\n";
}
