int main(int argc, char* argv[]) {

  //Declare Images buffer
  Image input1, input2;
  Image output;

  //Reading a greyscale image
  input2.Load("./img/background_image.pgm");
  input1.Load("./img/input_image.pgm");
  
  // allocate the output_image
  output.Build(input1.width, input1.height, input1.bpp);

  //copia dell'immagine, copiando i buffer
  for (int j=1; j<input1.height; ++j){
    for (int i=1; i<input1.width; ++i){
      int index = i + j * input1.width;

      if(input1.buffer[index] > input2.buffer[index])
        output.buffer[index] = 0;
      else
        output.buffer[index] = input2.buffer[index] - input1.buffer[index];

//      abs(input1.buffer[i] - input2.buffer[i]) > 30 ? output.buffer[i] = input1.buffer[i] : output.buffer[i] = 0;

#ifdef BINARIZATION
      if(output.buffer[index] > SOGLIA)
        output.buffer[index] = 255;
      else
        output.buffer[index] = 0;
#endif
    }
  }

  //Writing an image
  output.Save("./img/07_differenza_immagini.pgm");

  return 0;
}
int main(int argc, char** argv){
	if(argc < 2){
		std::cout << "Usage: " << argv[0] << " [pgm_image]\n";
		return -1;
	}
	
	Image input;
	Image output;

	input.Load(argv[1]);
	if(input.bpp != 8){
		std::cout << "The algorithm require a ppm image\n";
		return -1;
	}
	
	int th = 100;

	std::vector<CBlob*> blobs;

	// Initializing the array for check if a pixel was already evaluated
	bool *is_eval = new bool[input.width*input.height];
	for(int k = 0; k < input.width*input.height; ++k)
		is_eval[k] = false;

	// Looping for all the pixels
	for(int i = 0; i < input.height; ++i){
		for(int j = 0; j < input.width; ++j){
			if(input.buffer[j + i*input.width] > gc_th && is_eval[j + i*input.width] == false ){
				CBlob *blob = generate_blob(input,j, i, is_eval) ;
				blobs.push_back( blob );
			}		
		}
	}

	std::cout << "Generated " << blobs.size() << " blobs\n";

	// Saving the output to image
	output.Build(input.width, input.height, 24);

	srand(time(NULL));
	int r, g, b;
	for(int k = 0; k < output.width*output.height*3; ++k)
		output.buffer[k] = 0;

	for(int i = 0; i < blobs.size(); ++i){	
		r = rand() % 256;
		g = rand() % 256;
		b = rand() % 256;
		std::vector<Vector2i> tmp = blobs[i]->get_points();
		for(int j = 0; j < tmp.size(); ++j){
			output.buffer[tmp[j].x*3 + tmp[j].y*input.width*3] = r;
			output.buffer[tmp[j].x*3 + 1 + tmp[j].y*input.width*3] = g;
			output.buffer[tmp[j].x*3 + 2 + tmp[j].y*input.width*3] = b;
			
		}
	}
	
	output.Save("labelling.pgm");
	
	// Freeing the memory
	delete is_eval;
	while(!blobs.empty()){
		delete blobs.back();
		blobs.pop_back();
	}

	return 0;
}