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

// Adaptive Nearest Neighbor Filter (Goude Distance)
public class CBANNF extends vectorFilter
{
	double wnorm[];
	int indent;

	// Create object and initialize data
	public CBANNF(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 fuzzy weighting factor to the data array
	public void fuzzy_weight(int mask)
	{
		double w[] = new double[mask];
		double wtotal = 0;
		double max, min;
		
		max = array[0];
		min = array[0];
		
		// Finds max and min value in array
		for (int i=1; i<mask; i++)
		{
			if (array[i] > max)
			{
				max = array[i];
			}
			if (array[i] < min)
			{
				min = array[i];
			}
		}

		for(int i=0;i<mask;i++)
		{
			// w[i] is the fuzzy weight for each vector
			if (max == min)
			{
				w[i] = 1/(masksize*masksize);
			}
			else
			{
				w[i] = (array[i] - min)/(max-min);
			}
			wtotal += w[i];
		}

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

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

		// 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++;
					}
				}

				// S angle from pixel to all others in mask
				calc_goude();

				sumr = 0;
				sumg = 0;
				sumb = 0;
				
				// Apply fuzzy weighting factor
				fuzzy_weight(masksize*masksize);

				// 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 = Math.round(sumr);
				sumG = Math.round(sumg);
				sumB = 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;
	}
}
