/*
      _______                          .__ .__   .__   .__                 
      \      \    ____   __ __ _______ |__||  |  |  |  |__|  ____    ____  
      /   |   \ _/ __ \ |  |  \\_  __ \|  ||  |  |  |  |  | /  _ \  /    \ 
     /    |    \\  ___/ |  |  / |  | \/|  ||  |__|  |__|  |(  <_> )|   |  \
     \____|__  / \___  >|____/  |__|   |__||____/|____/|__| \____/ |___|  /
    =========\/======\/=================================================\/==
  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 <fstream>
#include <sstream>
#include <cmath>

//  LOCAL

#include "CounterMulti.h"

int
extract_digit(long double num, int width, int pos)
{
  --width;
  int digit=0;
  long double x;
  double power_of_ten;
  for (int digit_pos=width; digit_pos>=0; digit_pos--) {
    power_of_ten = pow(10, digit_pos);
    if (num >= power_of_ten) {
      x = int(num / power_of_ten);
      if (digit_pos == width-pos+1) {
        digit = int(x);
      }
      num -= (x*power_of_ten);
    }
  }
  return digit;
}

int
main()
{
  int hits=0;
  int pos=-1;
  int width=-1;
  std::string path;

  char *qs;
  qs = getenv("QUERY_STRING");
  if (qs) {
    std::string q(qs, strlen(qs));
    std::stringstream isstr;
    isstr.str(q);
    char sep;
    isstr >> pos;  // no error checking
    isstr >> sep;
    isstr >> width; // no error checking
    isstr >> sep;
    isstr >> path;
  }

  CounterMulti cm;

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

  int digit = extract_digit(hits, width, pos);

  std::stringstream ss;
  ss.str("");
  if (0 == path.size()) {
    path="/www/neurillion/images/digits/default"; // no trailing / on dir ...
  }
  ss << path << "/" << digit << ".gif";
  std::string type="gif";
  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::ifstream i(ss.str().c_str());

  if (i) {
    i.seekg(0);
    std::cout << i.rdbuf();
  } else {
    static const char gif1x1t[] = "\x47\x49\x46\x38\x39\x61\x01\x00\x01\x00\x80\x00\x00\xff\xff\xff\xff\xff\xff\x21\xf9\x04\x01\x0a\x00\x01\x00\x2c\x00\x00\x00\x00\x01\x00\x01\x00\x00\x02\x02\x4c\x01\x00\x3b\x00";
    std::string gif(gif1x1t,sizeof(gif1x1t));
    std::cout << gif;
  }

  return 0;
}
