#!/usr/bin/perl

## incrementCounter.pl :: If you send this routine the name of the counter file
## it will open the file if it exists and increment the number by one.
## return the new number and also write the new number to the file.
## nothing expensive about his.

sub incrementCounter
{
	my($counterFilename)=@_;
	my($counter)=0;
	my($lockfile)=$counterFilename."lock";

	# if counter file is locked wait.
	while(-e $lockfile)
	{
		sleep(1);
	}

	##lock counter file
	open(FILE,">".$lockfile);
	close(FILE);


	if (-e $counterFilename)
	{
		open(FILE,$counterFilename);
		$counter=<FILE>;
		close(FILE);
	}
	$counter++;
	
	open(FILE, ">".$counterFilename);
	print FILE $counter,"\n";
	close(FILE);

	##unlock counter file
	unlink($lockfile);
	
	return $counter;
}
1;
	

