// Macro for counting luminophore pixels in ImageJ
// analysis for manuscript "Worms or storms? Distinguishing bioturbation from physical mixing using multiple tracers" Kooistra et al., 2026


// === Parameters ===
tolerance = 20;

// Input dialog for additional text in the filename
userInput = getString("Enter a value for the filename:", "001");

// Get original filename without extension
origTitle = getTitle();
dotIndex = lastIndexOf(origTitle, ".");
if (dotIndex >= 0) {
    baseName = substring(origTitle, 0, dotIndex);
} else {
    baseName = origTitle;
}

// Check ROI (Region of Interest)
getSelectionBounds(x0, y0, roiWidth, roiHeight);
if (roiWidth == 0 || roiHeight == 0) {
    exit("Please select a region of interest (ROI) first.");
}

// Create mask (binary image of ROI)
run("Create Mask");
maskTitle = getTitle();
selectWindow(maskTitle);

// Get mask dimensions
maskWidth = getWidth();
maskHeight = getHeight();

// Store mask pixels in an array
maskPixels = newArray(maskWidth * maskHeight);
for (y = 0; y < maskHeight; y++) {
    for (x = 0; x < maskWidth; x++) {
        maskPixels[y * maskWidth + x] = getPixel(x, y);
    }
}

// Close mask window
run("Close");

// Return to original color image
selectWindow(origTitle);

// Get image dimensions
width = getWidth();
height = getHeight();

countRedOrange = 0;

// Iterate through pixels
for (y = 0; y < height; y++) {
    for (x = 0; x < width; x++) {
        idx = y * maskWidth + x;
        if (maskPixels[idx] != 0) {
            rgb = getPixel(x, y);
            r = (rgb >> 16) & 0xff;
            g = (rgb >> 8) & 0xff;
            b = rgb & 0xff;

            if (r > 150 && g > 40 && g < r - 30 && b < 100) {
                countRedOrange++;
            }
        }
    }
}

// Display result
print("Pixels in red/orange range: " + countRedOrange);

// Build CSV filename with user input and base name
savePath = "[my WD]" + baseName + "_count_" + userInput + ".csv";

// CSV content
csv = "Region;RotOrangePixel\nROI 1;" + countRedOrange + "\n";

// Save CSV
File.saveString(csv, savePath);
print("CSV saved: " + savePath);