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

my $ad_id = $ENV{QUERY_STRING};

# some definitions...
my(@ad_ids) = ();       # array for ALL ad ids
my(%data) = ();         # hash for storing the raw data

my $redirect = "";      # this will store the url to redirect to.

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 ($id == $ad_id) {
       $redirect = $url;
       $clicks = $clicks + 1;
       $data{$id} = 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);

if ($redirect ne "") {
   print redirect($redirect);
} else {
   print header;
   print start_html("Error");
   print qq(<h2>Error</h2>\n);
   print qq(<p>That ad wasn't found.</p>\n);
   print end_html;
}