import ij.plugin.filter.PlugInFilter;
import ij.ImagePlus;
import ij.process.ImageProcessor;
import ij.measure.ResultsTable;
import ij.plugin.filter.Analyzer;
import ij.measure.Calibration;
import ij.IJ;
import ij.gui.*;

/* Bob Dougherty, OptiNav, Inc.  Given an ROI, find the length, defined as the maximum distance
between any two points (Feret's diameter), and the width, which is the largest dimension
orthogonal to the length axis, as measured by virtual calipers.  Note: the left and right
points defining the width do not have to be at the same "station", or distace from the base.
Some code inspired by Wayne Rasband's getFeretsDiameter() method in PolygonRoi.

Version 0 June 9, 2004.
Version 1 June 9, 2004.  Applied specific formulas for different types of ROI to match expected results.
Version 2 June 10, 2004  Fixed bugs that made the orthogonal distance orientation dependant
*/
/*	License:
	Copyright (c) 2004, 2005, OptiNav, Inc.
	All rights reserved.

	Redistribution and use in source and binary forms, with or without
	modification, are permitted provided that the following conditions
	are met:

		Redistributions of source code must retain the above copyright
	notice, this list of conditions and the following disclaimer.
		Redistributions in binary form must reproduce the above copyright
	notice, this list of conditions and the following disclaimer in the
	documentation and/or other materials provided with the distribution.
		Neither the name of OptiNav, Inc. nor the names of its contributors
	may be used to endorse or promote products derived from this software
	without specific prior written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
	"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
	LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
	A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
	CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
	PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
	LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
	SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class Measure_Roi implements PlugInFilter{
	ImagePlus imp;
	int w,h,nBorder;
	double wp,hp;
	byte[] m;
	double[] x,y;
	public int setup(String str, ImagePlus imagePlus){
		imp = imagePlus;
		return DOES_ALL;
	}
	public void run(ImageProcessor imageProcessor){
		if (IJ.versionLessThan("1.32c")){
			IJ.error("Measure Roi requires ImageJ 1.32c or later.");
			return;
		}
 		Calibration cal = imp.getCalibration();
		wp = cal.pixelWidth;
		hp = cal.pixelHeight;
		Analyzer aSys = new Analyzer(); //System Analyzer
		ResultsTable rt = Analyzer.getResultsTable();
		Roi r = imp.getRoi();
		double feret = 0;
		double ortho = 0;
		if(r == null)return;
		if((r instanceof Line)||(r instanceof TextRoi)){
			IJ.showMessage("Measure Roi cannot process that type or ROI");
			return;
		}
		if(r instanceof PolygonRoi){
			PolygonRoi pr = (PolygonRoi)r;
			nBorder = pr.getNCoordinates();
			int[] intCoords = pr.getXCoordinates();
			x = new double[nBorder];
			for (int kp = 0; kp < nBorder; kp++)
				x[kp] = wp*intCoords[kp];
			intCoords = pr.getYCoordinates();
			y = new double[nBorder];
			for (int kp = 0; kp < nBorder; kp++)
				y[kp] = hp*intCoords[kp];

			//find the length, or Feret's diameter
			double cos = 1;
			double sin = 0;
			for (int k1 = 0; k1 < nBorder; k1++){
				for (int k2 = k1; k2 < nBorder; k2++){
					double dx = x[k2] - x[k1];
					double dy = y[k2] - y[k1];
					double d = Math.sqrt(dx*dx + dy*dy);
					if(d > feret){
						feret = d;
						cos = dx/d;
						sin = dy/d;
					}
				}
			}

			//find the orthogonal distance
			double pMin = sin*x[0] - cos*y[0];
			double pMax = pMin;
			for (int k = 1; k < nBorder; k++){
				double p = sin*x[k] - cos*y[k];
				if (p < pMin) pMin = p;
				if (p > pMax) pMax = p;
			}
			ortho = pMax - pMin;
		} else if (r instanceof OvalRoi){
			java.awt.Rectangle rect = r.getBoundingRect();
			double wr = wp*rect.getWidth();
			double hr = hp*rect.getHeight();
			if(wr > hr){
				feret = wr;
				ortho = hr;
			}else{
				feret = hr;
				ortho = wr;
			}

		} else {
			//Roi must be a rectangle
			java.awt.Rectangle rect = r.getBoundingRect();
			double wr = wp*rect.getWidth();
			double hr = hp*rect.getHeight();
			feret = Math.sqrt(wr*wr + hr*hr);
			if (feret == 0){
				ortho = 0;
			}else{
				ortho = 2*wr*hr/feret;
			}
		}
		rt.incrementCounter();
		rt.addValue("Roi_Length",feret);
		rt.addValue("Roi_Width",ortho);
		aSys.displayResults();
		aSys.updateHeadings();
	}
}
