#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use Fcntl qw(:flock :seek);
use strict;

print header;

# some definitions...
my(@ad_ids) = ();       # array for ALL ad ids
my(@ok_ads) = ();       # array for ads that haven't exceeced the max count
my(%data) = ();         # hash for storing the raw data

open(F,"+<addata.txt") or &dienice("Can't open data file: $!");
flock(F,LOCK_EX);      # exclusive lock
seek(F,0,SEEK_SET);    # rewind to beginning of file
while (my $line = <F>) {
    chomp($line);
    my($id,$img,$url,$alt,$max,$count,$clicks) = split(/\|/,$line);
    $data{$id} = $line;
    push(@ad_ids,$id);
    if ($count < $max) {
	push(@ok_ads,$id);
    }    
}
# pick a random ID#
my $pick = $ok_ads[int(rand(@ok_ads))];

if ($pick < 0) {
    # there's been some problem.  Abort.
    exit;
}

# split the ad data line again and print out the ad
my($id,$img,$url,$alt,$max,$count,$clicks) = split(/\|/,$data{$pick});
print qq(<a href="click.cgi?$id"><img src="$img" alt="$alt"></a>\n);

# increment the counter and save it back to the %data hash
$count = $count + 1;
$data{$pick} = qq($id|$img|$url|$alt|$max|$count|$clicks);

seek(F,0,SEEK_SET);             # rewind file to beginning... 
foreach my $i (@ad_ids) {       # and overwrite it.
   print F $data{$i}, "\n";
}
close(F);