import ij.*;
import ij.io.*;
import ij.process.*;
import ij.gui.*;
import java.io.*;
import java.awt.*;
import java.awt.Component;
import ij.plugin.filter.*;
import java.util.Vector;
import java.util.Calendar;
import java.util.GregorianCalendar;


public class AvgNoiseRmvr_ implements PlugInFilter, DialogListener
{
	static String[] slices;
	static boolean doAlign;
	static byte doEnhance;
	static byte retVal;
	static double A;
	static int B;
	public boolean dialogItemChanged (GenericDialog gd, java.awt.AWTEvent e)

	{	
		
		Vector boo = gd.getCheckboxes();
		Vector sliders = gd.getSliders();
		Vector num = gd.getNumericFields();
		Checkbox check=(Checkbox)boo.get(0);
		if (check.getState()==true)
		{
			TextField n0=(TextField)num.get(0);
			n0.setEnabled(true);
			TextField n1=(TextField)num.get(1);
			n1.setEnabled(true);
			Scrollbar s0=(Scrollbar)sliders.get(0);
			s0.setEnabled(true);
			Scrollbar s1=(Scrollbar)sliders.get(1);
			s1.setEnabled(true);
		}
		else
		{
		
			TextField n0=(TextField)num.get(0);
			n0.setEnabled(false);
			TextField n1=(TextField)num.get(1);
			n1.setEnabled(false);
			Scrollbar s0=(Scrollbar)sliders.get(0);
			s0.setEnabled(false);
			Scrollbar s1=(Scrollbar)sliders.get(1);
			s1.setEnabled(false);
		}
		return true;
	}
	protected ImageStack stack;
	public int setup(String arg, ImagePlus imp)
		{
			try
			{
				if (imp.getStack()==null) throw (new RuntimeException());
				stack = imp.getStack();
			}
			catch (RuntimeException e)
			{
				IJ.error("this plugin requires a stack");
			}
			return DOES_RGB + STACK_REQUIRED;
		}
	public void run (ImageProcessor ip)
	{
		slices= stack.getSliceLabels();
		int[] pixels = new int[1];
		int dimension = stack.getWidth()*stack.getHeight();
		int [] red = new int [dimension];
		int [] green = new int [dimension];
		int [] blue = new int [dimension];
		NonBlockingGenericDialog dial1 = new NonBlockingGenericDialog("Opzioni");
		dial1.addCheckbox ("Align Images", true);
		dial1.addCheckbox ("Show Histogram", true);	
		dial1.showDialog();
		if (dial1.wasCanceled()) return;
		doAlign = dial1.getNextBoolean();
		if (doAlign)
		{
			try { if( IJ.runPlugIn ("StackReg_", "")==null){throw (new ClassNotFoundException());};}
			catch (ClassNotFoundException e)
			{
				IJ.error("Please download StackReg_ & TurboReg_  plugins from\n"+"http://bigwww.epfl.ch/thevenaz/turboreg/ if you want to align images. Processing terminated.");
				return;
			}
		}
		for (int i=1;i<=stack.getSize();i++)
		{
			pixels = (int[]) stack.getPixels(i);
			for (int j=0;j<dimension;j++)
			{
				red[j] += (int)(pixels[j] & 0xff0000)>>16;
				green[j] += (int)(pixels[j] & 0x00ff00)>>8;
				blue[j] += (int)(pixels[j] & 0x0000ff);
			}
		}

		int [] average = new int [dimension];
		for (int j=0;j<dimension;j++)
		{
			average [j] = (int) ((((red[j]/stack.getSize())&0xff)<<16)+(((green[j]/stack.getSize())&0xff)<<8)+(((blue[j]/stack.getSize())&0xff)));
		}
		ColorProcessor cp= new ColorProcessor ( stack.getWidth(), stack.getHeight(), average);
		ImagePlus foto=new ImagePlus ("output", cp);
		ImageWindow out= new ImageWindow(foto);
		if (dial1.getNextBoolean()==true) {HistogramWindow isto = new HistogramWindow(foto);}
		doEnhance = enhance(average, dimension);
		if (IJ.showMessageWithCancel ("Report","Generate Html report?")) creaReportFile();
	}	
	byte enhance(int[] average, int dimension)
	{
		NonBlockingGenericDialog dial2 = new NonBlockingGenericDialog("Options");
		dial2.addCheckbox ("Enhance Contrast", true);
		dial2.addCheckbox ("Brighten", true);				
		dial2.addSlider ("Window Radius", 5,127,70);
		dial2.addSlider ("Window Center", 0,255,127);
		dial2.addDialogListener(this);
		dial2.showDialog();
		if (dial2.wasCanceled()) return 0;
		retVal =0;
		int [] sigmoid = new int [dimension];
		int redP,greenP,blueP;
		if (dial2.getNextBoolean())
		{
			retVal+=1;
			A = dial2.getNextNumber()/3;
			B = (int)dial2.getNextNumber();
			for (int j=0;j<dimension;j++)
			{
				redP = (int)(255*(1/(1+Math.pow(Math.E, -(((average[j] & 0xff0000)>>16)-B)/A))));
				greenP = (int)(255*(1/(1+Math.pow(Math.E, -(((average[j] & 0x00ff00)>>8)-B)/A))));
				blueP = (int)(255*(1/(1+Math.pow(Math.E, -(((average[j] & 0x0000ff))-B)/A))));
				sigmoid[j]=((redP & 0xff)<<16)+((greenP & 0xff)<<8) + (blueP & 0xff);
			}
		}
		else sigmoid=average;
		int [] bright = new int [dimension];
		if (dial2.getNextBoolean())
		{
			retVal+=2;
			for (int j=0;j<dimension;j++)
			{
				if (((sigmoid[j] & 0xff0000)>>16)<206) {redP=((sigmoid[j] & 0xff0000)>>16)+50;} else {redP=255;}
				if (((sigmoid[j] & 0x00ff00)>>8)<206) {greenP=((sigmoid[j] & 0x00ff00)>>8)+50;} else {greenP=255;}
				if (((sigmoid[j] & 0x0000ff))<206) {blueP=((sigmoid[j] & 0x0000ff))+50;} else {blueP=255;}
				bright[j]=((redP & 0xff)<<16)+((greenP & 0xff)<<8) + (blueP & 0xff);
			}
			
		}
		else bright=sigmoid;
		ColorProcessor cp2= new ColorProcessor ( stack.getWidth(), stack.getHeight(), bright);
		ImagePlus foto2=new ImagePlus ("adjOutput", cp2);
		ImageWindow out2= new ImageWindow(foto2);
		HistogramWindow isto2 = new HistogramWindow(foto2);
		NonBlockingGenericDialog dial3 = new NonBlockingGenericDialog("Contrast Enhancement");
		dial3.addMessage("Try again?");
		dial3.showDialog();
		if (dial3.wasOKed()) retVal = enhance (average,dimension);
		return retVal;	
	}
	
	
	
	public void creaReportFile() 
	{
		SaveDialog s = new SaveDialog("Salva report","report",".html");
		String file = s.getDirectory(); 
		file += s.getFileName();
		try
		{
			GregorianCalendar gc = new GregorianCalendar();
			int year = gc.get(Calendar.YEAR);
			int month = gc.get(Calendar.MONTH) + 1;
			int day = gc.get(Calendar.DATE);
			int hour = gc.get(Calendar.HOUR_OF_DAY);
			int min = gc.get(Calendar.MINUTE);
			int sec = gc.get(Calendar.SECOND);
			String min0;
			String sec0;
			if (min<10) min0 ="0"; else min0="";
			if (sec<10) sec0 ="0"; else sec0="";
			
			FileWriter report = new FileWriter(file);
			report.append("<html>");
			report.append("<head>");
			report.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");
			report.append("</head>");
			report.append("<body>");
			report.append("<h1>Multiple Images Average Noise Remover and Contrast Enhancer</h1>");
			report.append("Report Generation Date: "+"<strong>" + day +"\\"+month+"\\"+year+" "+hour+":"+min0+min+":"+sec0+sec+"</strong><BR>");
			report.append("<hr><h2>Applied Values:</h2></hr>");
			report.append("<ul><li>Align: <strong>"+doAlign+"</strong></li></ul>" + 
				"<ul><li>Enhance Contrast: <strong>"+((doEnhance%2)!=0)+"</strong>");
			if ((doEnhance%2)!=0) {report.append(", Window Radius: <strong>"+(int)(A*3)+"</strong>, Window Center: <strong>"+B);}
			report.append("</strong></li></ul>");
			report.append("<ul><li>Brighten: <strong>"+(doEnhance>1)+"</strong> </li></ul><hr></hr>");
			
			
			report.append("<h2>Input files: </h2>");
			for (int i =0;i<slices.length;i++)
			{
				if (slices[i]!=null){report.append ("<li>File #"+(i+1)+": "+slices[i]+"</li>");}
			}
			
			report.append("<hr><h2>Options description:</h2>");
			report.append("<p>This plugin calculates the average value of each pixel of the images of the stack. It can also align the images of the stack and there are options to enhance contrast and brightness of the output."+
					"<ul><li><strong>Align:</strong> The images in the stack are aligned using the stackReg included plugin.</li></ul>" + 
					"<ul><li><strong>Histogram:</strong> Generate the histogram relative to the current output image.</li></ul>"+
					"<ul><li><strong>Enhance Contrast:</strong> Enhance the contrast of the average image using the sigmoid function</li></ul>"+
					"<ul><li><strong>Window Radius:</strong> Set the radius of the window of values that will be expanded</li></ul></p>"+
					"<ul><li><strong>Window Center:</strong> Set the center of the contrast enhancing window</li></ul>"+
					"<ul><li><strong>Brighten:</strong> Enabling this option will boost the value of each pixels by 55 (capped at 255)</li></ul></p>"+
					"<ul><li><strong>Report:</strong> Create this file.</li></ul></p>");
			report.append("<hr></hr><h2>References: </h2>"+
					"<ul><li><a href=\"http://www.cambridgeincolour.com/tutorials/image-averaging-noise.htm\">Noise reduction by image averaging.</a></li>"+
					"<li><a href=\"http://en.wikipedia.org/wiki/Sigmoid_function\">Sigmoid function</a></li>"+
					"<li><a href=\"http://www.computing.dcu.ie/~humphrys/Notes/Neural/sigmoid.html\">Continuous Output - The sigmoid function</a></li>"+
					"<li><a href=\"http://bigwww.epfl.ch/thevenaz/stackreg/\">StackReg An ImageJ plugin for the recursive alignment of a stack of images.</a></li></ul><hr></hr></body></html>");					
			report.close();
		}
		catch (IOException e) {IJ.error("Output file not found");}
	}
}