#!/usr/bin/perl
# Get form data #
if ($ENV{'REQUEST_METHOD'} eq "GET") {
  $buffer = $ENV{'QUERY_STRING'};
} else {
  read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
  ($name, $value) = split(/=/, $pair);
  $value =~ tr/+/ /;
  $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
  $FORM{$name} = $value;
}

$Counter = 'countlink.log';
$conv = 'conv.dbs';
$banner_type = $FORM{'b'};
$fromlink = $FORM{'f'};
$tolink = $FORM{'l'};

&convertdbs();

open (CNT,"+<$Counter") || &endIt;
#flock (CNT,2); 
seek (CNT,0,0);
@infile = <CNT>;

$record = 0;
$correctspot = 'N';

while (($correctspot eq 'N') && ($record <= $#infile))  
{ ($count,$tolinkn,$fromlinkn,$banner_typen,$eol) = split(/\|/,$infile[$record]);
  if (($tolinkn eq $tolink)and($fromlinkn eq $fromlink)and($banner_typen eq $banner_type))
    {$count++;
    $infile[$record] = join ("\|",$count,$tolink,$fromlink,$banner_type,"\n");
    $correctspot = 'Y';
    }
  $record++;
}
if ($correctspot eq 'N')
{ $count = 1;
  $newrecord = join ("\|",$count,$tolink,$fromlink,$banner_type,"\n");
  push @infile, $newrecord;
}

@outfile = sort {($b =~ /(\d+)/)[0] <=> ($a =~ /(\d+)/)[0]} @infile;

seek (CNT,0,0);
print (CNT @outfile);
truncate (CNT,tell(CNT));
close (CNT);
#############
	print "Content-type: text/html\n";
	print "Location: http://$tolink\n\n";

sub convertdbs {
open(DBS, "$conv");
while ($dbs = <DBS>) {
  ($cod, $value, $zero) = split(/=/, $dbs);
  if ($fromlink eq $cod) {
	$fromlink = $value;
 	}
  if ($tolink eq $cod) {
	$tolink = $value;
 	}
  }
close(DBS);
}

sub endIt # exit on error
{ exit;
} # end endIt
