#include "stdafx.h"
#include "EasyBMP.h"
#include <vector>
#include <algorithm>
#include <cmath>
#include <cstdlib>
#define LIMIT 2000
#include<time.h>
#include<omp.h>
#include<complex>
using namespace std;
int  converge(complex<double> C)
{ complex<double> Z;
int i=0;
Z=0;
do{
Z=Z*Z+C;
i++;
}while(i<LIMIT&&norm(Z)<4.0);
return i;
}
int main()
{
	int steps=3000;
int *mand;
omp_set_num_threads(omp_get_num_procs()+1);
mand=(int*) malloc(steps*steps*sizeof(int));
double lowlimit=-1.3,highlimit=1.3,delta;
delta=(highlimit-lowlimit)/(double)steps;
double startime=omp_get_wtime();
#pragma omp parallel 
{
#pragma omp single 
	{
//#pragma omp  for schedule(static,1) 
for(int i=0;i<steps;i++)
{
#pragma omp task	
for(int j=0;j<steps;j++)
{
	complex<double> K;
	K=complex<double>(delta* (double) i-2,delta*(double) j+lowlimit);
	
mand[i*steps+j]=converge(K);
}
//if(i%100==0)cout << i<< endl;
}
	}// End Single

} // End Parallel
cout << "Tempo : "<< omp_get_wtime()-startime << endl; 
int count=0;
BMP Mandel;
Mandel.SetSize(steps,steps);
Mandel.SetBitDepth(16);
#pragma omp parallel for  reduction(+:count)// collapse(2) 33554431

for(int i=0;i<steps;i++)
for(int j=0;j<steps;j++)
{RGBApixel Pix;
	if (mand[i*steps+j]==LIMIT){
	
	Pix.Blue=255*mand[i*steps+j]/2000;
	Pix.Green=255;
	Pix.Red=255;
count++;
}else{
	Pix.Blue=255*mand[i*steps+j]/2000;
	Pix.Green=0;
	Pix.Red=255*mand[i*steps+j]/2000;
	
}
Mandel.SetPixel(i,j,Pix);
}
Mandel.WriteToFile("C:/Users/Giuseppe/Desktop/Mandel.bmp");
	cout << " " << count <<endl ;
	free(mand);
}