#!/usr/bin/perl

$count_file = "count.txt";
$digit_dir = "imag";

$flyprog = "cgi-bin/fly -q";
$fly_temp = "cgi-bin/fly_temp.txt";

	### IMAGE SETTINGS ###

$width = "15";
$height = "20";

$il = "1";

$frame_width = "8";
$frame_color = "0,0,0";

# Get the Counter Number And Write New One to File
&get_num;

# Determine Length of Counter Number
$num = $length = length($count);

# Set Individual Counter Numbers Into Associative Array
while ($num > 0) {
   $CHAR{$num} = chop($count);
   $num--;
}

# Determine the Height and Width of the Image
$img_width = (($width * $length) + ($frame_width * 2));
$img_height = (($frame_width * 2) + $height);

# Open the In-File for Commands
open(FLY,">$fly_temp") || die "Can't Open In File For FLY Commands: $!\n";

# Create New Counter Image
print FLY "new\n";
print FLY "size $img_width,$img_height\n";

# If User Wants Frame, Print Commands to the In-File
&make_frame;

# Copy Individual Counter Images Commands to In-File
$j = 1;
while ($j <= $length) {
   print FLY "copy $insert_width,$insert_height,-1,-1,-1,-1,$digit_dir/$CHAR{$j}\.gif\n";
   $insert_width = ($insert_width + $width); 
   $j++;
}

# If they want the image interlaced, make it interlaced
if ($il == 1) {
   print FLY "interlace\n";
}

# Close FLY
close(FLY);

$output = `$flyprog -i $fly_temp`;
print "Content-type: image/gif\n\n";
print "$output";

# Remove Temp File
unlink($fly_temp);

sub get_num {
   open(COUNT,"$count_file") || die "Can't Open Count Data File: $!\n"; 
   $count = <COUNT>;
   close(COUNT);
   if ($count =~ /\n$/) {
      chop($count);
   }

   $count++;

   open(COUNT,">$count_file") || die "Can't Open Count Data File For Writing: $!\n";
   print COUNT "$count";
   close(COUNT);
}

sub make_frame {
   $insert_width = $insert_height = $frame_width;

   $insert_frame = 0;

   while ($insert_frame < $frame_width) {
      $current_width = ($img_width - $insert_frame);
      $current_height = ($img_height - $insert_frame);
 
      print FLY "line 0,$insert_frame,$img_width,$insert_frame,$frame_color\n";
      print FLY "line $insert_frame,0,$insert_frame,$img_height,$frame_color\n";
      print FLY "line $current_width,0,$current_width,$img_height,$frame_color\n";
      print FLY "line $current_height,0,$current_height,$img_width,$frame_color\n";

      $insert_frame++;
   }
}