#!/usr/local/bin/perl

$DEBUG = 0;
if (defined($ENV{"PATH_TRANSLATED"}) ) {
    $path = $ENV{"PATH_TRANSLATED"} 
}
else {
    &f_error("No file specified\n");
}
if($DEBUG) {
   print "Content-type: text/plain\n\n";
   print "Translated path = $path\n\n"; 
}

$file     = $path;                  # File to be processed
$cnt_file = $path;
$cnt_file =~ s/.*\///;              # get counter filename
$path     =~ s/\/[\w-.;~]*$/\//;    # get path to directory

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

if($DEBUG) {
   print "File to process   = $file\n"; 
   print "Path to directory = $path\n";
   print "Cnt_file          = $cnt_file\n"; 
}

if( !(-e $cnt_file) ) {             # If count file doesn't exist
   open(CNTFILE, "> $cnt_file") || 
	       &f_error("Unable to create count file\n");    
   print CNTFILE "0";
   close(CNTFILE);
}

$loops = 0;                       # try to lock the count file
while ( flock($cnt_file,2) == -1 )  {
  $loops++;
  if( $loops > 4) {
     $cnt = "-1 (Unable to lock counter)\n";
     goto PROCESS;
  }
     sleep 1;
}

open(CNTFILE, "+< $cnt_file") 
	       || &f_error("Unable to open counter file\n");
$cnt = <CNTFILE>;
$cnt++;
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) 
	|| &f_error("Unable to open file for processing\n");

  @array= <FILE>;
close(FILE);

print "Content-type: text/html\n\n";
foreach (@array) {
   s/<!-- counter -->/ $cnt /i;  
   print $_;
}

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;
}
