import ij.*;
import ij.plugin.filter.PlugInFilter;
import ij.process.*;
import ij.gui.*;
import java.awt.*;
import ij.plugin.filter.*;

public class Frames_Global_Average_ implements PlugInFilter {
	protected ImageStack stck;
	protected int dimension;
	
	public int setup(String arg, ImagePlus imp) {
		try {
			if (arg.equals("about")) {
				showAbout();
				return DONE;
			}
			stck=imp.getStack();
			dimension=stck.getWidth()*stck.getHeight();
			return DOES_RGB+DOES_8G+STACK_REQUIRED;
		}
		catch(Exception exc) {
				IJ.showMessage("Error!", "An error occurred...");
				return DONE;
		}
	}
	
	public void run(ImageProcessor ip) {
		ImagePlus imp=WindowManager.getCurrentImage();
		
		if(imp.getType()==imp.COLOR_RGB) {
			int[] rgb_pixs;
			int[] red=new int[dimension]; int[] green=new int[dimension]; int[] blue=new int[dimension];
			
			for(int i=1; i<=stck.getSize(); i++) {			
				rgb_pixs=(int[])stck.getPixels(i);
				for (int j=0; j<dimension; j++) {				
					red[j]+=(rgb_pixs[j]&0xff0000)>>16;
					green[j]+=(rgb_pixs[j]&0x00ff00)>>8;
					blue[j]+=(rgb_pixs[j]&0x0000ff);
				}
			}
			int[] rgb_rslt=rgb_average(red, green, blue);
			rgb_show(rgb_rslt, ip);
		}
		else if(imp.getType()==imp.GRAY8) {
			byte[] gray8_pixs;
			int[] gray8_rslt=new int[dimension];
			for(int i=1; i<=stck.getSize(); i++) {
				gray8_pixs=(byte[])stck.getPixels(i);
				for(int j=0; j<dimension; j++) {
					gray8_rslt[j]+=0xff&gray8_pixs[j];
				}
			}
			byte[] gray8_rslt=gray8_average(gray8_rslt);
			gray8_show(gray8_rslt, ip);
		}
	}
	
	protected int[] rgb_average(int[] r, int[] g, int[] b) {
		int[] avrg=new int[dimension];
		
		for(int i=0; i<dimension; i++) {					
			r[i]=(int)((r[i]/stck.getSize())&0xff);
			g[i]=(int)((g[i]/stck.getSize())&0xff);
			b[i]=(int)((b[i]/stck.getSize())&0xff);
			
			avrg[i]=(int)((r[i]&0xff)<<16)+((g[i]&0xff)<<8)+(b[i]&0xff);
		}
		return avrg;
	}
	
	protected byte[] gray8_average(int[] pixs) {
		byte[] avrg=new byte[dimension];
		for(int i=0; i<dimension; i++) {
			avrg[i]=(byte)((pixs[i]/stck.getSize())&0xff);
		}
		return avrg;
	}
	
	private void rgb_show(int[] pixs, ImageProcessor stck_ip) {
		ImagePlus result=NewImage.createRGBImage("Result of Frames Global Average", stck.getWidth(), stck.getHeight(), 1, NewImage.FILL_BLACK);
		ImageProcessor result_ip=result.getProcessor();
		result_ip.setPixels(pixs);
		result.show();
	}
	
	private void gray8_show(byte[] pixs, ImageProcessor stck_ip) {
		ImagePlus result=NewImage.createByteImage("Result of Frames Global Average", stck.getWidth(), stck.getHeight(), 1, NewImage.FILL_BLACK);
		ImageProcessor result_ip=result.getProcessor();
		result_ip.setPixels(pixs);
		result.show();
	}
	
	void showAbout() {
		IJ.showMessage("About_Frames_Global_Average_...",
		"This plugin filter reduces the noise by creating\n" +
		"an image formed by averaging all the frames.\n" +
		"Look at the 'Frames_Global_Average_.java' source file.");
	}
}
