#include <iostream>
#include <sstream>
#include "libfft.h"

using namespace fft;
using namespace std;



int main(int argc, char** argv)
{
   
   try
   {

      Config cfg(argv[1]);
      String img;
      fft::real sR,eR,lpR;
      fft::real t;
      fft::u32 kernelSide;
      cfg["input"].to(img);
      cfg["min_radius"].to(sR);
      cfg["max_radius"].to(eR);
      cfg["lo_pass_radius"].to(lpR);
      cfg["treshhold"].to(t);
      cfg["median_kernel_side"].to(kernelSide);

      


      Array2D<Complex> arr = Array2D<Complex>(imread(img));
      Array2D<Complex> arr2 = arr;
      Array2D<Complex> lopassMask(arr2.W(), arr2.H());
      fft2(arr2);
      fftshift2(arr2);
      fft::abs(arr2).storeGnuPlot("fft.dat",4,4);
      lopassMask.circle(arr2.W() * .5 * lpR, 1, 0);
      arr2 = arr2 * lopassMask;
      ifftshift2(arr2);
      ifft2(arr2);
      //arr2.flipV();
      arr = arr2 - arr;
      //arr.normalize();
      imsave(abs(arr), img + "-flat.png");

      Array2D<Complex> mask(arr.W(), arr.H());
      Array2D<Complex> mask2(arr.W(), arr.H());
      mask.circle(arr.W() * .5 * sR, 0, 1);
      mask2.circle(arr.W() * .5 *eR, 1, 0);
      mask = mask * mask2;
      mask.at(mask.W()/2, mask.H()/2) = 1;

      imsave(fft::abs(mask), img + "-MASK.png");

      fft2(arr);
      fftshift2(arr);
      arr = arr * mask;
      Array2D<fft::real>rr = fft::abs(arr);
      rr.normalize();
      imsave(rr, img + "-mask.png");
      ifftshift2(arr);
      ifft2(arr);
      Array2D<fft::real> rarr = fft::abs(arr);
      rarr.normalize();
      imsave(rarr, img +"-mask2.png");
      cerr << "min-"<<rarr.min() << " max-" << rarr.max() << endl;

      Histogram<fft::real> hist(rarr, 256);
      hist.storeGnuPlot("hist.dat");
      //hist.print();
      fft::real histConvKernel[] = {0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1};
      hist.convolution(histConvKernel, 10);
      hist.storeGnuPlot("histConv.dat");

      
      Histogram<fft::real>::ExtremeValueList maxims = hist.localMax(5);
      cerr << "maxims: ";
      for (u32 i = 0; i < maxims.size(); i++)
      {
	 cerr << "("<< maxims[i].position << "," << maxims[i].value << ")";
      }
      cerr << endl;
      rarr = rarr > t;
      imsave(rarr, img + "-mask3.png");
      Array2D<fft::real> m = rarr.medianFilter(kernelSide);
      imsave(m, img + "-median.png");
   }
   catch(std::exception& ex)
   {
      cerr << ex.what() << endl;
   }

   return 0;

}
