#!/usr/bin/perl

# Fetch parameter
$id = param("id");

# Constants
$COUNTERFNAME = "../data/countData.js";
$COUNSEMAPHORE = $COUNTERFNAME . ".lock";
# (also look for comments "change" below)

# Default (initial) values
$imagetype = 'image/jpeg';
$name = "undefined";
$imageFile = "";

# Set values based on id - change these values
if($id eq "conret") {
  $name = "ConRetSite3Visit";
  $imageFile = "../images/retlogo80.gif";
  $imagetype = 'image/gif';
}
elsif($id eq "conmco") {
  $name = "ConMcoSite3Visit";
  $imageFile = "../images/mcologo80.gif";
  $imagetype = 'image/gif';
}
elsif($id eq "conrethelp") {
  $name = "ConRetHelpVisit";
  $imageFile = "../images/retlogo80.gif";
  $imagetype = 'image/gif';
}


use CGI qw(:all);


#===== Bikin log file ==========

  #----------- COUNT FILE ------------
    
    %count = ();
    
    # Open semaphore file
    $retries = 0;
    while(1) {
	    if(open(LOCK, ">$COUNSEMAPHORE")) 
	    {	 last;	}
    	$retries++;
	    if($retries > 10) 
		  {  die "Can't open $COUNSEMAPHORE ($!)"; }
		  select(undef, undef, undef, 0.02); # pause 20ms
    }
    flock(LOCK, LOCK_EX);
    
    # After succeed (meaning no other process using the counter file, open it)
    if (open CTFILE, "<$COUNTERFNAME") # Open for reading
    {
      while (<CTFILE>)
      {
        my $line = $_; chomp $line;
        @arr = split(/ *= */, $line);
        $count{$arr[0]} = $arr[1];
      }
    }
    close CTFILE;
    
    $count{$name}++;

    open CTFILE, ">$COUNTERFNAME"; # Open again for writing
    for my $key (keys(%count))
    { print CTFILE $key ." = ". $count{$key} . "\n"; }
    close CTFILE;
    close LOCK;

        
#====== Display image ==========
  
  print header(-type => $imagetype); # Ini generate HTML tag
  
  open(IMAGE, $imageFile) || exit;
  
  print <IMAGE>;
  close(IMAGE);
  
  exit 0;
  