#!/usr/bin/perl
$wait=3;
$header="Content-Type: text/html\n\n";
print $header;

$cfile	= 'count7';
$cfiledir = '/home/piataev/public_html/cgi-bin/counts7';
chdir $cfiledir;

open STDERR, ">errors" or print "Oppa";
$lockdir="";
$lockdir=$cfiledir;
$l = lc $ENV{'DOCUMENT_NAME'};
if ($a=&lockfile)
  { print "$a ?? раз"; 
    exit ;
  }

open(F, "$cfile");
@DATA = <F>;
close(F);
foreach (@DATA) {
  ($c, $bl) = split / - /;
  chomp $bl;
  if ($bl eq $l)
  {
    $c++;
    $_ = "$c - $bl\n";
    $tmp = "$cfile$$.tmp";
    open(F, ">$tmp");
    print F @DATA;
    close(F);
    rename("$tmp", $cfile);
    print "$c раз".&Suffix($c);
    &unlockfile ;
    exit
  }
}

open(F, ">>$cfile");
print F "1 - $l\n"; 
close(F);

print "первый раз";
&unlockfile;

sub lockfile
{  
   $tmp="$cfile$$.tmp";
   $lock="$cfile.loc";
   open F,">$tmp" or (print $@,return 1);
   print F $$;
   close F;
   if (-e $lock) {
    for (1..$wait){
       sleep(1); 
       last unless -e $lock
    }
   }
   if ((-e $lock) && (-M $lock<0)){unlink $tmp;
return 2}
   elsif (!rename($tmp,$lock)) {return 3}
   open(LOCK,"<$lock") or return 3;
   $lock_pid=<LOCK>;
   close(LOCK);
   return 2 unless $lock_pid == $$;
   return 0; 
}

sub unlockfile
{
  open (LOCK, "<$lock") or return 1;
  $lock_pid=<LOCK>;
  close(LOCK);
  return 2 unless $lock_pid==$$;
  unlink($lock) or return 3;
  return 0;
}


sub Suffix {
	my ($qnum) = @_;
   my ($suffix) = 'а' if $qnum =~ /[234]$/;
   $suffix = '' if $qnum =~ /156789$/ || $qnum =~ /1.$/;
   return $suffix;
}
