#!/usr/local/bin/perl
if (defined($ENV{"PATH_TRANSLATED"}) ) {
    $path = $ENV{"PATH_TRANSLATED"} # get file from path info
}
else {
    &f_error("No file specified\n");
}
$file     = $path;               # Path to file to be processed
$cnt_file = $path;
$cnt_file =~ s/.*\///;           # Extract counter filename string
$path     =~ s/\/[\w-.;~]*$/\//; # get path to directory

$cnt_file = $path.".".$cnt_file; # counter filename=path/filename

if( !(-e $cnt_file) ) {          # Create count file if it 
                                 # doesn't exist
   open(CNTFILE, "> $cnt_file") || 
           &f_error("Unable to create count file\n");    
   print CNTFILE "0";
   close(CNTFILE);
}
$loops = 0;                     # try 4 times to lock count file
while ( flock($cnt_file,2) == -1 )  {
  $loops++;
  if( $loops > 4) {
     $cnt = "-1 (Unable to lock counter)\n";
     goto PROCESS;                  # If unable to lock, skip it.
  }
     sleep 1;
}
open(CNTFILE, "+< $cnt_file")       # open the counter file
         || &f_error("Unable to open counter file\n");
$cnt = <CNTFILE>;                   # get the current count
$cnt++;                             # increment count by one
seek(CNTFILE, 0, 0);                # rewind to start of file
print CNTFILE "$cnt";               # write out new count
close(CNTFILE);                     # close the count file
flock($cntfile, 8);                 # Unlock the count file

PROCESS:
open(FILE, $file)                   # Open file to process
      || &f_error("Unable to open file for processing\n");
@array= <FILE>;                     # Read in the file
close(FILE);
                                    # Print out the document
print "Content-type: text/html\n\n";
foreach (@array) {                  # scan for special string: 
   s/<!-- counter -->/ $cnt /i;     # replace it by the count
   print $_;
}
# Error Handling Subroutine
sub f_error {
  print "Content-type text/plain\n\n";
  print "<HTML><HEAD>\n<TITLE>Error In Counter Script</TITLE>";
  print "\n</HEAD><BODY>\n<h2>Error</h2>\n<P>Error message: $_[0]";
  print "\n<P> Please report this problem to someone.";
  print "\n</BODY></HTML>";
  die;
}

