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

print header;
print start_html("Ad Counts");
print qq(<h2 align="CENTER">Ad Counts</h2>);

print qq(<table border=0 width=100%>
    <th align="LEFT">ID</th>
    <th align="LEFT">Ad</th>
    <th align="LEFT">Max</th>
    <th align="LEFT">Hits</th>
    <th align="LEFT">Clicks</th>
    <th align="LEFT">CTR</th>

open(F,"addata.txt") or &dienice("Can't open data file: $!");
flock(F,LOCK_SH);      # shared lock
seek(F,0,SEEK_SET);    # rewind to beginning of file
while (my $line = <F>) {
    my($id,$img,$url,$alt,$max,$count,$clicks) = split(/\|/,$line);
    my $ctr = 0;
    if ($count > 0) {  # prevent divide by zero
       $ctr = ($clicks / $count) * 100;
    $ctr = sprintf("%4.2f%%", $ctr);
    print qq(<tr>
        <td>$id</td> <td>$alt (<a href="$url">$url</a>)</td>
        <td>$max</td> <td>$count</td>
        <td>$clicks</td> <td>$ctr</td> </tr>\n);
print qq(</table>\n);
print qq(<p>CTR: Click-through ratio</p>\n);

print end_html;