#!/usr/bin/perl

use warnings;
use strict;

package CGI::Counter;

our $VERSION=1.0;

our @ISA='Exporter';
our @EXPORT=qw(new value inc);
require Exporter;


sub new($$)
{
  my ($class_name, $file_name)=@_;
  
  defined $file_name or 
    die __PACKAGE__ . " constructor must known counter file name";

  bless {file=>$file_name}, $class_name;
}

sub load_counter($)
{
  my ($self)=@_;

  unless (-f $self->{file})
  {
    $self->{counter}=0;
    return;
  }
  open my $counter_file, '<', $self->{file} or 
    die "Can not open file '$self->{file}': $!";
 
  flock $counter_file, 2;
  my $value=<$counter_file>;
  
  $self->{counter}=0;
  defined $value or return;
  $value=~/(\d+)/ and $self->{counter}=$1;
}

sub inc($)
{
  my ($self)=@_;
  
  my $cf;

  unless (-f $self->{file})
  {
    open $cf, ">", $self->{file}
      or die "Can not create file '$self->{file}': $!";
    flock $cf, 2;
    print $cf "0\n";
  }
  else
  {
    open $cf, "+<", $self->{file}
      or die "Can not open file '$self->{file}': $!";
    flock $cf, 2;
  }
  seek $cf, 0, 0;

  $self->{counter}=<$cf>;
  defined $self->{counter} or $self->{couter}=0;
  $self->{couter}=~s/\s+//g;
  $self->{counter}++;

  seek $cf, 0, 0;
  print $cf "$self->{counter}\n";
}

sub value($)
{
  my ($self)=@_;
  defined $self->{counter} or $self->load_counter;
  $self->{counter};
}

__END__
=pod

=head1 NAME

CGI::Counter - This is easy counter for CGI scripts

=head1 SYNOPSYS

use CGI::Counter;

my $counter=CGI::Counter('file_counter');

print $counter->value, "\n";

$counter->inc;

print $counter->value, "\n";

=head1 METHODS


B<new(file_name)> - Constructor;


B<inc()> - increment counter;

B<value()> - return counter value.

=head1 AUTHOR

B<Dmitry E. Oboukhov> E<lt>dimka@avanto.orgE<gt>

=head1 COPYRIGHT

Copyright (C) B<Dmitry E. Oboukhov> E<lt>dimka@avanto.orgE<gt>

This program is free software; you can redistribute it and/or modify
it under the terms of the B<GNU General Public License> as published by
the Free Software Foundation; version 2 of the License

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA


=head1 SCRIPT CATEGORIES

CGI

=head1 OSNAMES

any

=cut
