/*
      _______                          .__ .__   .__   .__                 
      \      \    ____   __ __ _______ |__||  |  |  |  |__|  ____    ____  
      /   |   \ _/ __ \ |  |  \\_  __ \|  ||  |  |  |  |  | /  _ \  /    \ 
     /    |    \\  ___/ |  |  / |  | \/|  ||  |__|  |__|  |(  <_> )|   |  \
     \____|__  / \___  >|____/  |__|   |__||____/|____/|__| \____/ |___|  /
    =========\/======\/=================================================\/==
  v0.01 04/JUL/2007 © Copyright 2007-2007 Scott D. Yelich SOME RIGHTS RESERVED
 .,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.,-*~'`^`'~*-,._.-*~'`^`'~*-,._.,-*~'`^`'~*-,. 


  LICENSE:  Creative Commons Attribution 3.0 License.
  SEE:      http://creativecommons.org/licenses/by/3.0/


  Sun Jul 29 21:33:38 EDT 2007, v0.02 sdy

  This is a *very* simple program written to do a web page
  hit counter using sqlite3.

*/

//  C++

#include <iostream>
#include <iomanip>
#include <sstream>

//  LOCAL

#include "Counter.h"
#include "Gd.h"

int
main()
{
  int hits=0;
  int width=8;
  std::string font;
  int color;
  int point_size=12;

  char *qs;
  qs = getenv("QUERY_STRING");
  if (qs) {
    std::string q(qs,strlen(qs));
    std::stringstream isstr;
    isstr.str(q);
    isstr >> width; // no error checking
    isstr.ignore(1);
    isstr >> point_size;  // no error checking
    isstr.ignore(1);
    //    isstr >> color;
    isstr >> std::noskipws >> std::hex >> color;
    isstr.ignore(1);
    isstr >> font;
  }

  Counter cm;

  char * referer_cstr = getenv("HTTP_REFERER");
  if (referer_cstr) {
    std::string page(referer_cstr, strlen(referer_cstr));
    hits = cm.hit(page);
  }

  std::string type="png";
  std::cout << "Content-Type:  image/" << type << std::endl
    << "Expires: 0" << std::endl
    << "Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0" << std::endl
    << "Pragma: no-cache" << std::endl
    << std::endl;

  std::ostringstream ss;
  ss.str("");

  ss << std::setw(width);
  ss << std::right;
  ss << std::setfill( '0' );
  ss << std::dec;

  ss << hits;
  std::string s(ss.str());

  Gd gd;
  gd.set_point_size(point_size);
  gd.set_RGB(color>>16&255,color>>8&255,color&255);
  gd.set_font(font);
  gd.make_img(s);
  gd.to_stdout();

  return 0;
}
