// TO DO: see C version for better RGB handling.

#include "imatrix.h"
#include "ETF.h"
#include "fdog.h"
#include "myvec.h"

#include "CImg/CImg.h"

#include <iostream>
#include <string>
#include <cstdio>

int main (int argc, char *argv[]) 
{
  using namespace std;
  using namespace cimg_library;

  if (argc != 2) {
    fprintf(stderr, "syntax: draw imagefile\n");
    exit(1);
  }

  {
  FILE *test = fopen(argv[1], "rb");
  if (test == NULL) {
    fprintf(stderr, "draw: cannot open %s\n", argv[1]);
    exit(2);
  } else fclose(test);
  }

  CImg<unsigned char> original(argv[1]);

  if (original.width() == 0 || original.height() == 0) {
    fprintf(stderr, "draw: bad image in %s\n", argv[1]);
    exit(3);
  }

  int image_biggest = original.width() > original.height() ? original.width() : original.height();
  imatrix img (image_biggest, image_biggest); // line-finding code seems to need a square matrix
  
  int image_x = img.getRow ();
  int image_y = img.getCol ();

  // Load input image into an imatrix named "img" 

  for (int row = 0; row < image_y; row++) {
    for (int col = 0; col < image_x; col++) {
      img[row][col] = 0;
    }
  }

  for (int row = 0; row < original.height(); row++) {
    for (int col = 0; col < original.width(); col++) {
      img[row][col] = (((original(col,row,2) << 8) | original(col,row,1)) << 8) | original(col,row,0);
    }
  }
  
  //////////////////////////////////////////////////
  fprintf(stderr, "img(%dx%d): %d\n", image_x, image_y, img.crc());
#ifdef DEBUG1
  fprintf(stdout, "# ImageMagick pixel enumeration: %d,%d,255,rgb\n", image_y, image_x);

  for (int row = 0; row < image_x; row++) {
    for (int col = 0; col < image_y; col++) {
      fprintf(stdout, "%d,%d: (%d,%d,%d) #\n", col, row, img[row][col]&255, img[row][col]&255, img[row][col]&255);
    }
  }
  exit(0);
#endif
  //////////////////////////////////////////////////
  ETF e;
  e.init (image_x, image_y);
  
  //e.set(img);               // get gradients from input image
  fprintf(stderr, "before set2: e %f\n", e.crc());
  e.set2 (img);		// get gradients from gradient map
  fprintf(stderr, "e returned from set2 = %f\n", e.crc());
  e.Smooth (4, 2);
  fprintf(stderr, "after Smooth: e %f\n", e.crc());
  
  //////////////////////////////////////////////////////
    
  ///////////////////////////////////////////////////
  double tao = 0.99;
  double thres = 0.7; // 0.7;
  GetFDoG (img, e, 1.0, 3.0, tao);
  fprintf(stderr, "post GetFDog img: %d\n", img.crc());
  GrayThresholding (img, thres);
  fprintf(stderr, "post GrayThresholding img: %d\n", img.crc());

  fprintf(stdout, "# ImageMagick pixel enumeration: %d,%d,255,rgb\n", image_y, image_x);

  for (int row = 0; row < original.height(); row++) {
    for (int col = 0; col < original.width(); col++) {
      fprintf(stdout, "%d,%d: (%d,%d,%d)\n", col, row, img[row][col]&255, img[row][col]&255, img[row][col]&255);
    }
  }
  
  /////////////////////////////////////////////
  exit(0);
  return 0;
} 
