#!/usr/bin/perl -wT
use CGI qw(:standard);
use CGI::Carp qw(warningsToBrowser fatalsToBrowser);
use strict;
use GD;

my $imgdir = "countimg";    # the images directory

my $count     = $ENV{'QUERY_STRING'};
my $numdigits = length($count);        # figure out how many digits there are
my @digits    = split ( //, $count );  # split it into an array of single digits

# read in one digit 
my $tmp = GD::Image->newFromPng("$imgdir/0.png");

# get the width and height
my ( $width, $height ) = $tmp->getBounds;

# destroy (undefine) the temp image
undef $tmp;

# for now, make a guess about the total width of the image
# by multiplying the width of the 0 by the number of digits
my $maxwidth = $width * ( $#digits + 1 );

# create a temp image for storing the counter
my $newimg = new GD::Image( $maxwidth, $height ) or die "can't create newimg";

# counter for the actual width
my $actual_width = 0;

# now fill the temp image with the digits
foreach my $i (@digits) {

    # read in that digit's image;
    my $tmp = GD::Image->newFromPng("$imgdir/$i.png");

    # get its width/height
    my ( $tmpx, $tmpy ) = $tmp->getBounds;

    # copy that digit onto the end of the counter image
    $newimg->copy( $tmp, $actual_width, 0, 0, 0, $tmpx, $tmpy );

    # increment the total width (so far) of the counter image
    $actual_width = $actual_width + $tmpx;
    undef $tmp;
}

# now create the FINAL counter image with the exact height/width
my $finalimg = new GD::Image( $actual_width, $height );

# copy the tmp counter to the final one
$finalimg->copy( $newimg, 0, 0, 0, 0, $actual_width, $height );

# make the final image interlaced
$finalimg->interlaced(1);

# get a the raw PNG image data
my $img_data = $finalimg->png;

# print a content-type header indicating that this is an image
print header('image/png');

# set the output filehandle to binary mode
binmode(STDOUT);

# now print the actual image data
print $img_data;