
#include <stdlib.h> 
#include <stdio.h> 
#include "vision_utilities.h"

int myround(double x);

int p1(char *fname_input, char *fname_output)
{
	Image *im_input = new Image;//input image
	Image *im_output = new Image;//output image
	readImage(im_input, fname_input);
	int NRows = getNRows(im_input);//# of rows
	int NCols = getNCols(im_input);//# of cols
	setSize(im_output,NRows,NCols);
	setColors(im_output,255);

	/*USING SOBEL (3*3)*/
	const int SOBEL_X[9] = {-1,0,1,
				-2,0,2,
				-1,0,1};
	const int SOBEL_Y[9] = {1,2,1,
				0,0,0,
				-1,-2,-1};

	/*EDGE MAGNITUDE*/
	int **edgeMagnitude = new int*[NRows];
	for (int i = 0; i < NRows; i++)
		edgeMagnitude[i] = new int[NCols];
	for (int i = 0; i < NRows; i++)
		for (int j = 0; j < NCols; j++)
			edgeMagnitude[i][j] = 0;

	int maxEdge = 0;
	/*COMPUTE EDGE MAGNITUDE*/
	for (int i = 1; i<NRows-1; i++)
	{
		for (int j = 1; j<NCols-1; j++)
		{
			int edgeX = getPixel(im_input,i-1,j-1)*SOBEL_X[0]
				+ getPixel(im_input,i-1,j)*SOBEL_X[1]
				+ getPixel(im_input,i-1,j+1)*SOBEL_X[2]

				+ getPixel(im_input,i,j-1)*SOBEL_X[3]
				+ getPixel(im_input,i,j)*SOBEL_X[4]
				+ getPixel(im_input,i,j+1)*SOBEL_X[5]

				+ getPixel(im_input,i+1,j-1)*SOBEL_X[6]
				+ getPixel(im_input,i+1,j)*SOBEL_X[7]
				+ getPixel(im_input,i+1,j+1)*SOBEL_X[8];

			int edgeY = getPixel(im_input,i-1,j-1)*SOBEL_Y[0]
				+ getPixel(im_input,i-1,j)*SOBEL_Y[1]
				+ getPixel(im_input,i-1,j+1)*SOBEL_Y[2]

				+ getPixel(im_input,i,j-1)*SOBEL_Y[3]
				+ getPixel(im_input,i,j)*SOBEL_Y[4]
				+ getPixel(im_input,i,j+1)*SOBEL_Y[5]

				+ getPixel(im_input,i+1,j-1)*SOBEL_Y[6]
				+ getPixel(im_input,i+1,j)*SOBEL_Y[7]
				+ getPixel(im_input,i+1,j+1)*SOBEL_Y[8];

			edgeMagnitude[i][j] = myround(sqrt(double(edgeX*edgeX+edgeY*edgeY)));	
			if (edgeMagnitude[i][j] > maxEdge) maxEdge = edgeMagnitude[i][j];			
		}
	}

	/*NORMALIZE EDGE MAGNITUDE TO (0, 255)*/
	for (int i = 1; i<NRows-1; i++)
	{
		for (int j = 1; j<NCols-1; j++)
		{
			setPixel(im_output,i,j,myround(double(edgeMagnitude[i][j])/maxEdge*255));
		}
	}

	writeImage(im_output, fname_output);
	printf("U got it\n");
	return 0;
}

int myround(double x)
{
	if (x<floor(x)+0.50) return floor(x);
	else return (floor(x)+1);
}

int main(int argc, char **argv) 
{ 
	if (argc <= 2){ 
		printf("Usage: %s <input image> <output edge image>\n", argv[0]); 
		return 0; 
	} 
	char *inputFilename = argv[1];  
	char *outputFilename = argv[2]; 
	p1(inputFilename,outputFilename); 
	return 0; 
}
