#include <windows.h>
#include <math.h>
#include "common.h"

Image_data * SmoothGaussian(Image_data *piData, double sigma, int T)
{
	Image_data		*pproData, *ptempData;
	unsigned char	*curPtr, *origPtr;

	int		i, k, x, y, width, height, numpixels;
	double	*weight;
	int		windowSize, offset;
	double	s = -1.5 * sigma;
	double	PI = 3.141592654;

	windowSize = (int)(3.0 * sigma);
	if ((windowSize % 2) == 0)
		--windowSize;

	offset = (windowSize-1) /2;

	width = piData->n_cols;
	height = piData->n_rows;

// ----------- Memory allocation stuff --------------//
	
	weight = malloc(windowSize * sizeof(float));

	ptempData = malloc(sizeof(Image_data));
	ptempData->image_G_ptr = calloc(piData->n_rows * piData->n_cols, sizeof(unsigned char));
	//memcpy(ptempData->image_G_ptr, piData->image_G_ptr, piData->n_rows * piData->n_cols);

	pproData = malloc(sizeof(Image_data));
	pproData->image_G_ptr = calloc(piData->n_rows * piData->n_cols, sizeof(unsigned char));
	pproData->n_cols = piData->n_cols;
	pproData->n_rows = piData->n_rows;
	lstrcpy(pproData->filename, "Gaussian Smoothed Image");

	
// -------------------------------------------------//

	for (i = 0; i < windowSize; i++)
	{
		weight[i] = 1.0 / (sqrt(2.0 * PI) * sigma) * exp(-1.0 * s * s / (2.0 * sigma * sigma));
		s += 3.0 * sigma / (double) (windowSize-1);
	}

	for (x = offset; x < width - offset; x++)
		for (y = 0; y < height; y++)
			for (i = x - offset, k = 0; i <= x + offset; i++, k++)
				ptempData->image_G_ptr[y*width+x] += (int)( weight[k] * piData->image_G_ptr[y*width+i] );
	
			
	for (x = 0; x < width; x++)
		for (y = offset; y < height - offset; y++)
			for (i = y - offset, k = 0; i <= y + offset; i++, k++)
				pproData->image_G_ptr[y*width+x] += (int)( weight[k] * ptempData->image_G_ptr[i*width+x] );
	
	

	curPtr = pproData->image_G_ptr;
	origPtr = piData->image_G_ptr;
	numpixels = width * height;

	for (i = 0; i < numpixels; i++)
	{
		*curPtr = *curPtr + 70;
		if (abs(*curPtr - *origPtr) > T)
			*curPtr = *origPtr;
		++origPtr;
		++curPtr;
	}

	
	free(weight);
	free(ptempData->image_G_ptr);
	free(ptempData);

	return pproData;
}
