import ij.*;
import ij.plugin.*;
import ij.gui.*;
import ij.process.*;

/** This plugin copies a region of interest from one image to another.
*/ 

public class Copy_ROI implements PlugIn {

    static String title = "Copy ROI";
    int[] wList;
    private String[] titles;
    ImagePlus i1;
    ImagePlus i2;

    public void run(String arg) {
        if (IJ.versionLessThan("1.27w"))
	 return;

        wList = WindowManager.getIDList();

        if (wList==null || wList.length<2) {
            IJ.showMessage(title, "There must be at least two windows open");
            return;
        }

        titles = new String[wList.length];

        for (int i=0; i<wList.length; i++) {
            ImagePlus imp = WindowManager.getImage(wList[i]);
            if (imp!=null)
                titles[i] = imp.getTitle();
            else
                titles[i] = "";
        }
        
        if (!showDialog())
            return;

	Roi roi = i1.getRoi();
	if( roi != null ) {

		i2.setRoi( roi );
	}

    }
    
    public boolean showDialog() {
        GenericDialog gd = new GenericDialog(title);
        gd.addChoice("From:", titles, titles[0]);
        gd.addChoice("To:", titles, titles[1]);
        gd.showDialog();
        if (gd.wasCanceled())
            return false;
        int i1Index = gd.getNextChoiceIndex();
        int i2Index = gd.getNextChoiceIndex();
  
        i1 = WindowManager.getImage(wList[i1Index]);
        i2 = WindowManager.getImage(wList[i2Index]);

        return true;
    }

}
