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

/** Gradient XY from Float
  *
  * Gets the XY gradient from a floating point image
  *
  * This example adapted by pf from tutorial plugins named
  * ColorInverter & StackAverage found with the tutorial at
  * http://www.fh-hagenberg.at/mtd/depot/imaging/imagej
  * 
  */
public class GradXYfromFloat_ implements PlugInFilter {

	protected ImagePlus imp; // defines an instance variable, protected means what?
	

	public int setup(String arg, ImagePlus imp) {
		if (arg.equals("about"))
			{showAbout(); return DONE;}
		this.imp=imp;
                return DOES_32; // checks for stacked floats as input
	}

	public void run(ImageProcessor ip) {

		// ImageStack stack=imp.getStack(); // sets up the image stack for access
		// get width, height and the region of interest
		int w = ip.getWidth();     
		int h = ip.getHeight();    
		int dimension = ip.getWidth()*ip.getHeight();	
		float[] pixels01 = (float[]) ip.getPixels(); // gets the first slice pixel array
	
		double amplitude=0;
		double phase=0;
		int i, j, iplus, jplus, k;
		// IJ.showMessageWithCancel("testwindow","look out");

		// create a new image with the same size and copy the pixels of the original image

		ImagePlus fpimage = NewImage.createFloatImage("XYgradient stack",w,h,2,NewImage.FILL_BLACK);
		ImageStack fpstack = fpimage.getStack();
		float[] rpixels = (float[]) fpstack.getPixels(1);
		float[] ipixels = (float[]) fpstack.getPixels(2);
		for (i=0; i<w; i++) {
			if (i==w-1) {iplus=1;} else {iplus=i+1;}
			for (j=0; j<h; j++) {
				if (j==h-1) {jplus=1;} else {jplus=j+1;}
				k = i + w*j;
				rpixels[k] = (float) (pixels01[iplus+w*j]-pixels01[k]);
				ipixels[k] = (float) (pixels01[i+w*jplus]-pixels01[k]);
			}
		}

		// fpimage.resetMinAndMax();
		fpimage.show();
		fpimage.updateAndDraw();



	}

	void showAbout() {
		// called by setup if the string argument is "about"
		IJ.showMessage("Amplitude-Phase from Real-Imaginary",
			"creates an amplitude-phase stack from a real-imaginary stack");
	}

}