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

// Arithmatic Mean Filter
public class AMF extends vectorFilter
{
	int indent;

	// Creates object and initializes data
	public AMF(int size)
	{
		masksize = size;
		maskIndex = new int[masksize*masksize];
		indent = (int) Math.floor(masksize/2);
	}

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

		// Moves through 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++;
					}
				}
				
				sumR = 0;
				sumG = 0;
				sumB = 0;
				
				// Calculates the mean pixel within the mask
				for (int i=0; i<masksize*masksize; i++)
				{
					sumR += ((pixels[maskIndex[i]])>>16)&0xff;
					sumG += ((pixels[maskIndex[i]])>>8)&0xff;
					sumB += (pixels[maskIndex[i]])&0xff;
				}

				sumR = Math.round(sumR/(masksize*masksize));
				sumG = Math.round(sumG/(masksize*masksize));
				sumB = Math.round(sumB/(masksize*masksize));

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