import ij.*; 
import ij.process.*; 
import ij.plugin.*; 
import ij.io.FileInfo; 

import java.lang.*; 
import java.awt.*;
import java.text.DecimalFormat; 
import java.awt.image.*; 


/** Transforms a FluoviewTiff_ stack into a stack of color images.  

@see ij.plugin.FluoviewTiff_

@author Patrick Kelly <phkelly@ucsd.edu>

*/


public class FVToColor_ implements PlugIn {
    private static String TITLE_TAG = "RGB_"; 

    // --------------------------------------------------
    public void run(String arg) {
	ImagePlus imp = WindowManager.getCurrentImage(); 

	if(imp==null) {
	    IJ.noImage(); 
	    return; 
	}

	// Make sure image is valid Fluoview.
	if(!FluoviewTiff_.isFluoviewImage(imp)) {
	    IJ.error("FVToColor_: Input is not a "+
		     "valid FluoviewTiff_ image."); 
	    return; 
	}

	if(!imp.lock())
	    return;   // exit if in use
	{
	    processStack((FluoviewTiff_)imp); 
	}
	imp.unlock(); 
    }

    public void convert(FluoviewTiff_ fimp) {
	if(!fimp.lock()) return;  // exit if in use
	processStack(fimp); 
	fimp.unlock(); 
    }

    // --------------------------------------------------
    protected void processStack(FluoviewTiff_ fimp) {
	if(fimp.getNumberComposites()==1)
	    stack2image(fimp); // special case, 1 image per substack
	else
	    stack2stack(fimp); 
    }

    // --------------------------------------------------
    /** This routine handles the case when the number of slices in the
	original stack equals the number of channels. In this case,
	there is only a single composite (RGB) image. */
    protected void stack2image(FluoviewTiff_ fimp) {
	// Get single composite image.
	Image img = fimp.compositeChannels(); 

	ImagePlus imp = new ImagePlus(TITLE_TAG+fimp.getTitle(),
				      img); 

	// Show new image.
	imp.show(); 
    }


    // --------------------------------------------------
    /** This routine handles case where there are multiple composite
	images. */

    protected void stack2stack(FluoviewTiff_ fimp) {
	ImageStack ims = new ImageStack(fimp.getWidth(),
					fimp.getHeight()); 

	DecimalFormat df = new DecimalFormat("0000");  // for slice label

	// Note, loop through only the first numImages elements 
	for(int s=1;s<=fimp.getNumberComposites();++s) {
	    IJ.showStatus("Color converting slice: "+s); 
	    Image imp = fimp.compositeChannels(s); 

	    ImagePlus nimp = new ImagePlus("",imp); 

	    String sliceLabel = "slice_"+df.format(s); 
	    ims.addSlice(sliceLabel,nimp.getProcessor()); 
	}

	ImagePlus implus = new ImagePlus(TITLE_TAG+fimp.getTitle(),ims);  
	implus.show(); 
    }

}  // end FVToColor_
