import java.awt.*;
import java.awt.image.*;
import java.io.*;

// Gaussian Adaptive Non-Parametric Filter
public class AMNFG extends vectorFilter
{
	double wnorm[];
	int indent;

	// Create object and initialize data
	public AMNFG(int size)
	{
		masksize = size;
		maskIndex = new int[masksize*masksize];
		array = new double[masksize*masksize];
		wnorm = new double[masksize*masksize];
		indent = (int) Math.floor(masksize/2);
	}

	// Applies the weighting factor to the data array
	public void weight(int mask, double h[])
	{
		double w[] = new double[mask];
		double wtotal = 0;
		
		for(int i=0;i<mask;i++)
		{
			// w[i] is the weight for each vector
			w[i] = (1/Math.pow(h[i],3))*(Math.exp(-(array[i])));
			wtotal += w[i];
		}

		for(int i=0;i<mask;i++)
		{
			// Normalize the weights
			if (wtotal ==0)
				wnorm[i] = 0;
			else
				wnorm[i] = w[i]/wtotal;
		}
	}

	// Runs the algorithm
	public void performEffect()
	{
		double sumr,sumg,sumb;
		int counter, sumR, sumG, sumB;	
		int newPixels[] = new int [width*height];
		double temp_array[] = new double [masksize*masksize];

		// Moves through the input array pixel by pixel
		for (int y=indent;y<height-indent;y++)
		{
			for (int x=indent;x<width-indent;x++)
			{
				// Location of centre of mask
				int pointOffset = y*width+x;

				// Calculate Index for mask
				counter = 0;
				for (int i=-indent;i<=indent;i++)
				{
					for (int j=-indent;j<=indent;j++)
					{
						maskIndex[counter] = (y+i)*width+(x+j);
						counter++;
					}
				}

				// Distance from pixel to all others in mask
				calc_dist();

				// Calculate average distance
				for (int i=0; i<masksize*masksize; i++)
				{
					temp_array[i] += array[i]/(masksize*masksize);
				}
				
				// Distance from pixel to centre of mask
				calc_centre();
				
				// Sets array to ratio of dis from centre to avg dis
				for (int i=0; i<masksize*masksize; i++)
				{
					if (temp_array[i] != 0)
					{
						array[i] = array[i]/temp_array[i];
					}
					else
					{
						array[i] = 0;
					}
				}

				sumr = 0;
				sumg = 0;
				sumb = 0;
				
				// Apply weighting factor
				weight((masksize*masksize), temp_array);

				// Calculate output based on weighting and input pixels
				for (int i=0;i<masksize*masksize;i++)
				{
					sumr += wnorm[i]*((pixels[maskIndex[i]] >> 16)&0xff);
					sumg += wnorm[i]*((pixels[maskIndex[i]] >> 8)&0xff);
					sumb += wnorm[i]*((pixels[maskIndex[i]])&0xff);
				}

				sumR = (int)Math.round(sumr);
				sumG = (int)Math.round(sumg);
				sumB = (int)Math.round(sumb);

				if (sumR > 255) sumR = 255;
				if (sumR < 0) sumR = 0;
				if (sumG > 255) sumG = 255;
				if (sumG < 0) sumG = 0;
				if (sumB > 255) sumB = 255;
				if (sumB < 0) sumB = 0;

				newPixels[pointOffset] = (255<<24) | sumR<<16 | sumG <<8 | sumB;
			}
		}
		this.pixels = newPixels;
	}
}
