importClass(Packages.plugins.adufour.roi.ROIBasicDescriptor)
importClass(Packages.icy.roi.ROIUtil)
importClass(Packages.icy.roi.ROIDescriptor)
importClass(Packages.icy.gui.dialog.MessageDialog)
importClass(Packages.icy.sequence.Sequence)
importClass(Packages.java.util.ArrayList)
importClass(Packages.plugins.fab.spotDetector.detector.UDWTWavelet)
importClass(Packages.icy.roi.ROI2DRectangle)
importClass(java.awt.geom.Point2D)

// this is the parameters you asked for: considering the center of mass,
// the algo will look in a box of side boxSize*2+1 where the center of mass is the center of this box
//
// for boxSize = 2
//
// *****
// *****
// **X**
// *****
// *****
//
// with * : pixel considered for Rectangle ROI
// X: location of center of mass

boxSize = 2;
removePreviousRois = false;

// get the current sequence focused by the user
sequence = getSequence()

// check if the sequence exists
if ( sequence == null )
{
        MessageDialog.showDialog("Please open an image first", MessageDialog.INFORMATION_MESSAGE);
        throw "no sequence"; // stops the script and say why
}

w = sequence.getSizeX()
h = sequence.getSizeY()

// get all rois
rois = sequence.getROIs()
// get the number of rois
roiCount = rois.size();
println("Number of rois: " + roiCount)

// remove all existing ROI if requested
if (removePreviousRois)
    sequence.removeAllROI()

// cycle over all rois
for (i = 0; i < roiCount; i++)
{
    roi = rois.get(i) // get the spot

    x = ROIUtil.computeDescriptor("MassCenterX", roi, sequence)
    y = ROIUtil.computeDescriptor("MassCenterY", roi, sequence)
    
    surface = ROIUtil.computeDescriptor("Interior", roi, sequence)
    meanIntensity = ROIUtil.computeDescriptor("MeanIntensity", roi.getSubROI(-1, -1, 0), sequence)
    
    keepSpot = true

    // filtering
//    if (surface < 10) keepSpot = false // remove too small spots
//    if (surface > 60) keepSpot = false // remove too big spots
//    if (meanIntensity < 100) keepSpot = false // remove too big spots

    // remove spot if mass center too close from borders
    if (x - (boxSize+1) < 0) keepSpot = false
    if (y - (boxSize+1) < 0) keepSpot = false
    if (x + (boxSize+1) > w) keepSpot = false
    if (y + (boxSize+1) > h) keepSpot = false

    if (!keepSpot) continue

    // create the Rectangle ROI
    newRoi = new ROI2DRectangle(new Point2D.Double(x - boxSize, y - boxSize),
        new Point2D.Double(x + boxSize + 1, y + boxSize + 1),
        false)
    // preserve some settings from original ROI
    newRoi.setName(roi.getName() + " - fixed")
    newRoi.setColor(roi.getColor())

    // add the ROI to the sequence
    sequence.addROI(newRoi)
}
