#include <cstdio>
#include <cstdlib>
#include "image.h"
#include "misc.h"
#include "pnmfile.h"
#include "segment-image.h"

int main(int argc, char **argv) {
  if (argc != 3) {
    fprintf(stderr, "usage: %s  input(ppm) output(ppm)\n", argv[0]);
    return 1;
  }
  /*
  float sigma = atof(argv[1]);
  float k = atof(argv[2]);
  int min_size = atoi(argv[3]);*/
	
  printf("loading input image.\n");
  image<rgb> *in = loadPPM(argv[1]);
  int xsize = in->width();
  int ysize = in->height();
  image<float> *input = new image<float>(xsize, ysize);
  	  for(int x =0; x<xsize; x++){
		for(int y=0; y<ysize;y++){
			rgb p = imRef(in, x, y);
  			imRef(input,x,y) = (p.r+p.g+p.b)/3.0;
  		}
  		}
	
  printf("processing\n");

  int hy[3][3] = {{-1,-2,-1},{0,0,0},{1,2,1}};
  int hx[3][3] = {{-1,0,1},{-2,0,2},{-1,0,1}};

 
  image<float> *sbx = new image<float>(xsize, ysize);
  image<float> *sby = new image<float>(xsize, ysize);
  image<float> *sbout = new image<float>(xsize, ysize);

  for(int x = 1; x<xsize-1; x++){
	for(int y=1; y<ysize-1;y++){
		float sum = 0;
	for (int j = -1; j<=1; j++){
		for (int i = -1; i <= 1; i++) {
		sum += hx[j+1][i+1]*imRef(input,x+i,y+i);
		}
	}
	imRef(sbx, x, y ) = sum;
  }
  }
  
    for(int x = 1; x<xsize-1; x++){
	for(int y=1; y<ysize-1;y++){
		float sum = 0;
	for (int j = -1; j<=1; j++){
		for (int i = -1; i <= 1; i++) {
		sum += hy[j+1][i+1]*imRef(input,x+i,y+i);
		}
	}
	imRef(sby, x, y ) = sum;
  }
  }
  
 	for(int x = 1; x<xsize-1; x++){
		for(int y=1; y<ysize-1;y++){
			float gsum = sqrt(pow(imRef(sbx,x,y),2)+pow(imRef(sby,x,y),2));
			imRef(sbout,x,y) = gsum;
		}
	}


	for(int x =0; x<xsize; x++){
		for(int y=0; y<ysize;y++){
			float p = imRef(sbout, x, y);
			if (p>255) p = 255;
			rgb c;
			c.r = c.g = c.b = p;
  			imRef(in,x,y) = c;
  		}
  		}


 savePPM(in, argv[2]);







  /*int num_ccs; 
  image<rgb> *seg = segment_image(input, sigma, k, min_size, &num_ccs); 
  savePPM(seg, argv[5]);

  printf("got %d components\n", num_ccs);
  printf("done! uff...thats hard work.\n");
*/
  return 0;
}
