//	sarah_particles.java

//		Plugin to go through Sarah's images & perform particle-analysis, including number of particles & particle sizes
//		All TIF files within the selected directory will be processed 
//		The TIFF images are of 2 types:-
//			Nuclei (ch00) & connexins (ch01)
//		The program makes allowance for this (e.g. different thresholds, etc.)
	

//	D. Ciantar.   Feb 2007


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

import ij.io.*;
import ij.text.*;
import ij.plugin.filter.*;
import ij.measure.*;

import javax.swing.*;
import java.io.*;

public class sarah_particles implements PlugIn 
{

	public void run(String arg) 
	{

		//	Select directory
		JFileChooser chooser = new JFileChooser();
    		int returnVal = chooser.showOpenDialog(null);
    		if(returnVal == JFileChooser.APPROVE_OPTION)
		 {		
			//	Get directory & file info
			File dir = chooser.getCurrentDirectory();
			String path = dir.getAbsolutePath();
			File [] LF = dir.listFiles();
	
			//	Set Measurement Options
			int thres = 78;
			int nThres = 78;
			int maxPart = 99;
			int minPart = 3;
			int nucMin = 50;
			int nucMax = 8000;
			GenericDialog gd = new GenericDialog("Enter Parameters", IJ.getInstance());
			gd.addNumericField("Threshold :   ", thres, 0);
			gd.addNumericField("Nucleus Threshold", nThres, 0);
			gd.addNumericField("Maximum particle size :  ", maxPart, 0);
			gd.addNumericField("Minimum particle size :  ", minPart, 0);
			gd.addNumericField("Maximum NUCLEUS size :  ", nucMax, 0);
			gd.addNumericField("Minimum NUCLEUS size :  ", nucMin, 0);
			gd.showDialog();
			if (gd.wasCanceled() )
			{
				return;
			}
			thres = (int)gd.getNextNumber();
			nThres = (int)gd.getNextNumber();
			maxPart = (int)gd.getNextNumber();
			minPart = (int)gd.getNextNumber();
			nucMax = (int)gd.getNextNumber();
			nucMin = (int)gd.getNextNumber();

			IJ.run("Set Measurements...", "area display decimal=3");

			//	Results file
			FileWriter fw;
			PrintWriter pw;
			try
			{
				fw = new FileWriter(path + File.separator +  "particles1.txt");
				pw = new PrintWriter(fw, true);
			}
			catch(IOException ioEX)
			{
				IJ.showMessage("FAILED to create output file " + path +  File.separator +  "particles1.txt.   ABORTING!");
				return;
			}
			pw.println("Filename  Number-of-partcles Total-Area");
			pw.println("  ");


			int useThres = nThres;
			int useMax = nucMax;
			int useMin = nucMin;
			//	loop through files
			for(int df = 0; df < LF.length; df++)
			{

				if(LF[df].isFile())
				{
					String fname = LF[df].getName();
					if(fname.substring(fname.length()-3, fname.length()).equals("tif"))
					{	//	TIF file, so process
					
				
						//	Check channel
						if(fname.substring(fname.length()-5, fname.length()-4).equals("1") )
						{	//	Channel 1 (i.e. connexin)
							useThres = thres;
							useMax = maxPart;
							useMin = minPart;
						}
						else
						{
							useThres = nThres;
							useMax = nucMax;
							useMin = nucMin;
						}
						//	Open file
						Opener op = new Opener();
						ImagePlus imp = op.openImage(path, fname);
						if(imp!=null)
						{
							imp.show();
							imp.draw();
							ImageProcessor impr = imp.getProcessor();
							impr.setThreshold(useThres, 255, ImageProcessor.BLACK_AND_WHITE_LUT);	//  !!! CHANGE???
							imp.repaintWindow();

							IJ.run("Threshold", "thresholded remaining black");

							//	Line below can be changed!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
							IJ.run("Analyze Particles...", "minimum=" + useMin +" maximum=" + useMax + " bins=5 show=Nothing display size clear");

							//  Save Results
							ResultsTable resTab = Analyzer.getResultsTable();
							StringBuffer resStr = new StringBuffer();
							resStr.append(fname);
							resStr.append("  " + resTab.getCounter());
				
							double sumParticleSizes = 0.0;
							for(int c = 0; c < resTab.getCounter(); c++)
								sumParticleSizes += resTab.getValue("Area", c);
							resStr.append(" " + sumParticleSizes);

							pw.println(resStr.toString());
														
							TextPanel tp = IJ.getTextPanel();
							String sf = new String(path);
							sf = sf.concat(File.separator + fname);
							sf = sf.concat(".txt");
							tp.saveAs(sf);

							//	Close image window
							imp.hide();
	
							//	Close all windows
							resTab.reset();			//	Clear so as not to manually save
							WindowManager.closeAllWindows();							
								
						}
							
					}
				}
			}

			try
			{
				pw.close();
				fw.close();
			}
			catch(IOException ioEX)
			{
				//	DO NOTHING!
			}
		}
	}

}



