#/usr/bin/perl

use strict;
my $f = '\S+\s+';
my %engines;

my @bnames = ('IE', 'Mozilla', 'Safari', 'Opera', 'Lynx');
my %browsers;
my $count = 0;
my %puzzle;

my $lastGImage;
while (<STDIN>)
{
  my $who;
  my $referer;
  my $agent;

  if (/^(\S+)\s+$f$f$f$f$f$f$f$f$f\"(\S+)\"\s+\"(.*)\"$/o)
  {
      $who = $1;
      $referer = $2;
      $agent = $3;
  }
  
  s/\" .*$//;
  my $e = '';
  next if ($referer =~ /^-?$/);
  if    ($referer =~ /search\.yahoo/)               { $e = 'Yahoo'; }
  elsif ($referer =~ m@^http://images.google@)
  {
      if ($who ne $lastGImage) { $e = 'Google Images'; }
      $lastGImage = $who;
  }
  elsif ($referer =~ m@^http://www.google.*search@) { $e = 'Google'; }
  elsif ($referer =~ m@^http://search.msn.com@)     { $e = 'MSN'; }
  elsif ($referer =~ m@^http://web.ask.com@)        { $e = 'Ask Jeeves'; }
  if ($e)
  {
      $engines{$e}++;
      &browser($agent);
  }
  
}

my $b;

# Turn on from time to time to sanity-check
if (0)
{
    foreach $b (sort keys(%puzzle))
    {
        print "$puzzle{$b} $b\n";
    }
}

$ARGV[0] =~ s/\..*$//;
print "$ARGV[0]\t";
foreach $b (@bnames)
{
    printf "%0.1f\t", 100.0 * $browsers{$b} / $count;
}
print "\n";

print STDERR "Total searches: ", $count, "\n";

sub browser
{
    my $b = shift;
    my $a = '';

    if    ($b =~ /lynx/i) { $a = 'Lynx'; }
    elsif ($b =~ /Safari/i) { $a = 'Safari'; }
    elsif ($b =~ /opera/i) { $a = 'Opera'; }
    elsif ($b =~ /MSIE/) { $a = 'IE'; }
    elsif ($b =~ /Mozilla.*Gecko/) { $a = 'Mozilla'; }

    if ($a)
    {
	$browsers{$a}++;
	$count++;
    }
    else    { $puzzle{$b}++;   }
}
