/*

GRAPHICAL GIF WEB PAGE COUNTER...

Author: Matthew W. Coan
Date: Tue Aug 20 02:05:50 EDT 2013

*/

#include <iostream>
#include <fstream>

#include <stdio.h>
#include <stdlib.h>
extern "C" {
#include <gd.h>
#include <gdfontt.h>
#include <gdfonts.h>
#include <gdfontl.h>
}

using namespace std;

#ifdef BLACK_BG
#define COUNT_FILE "count1.txt"
#else
#define COUNT_FILE "count2.txt"
#endif

int main(void)
{
   gdImagePtr im;
   int bg,fg;
        int count = 0;

   cout << "Content-type: image/gif\r\n\r\n" << flush;

   ifstream in(COUNT_FILE, ios::in);
   if(in) {
      in >> count;
      in.close();
   }

   count++;

   ofstream out(COUNT_FILE, ios::out | ios::trunc);
   if(out) {
      out << count << flush;
      out.close();
   }

   im = gdImageCreate(100, 18);
   if (!im) {
      fprintf(stdout, "can't create image");
      return 1;
   }

#ifndef BLACK_BG
   bg = gdImageColorAllocate(im, 255, 255, 255);

   fg = gdImageColorAllocate(im, 0, 0, 0);
#else
   bg = gdImageColorAllocate(im, 0, 0, 0);
   fg = gdImageColorAllocate(im, 255, 255, 255);
#endif

   gdImageFilledRectangle(im, 0, 0, 100, 15, bg);

   char buffer[100];

   sprintf(buffer, "%d", count);

   gdImageString(im, gdFontLarge, 0, 0, (unsigned char*)buffer, fg);

   gdImageGif(im, stdout);

   fflush(stdout);

   gdImageDestroy(im);

   return 0;
}
