#!/usr/bin/perl

$dataFile = "/home/jonxon/public_html/counter/index.txt";
$ipFile = "/home/jonxon/public_html/counter/index.ip";
$image = "/home/jonxon/public_html/counter/dot.gif";
$lengthOfList = 30;

# Should this one be counted??
# Check the IP address...
open (IPS, "$ipFile");
@ips = <IPS>;
close (IPS);
$newIP = $ENV{'REMOTE_ADDR'};
$found = 0;
foreach $item(@ips) {
  ($thisIP, $rest) = split (/::/,  $item, 2);
  if ("$newIP" =~ "$thisIP")  {
    $found = 1;
  }
}
if ($found == 0)  {
# Ok, this is a new ip address, increment the counter and add the ip to the list
# Hemtar datum
#print "FOUND";
  ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst) = gmtime(time);
  $mon++;
  $hour = $hour + 2;
  if (($mon>10 || $mon<3) || ($mon==3 && $mday<26) || ($mon==10 && $mday>28))
  {
     $hour = $hour - 1;
  }
   
  if($hour > 23)  {
    $hour = $hour - 24;
    $mday++;
    if ($mday>31)  {
      $mday = $mday - 31;
      $mon++;
    }
    if ($mon > 12)  {
      $mon = 1;
      $year++;
    }
  }
  $year = $year + 1900;
  $datum = "$year-$mon-$mday  $hour:$min:$sec";                               

  open (IPS, ">$ipFile");
  print IPS join('::', "$newIP", "$datum #"), "\n";
  $nr = @ips;
  $pos = 0;
  while ($pos < $nr && $pos < $lengthOfList)  {
    print IPS $ips[$pos]; 
    $pos = $pos + 1;
  }
  close (IPS);
  open (COUNT, "$dataFile");
  @count = <COUNT>;
  close (COUNT);
  $count[0] = $count[0] + 1;
  if ($count[0] >= 1000)  {
    $count[1] = $count[1] + 1;
    $count[0] = $count[0] - 1000;
  }

  open (COUNT, ">$dataFile");
  print COUNT "$count[0]\n";
  print COUNT "$count[1]";
  close (COUNT);
}
open (DOT, "$image");
@dot = <DOT>;
close (DOT);

print "Content-type: image/gif\n\n";
print @dot;
