#include "Complex.cc"
#include <iostream>
#include "TH2F.h"
#include "TBenchmark.h"
#include "TStyle.h"

using namespace std;

int mandel(Complex point){
  Complex temp = point;
  int iter=0;
  const int max_iter=200;
  const double soglia=100;

  while ((iter++)<max_iter && temp.mag2()< soglia){
    temp = temp*temp+point;
    //cout << "temp " << temp << " " << temp.mag2() << endl;
  }
  return iter;
}

void Mandel(double minx=-2.1, double maxx=0.5,
            double miny=-1.2, double maxy=1.2) {
  gBenchmark->Start("mandel");
  int nbinx=1000;
  int nbiny=1000;

  /// Zoom cuspide
  //int nbinx=1000;
  minx= -1.05;
  maxx= -0.66;
  // int nbiny=1000;
  miny= -0.29;
  maxy= -0.03;

  // // / Zoom interessante
  // // int nbinx=1000;
  // minx= -0.19;
  // maxx= -0.13;
  // //int nbiny=1000;
  // miny= -1.09;
  // maxy= -0.98;

  /// Zoom ancora piu' profondo
  // int nbinx=1000;
  // minx= -0.1753;
  // maxx= -0.1739;
  // int nbiny=1000;
  // miny= -1.0725;
  // maxy= -1.0705;

  TH2F hMan("mandel","Mandelbrot",nbinx,minx,maxx,nbiny,miny,maxy);

  for (int ix=0; ix<nbinx; ++ix){
    for (int iy=0; iy<nbiny; ++iy){
      // loop e' sui bin, trasformo il bin in x,y
      double x = (ix+0.5)*(maxx-minx)/nbinx+minx;
      double y = (iy+0.5)*(maxy-miny)/nbiny+miny;

      Complex point(x,y);
      int iter=mandel(point);
      //cout <<"point "<< point << " iter " << iter << endl;
      //hMan.SetBinContent(ix+1,iy+1,iter);
      hMan.Fill(point.re(), point.im(),iter);
    }
    //hMan.DrawCopy("col");
  }

  gStyle->SetOptStat(0);

  hMan.DrawCopy("col");
  gBenchmark->Stop("mandel");
  gBenchmark->Print("mandel");

}