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

// Generalized Vector Directional Filter
public class GVDF extends vectorFilter
{
	int indent;

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

	// Runs the algorithm
	public void performEffect()
	{
		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++;
					}
				}

				// Sorts pixels in mask by sum of angles
				calc_angle();
				b_sort();
				
				sumR=0;
				sumG=0;
				sumB=0;
				
				// Calculates average pixel value for group of similar vectors
				// in mask and outputs value
				for (int i=0; i<(Math.round((masksize*masksize)/2)+1); i++)
				{
					sumR += ((pixels[maskIndex[i]])>>16)&0xff;
					sumG += ((pixels[maskIndex[i]])>>8)&0xff;
					sumB += (pixels[maskIndex[i]])&0xff;					
				}

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

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