#!/usr/local/bin/perl
require'./gifcat.pl';

#-- 初期設定
# カウント数ファイル
$data_file = "./count.dat";

# 数字画像ディレクトリ（0.gif〜9.gifのファイル名で保存）
$imgdir = "./image";

# 表示桁数
$figure = 5;





# ファイルロック
$lfh = &file_lock() || die 'Busy!';

# カウントデータファイル読み込み
@LINES = &loadfile($data_file);

# カウント
$count = $LINES[0]+1;

# カウント数をカウントデータファイルに書き込み
&regist($data_file,$count) || die 'Regist Error!';

# ファイルアンロック
&file_unlock($lfh);

# カウンター表示
&gif($count,$figure);

exit;

sub loadfile{

	my(@LINES);
	open (IN,$_[0]);
	@LINES = <IN>;
	close (IN);
	return @LINES;
}


sub regist{

	my($file_dat, @LINES) = @_ ;
	open(OUT, "+< $file_dat") || return undef;
	seek(OUT, 0, 0);
	print OUT (@LINES);
	close (OUT);
    return 1;
}


sub file_lock{
	my %lfh = (dir => './lockdir/', basename => 'lockfile',
		timeout => 60, trytime => 10, @_);
	$lfh{path} = $lfh{dir} . $lfh{basename};

	for (my $i = 0; $i < $lfh{trytime}; $i++, sleep 1) {
		return \%lfh if (rename($lfh{path}, $lfh{current} = $lfh{path} . time));
	}
	opendir(LOCKDIR, $lfh{dir});
	my @filelist = readdir(LOCKDIR);
	closedir(LOCKDIR);
	foreach (@filelist) {
		if (/^$lfh{basename}(\d+)/) {
			return \%lfh if (time - $1 > $lfh{timeout} and
			rename($lfh{dir} . $_, $lfh{current} = $lfh{path} . time));
			last;
		}
	}
	undef;
}
sub file_unlock{
	rename($_[0]->{current}, $_[0]->{path});
}


sub gif{
	my($count,$num,@img,$figure);
    $count = $_[0];
    $figure = $_[1];
    
    # 桁が足りなかったら足す
	$count = "0".$count while (length($count) < $figure);

	foreach(0..(length($count)-1)){
		$num = substr($count,$_,1);
		push(@img,"$imgdir/$num\.gif");
	}
	print "Content-type: image/gif\n\n";
	binmode(STDOUT);
	print &gifcat'gifcat(@img);
}


