#!/usr/athena/bin/perl

use Fcntl;

my $referer = $ENV{'HTTP_REFERER'};
if (substr($referer,0,33) eq "http://homepage.mac.com/gapodaca/") {
    print "Content-Type: image/jpeg\nContent-Length: 2\n\nX\n";
    exit 0;
}

sub png {
  my($num) = @_;
  print("Content-type: image/png\n\n");
  if ($num !~ /^\d+$/) {
    exit;
  }
  my $filename = '/var/www/data/pngs/' . $num . '.png';
  if (-e $filename) {
      open(PNG,$filename) || exit;
      my $d;
      sysread(PNG,$d,2000);
      close PNG;
      print $d;
      exit;
  }
  require "GD.pm";
  my $digits = 1 + int(log($num) / log(10));
  my $im = new GD::Image($digits * 8 + 4, 16 + 4);
  my $white = $im->colorAllocate(255,255,255);
  my $black = $im->colorAllocate(0,0,0);
  $im->fill(1,1,$black);
  $im->string(GD::Font->MediumBold,4,3,$num,$white);
  print $im->png();
  close STDOUT;
}

#$LOCK_SH = 1;
#$LOCK_EX = 2;
#$LOCK_NB = 4;
#$LOCK_UN = 8;

$key = $ENV{'PATH_INFO'};

if (($key eq "") || ($key eq "/")) {
# If no key is given, default to directions page.
    print "Location: http://stuff.mit.edu/doc/counter-howto.html\n\n";
} else {
    open(LOCK, ">>/var/www/data/perday.lock");
    my $lock = pack('s s l l s', &F_WRLCK, 0, 0, 0, 0);
    fcntl(LOCK, &F_SETLKW, $lock);
    my %perdaydb;
    dbmopen(%perdaydb, "/var/www/data/perdaydb", 0777);
    my ($start, $ct) = split(" ", $perdaydb{$key});
    if(!$start) { $start = time(); $ct = 0;}
    $ct++;
    $now = time();
    

    $perdaydb{$key} = "$start $ct";
    my $val;
    if(($now-$start) < 86400){
	$val = $ct;
    }
    else{
	$val = int($ct/(($now-$start+10)/86400));
    }
    dbmclose(%perdaydb);
    $lock = pack('s s l l s', &F_UNLCK, 0, 0, 0, 0);
    fcntl(LOCK, &F_SETLK, $lock);
    png($val);
}
