import java.io.File;
import java.io.IOException;
import java.awt.image.BufferedImage;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import javax.imageio.ImageIO;
import java.awt.geom.Rectangle2D;
import java.io.RandomAccessFile;

public class ImgCounterCgi {

    public static void writePNGImageString(
	int imgWidth, int imgHeight, String str ) throws IOException
    {
        BufferedImage image =
	    new BufferedImage( imgWidth, imgHeight, BufferedImage.TYPE_3BYTE_BGR);
	Graphics2D g2d = image.createGraphics(); 
	Font f = new Font( "Monospaced", Font.BOLD, 14 );
	g2d.setFont( f );
	FontMetrics fm = g2d.getFontMetrics();
	g2d.setColor( Color.white );
	g2d.fillRect(0, 0, imgWidth, imgHeight );
	g2d.setColor( Color.red );

	Rectangle2D bounds = fm.getStringBounds( str, g2d );
	int w = (int)bounds.getWidth();
	int h = (int)bounds.getHeight();
	int x = (imgWidth - w)/2;
	int y = imgHeight - (imgHeight - h)/2;
	g2d.drawString( str, x, y );

	ImageIO.write(image, "png", System.out );
    }
    public static void main( String[] args ) {
	int count = -1;
	try {
	    File file = new File("counter");
	    boolean flag =  file.exists() ;
	    RandomAccessFile fw = new RandomAccessFile( file, "rws" );
	    // handle an initially empty file
	    if ( flag ) {
		fw.seek( 0 );
		count = fw.readInt();
	    }
	    else {
		count = 0;
	    }
	    fw.seek( 0 );
	    fw.writeInt( count+1 );
	    fw.close();
	}
	catch( Exception ex ) {
	    // ignore exception, use count -1 to indicate error
	}
	String str;
	if ( count < 0 ) {
	    str = "no count";
	}
	else {
	    str = String.format( "%07d", count );
	}
	try {
	    System.out.print("Content-Type: image/png\r\n\r\n");
	    writePNGImageString( 90, 20, str );
	}
	catch( Exception ex ) {
	}
    }
}
