Macro fails to process folder, but not subfolder files

Hello,
I wrote a macro to process images acquired in IN Cell Analyzer (GE Healthcare) located within a main folder an its subfolders and generate colorized, merged images and stacks. So far it works quite well except it doesn’t process files within main folder. It’s likely a simple mistake but I didn’t figure it out myself :expressionless:
Also, the macro is huge and I failed to make it shorter .
Any advices on that subject are welcome as well.
Thank you in advance.
ps: here is a folder with example images Folder.rar (115.5 KB)

macro "IN Cell - image manipulator" {
dir = getDirectory("Choose a Directory ");  
setBatchMode(true);

//Gets number and color of channels and order of channels in stack.     
     Dialog.create("IN Cell - image manipulator");
     itens = newArray("2", "3", "4");
     Dialog.addRadioButtonGroup("Number of channels", itens, 1, 3, 2);
     Dialog.show();
     nchannels = parseInt(Dialog.getRadioButton());
     Dialog.create("IN Cell - image manipulator");
     Dialog.addMessage("Please reorder the channels if desired order is different from acquisition order." +"Example:\n"+"Acquisition order --> DAPI(1) - Cy3(2) - FITC(3)\n" +"New order --> Cy3(2) - FITC(3) - DAPI(1)");
     Dialog.addString("Sequence order (ex. 1,2,3):", "");
     Dialog.addMessage("ps.: Numerical order (1,2,3...) is the acquisition order\n"
     +"Make sure to include commas between the numbers");
     itens = newArray("Red", "Green", "Blue", "Cyan", "Magenta", "Yellow", "Grays");
     for (i = 0; i < nchannels; i++) {
     Dialog.addRadioButtonGroup("Color of channel "+i+1+"", itens, 1, 7, 1);
     }
     Dialog.show();
     colorArr = newArray(nchannels);
     for (i = 0; i < nchannels; i++) {
         colorArr[i] = Dialog.getRadioButton();
         }
     start = getTime(); 
     order=Dialog.getString();
  print("\\Clear");
  
//Get tif files in folder (?) and subfolders    
 listFiles(dir); 
  function listFiles(dir) {
     list = getFileList(dir);
     for (i=0; i<list.length; i++) 
        if (endsWith(list[i], "/"))
           listFiles(""+dir+list[i]);
        else 
    counter=0;   
  for (i=0; i<list.length; i++)        
    if ( endsWith(list[i], "tif"))
  counter++;
  tiflist = newArray(counter);
  counter = 0;
  for (i=0; i<list.length; i++)          
    if  (endsWith(list[i], "tif")) {
      tiflist[counter] = list[i];
      counter++;
    }
    
//Import image sequence according infos provided by user in dialog box    
       for (t = 0; t < tiflist.length; t=t+nchannels) {
    run("Image Sequence...", "open=["+dir+"] number="+nchannels+" starting="+t+1+"");
    if (nSlices/nchannels != parseInt(nSlices/nchannels)) {exit("Error: uneven number of stacks. Please check whether your number of images and channels are really "+counter+" and "+nchannels+", respectively")}
  filename=dir+tiflist[t];
  startindex=lastIndexOf(filename, "/");
  finalindex=lastIndexOf(filename, "w");
  basename=substring(filename, startindex+1, finalindex-1);
  finalname=basename+")";
  ResultsPath = dir + "Results" + File.separator;
  File.makeDirectory(ResultsPath);
  
//Generates and saves stack 
run("Make Substack...", "  slices=" + order);
sliceLabels=newArray(nSlices);
for (f = 0; f < nSlices; f++) {
	setSlice(f+1);
	sliceLabels[f]=getInfo("slice.label");
	}
//run("Channels Tool...");
run("Make Composite", "display=Color");
for (i = 0; i < lengthOf(colorArr); i++) {
  Stack.setChannel(i+1);
  run(colorArr[i]);
  }
run("RGB Color");
stackPath = ResultsPath + "Stack" + File.separator;
    File.makeDirectory(stackPath);
saveAs("Tiff", stackPath + finalname);

//Generates and saves merged channels image
close();
run("Duplicate...", "duplicate");
run("Make Composite");
run("RGB Color");
mergePath = ResultsPath + "Merge" + File.separator;
File.makeDirectory(mergePath);
saveAs("Tiff", mergePath + finalname);

//Generates and saves colorized channels
selectWindow("Substack ("+order+")");
close("\\Others");
run("Split Channels");
images=newArray(nImages);
Array.reverse(sliceLabels);
for (ni = 0; ni < lengthOf(images); ni++) {
rename(sliceLabels[ni]);
colorPath = ResultsPath + "Color" + File.separator;
File.makeDirectory(colorPath);
saveAs("Tiff", colorPath + getTitle() + ".tif");
close();
       }
  run("Close All");
  print("\\Update:[Image processed successfully: "+finalname+"]");
  }
  }
}
print("Finished macro. Please check the output directory for results");
print ("Macro execution time: " + (((getTime()-start)/1000)/60) + " minutes");
setBatchMode(false);```

Hi there is template for batch processing that does exactly what you need.
I always use this as kernel for my projects.

Macro Editor > Templates > Batch > Process Folder (IJ Macro)

/*
 * Macro template to process multiple images in a folder
 */

#@ File (label = "Input directory", style = "directory") input
#@ File (label = "Output directory", style = "directory") output
#@ String (label = "File suffix", value = ".tif") suffix

// See also Process_Folder.py for a version of this code
// in the Python scripting language.

processFolder(input);

// function to scan folders/subfolders/files to find files with correct suffix
function processFolder(input) {
	list = getFileList(input);
	list = Array.sort(list);
	for (i = 0; i < list.length; i++) {
		if(File.isDirectory(input + File.separator + list[i]))
			processFolder(input + File.separator + list[i]);
		if(endsWith(list[i], suffix))
			processFile(input, output, list[i]);
	}
}

function processFile(input, output, file) {
	// Do the processing here by adding your own code.
	// Leave the print statements until things work, then remove them.
	print("Processing: " + input + File.separator + file);
	print("Saving to: " + output);
}

Thanks @schmiedc.
Mine was based on a similar template (https://imagej.nih.gov/ij/macros/BatchProcessFolders.txt)
I’ll try the one you suggests.

Here the standard recursive example :

https://imagej.nih.gov/ij/macros/BatchProcessFolders.txt

For readability it would be nice if you wrap loop and conditions with a curly bracket to see the end of the loop.

And try to debug. It helps to identify the problems.

By the way I couldn’t open your example images archive to debug the macro.

And please consider this:

The braces can be omitted if there is only one statement in the loop. for (i=0; i<=90; i+=10) print(i);

See (page 13):

Thanks for the suggestions @Bio7.
Regarding debugging, this is the kind of error I got:

Example images are actually thumbnail (very small) versions of real images. Maybe that’s the problem ?

Thanks for the guide. I’ll take a deeper look at it !

I found a way for the macro to process the files in the main folder. I had to change this part:

filename=dir+tiflist[t];
  startindex=lastIndexOf(filename, "/");
  finalindex=lastIndexOf(filename, "w");
  basename=substring(filename, startindex+1, finalindex-1);

To this:

  filename=File.getName(dir+tiflist[t]);
  finalindex=lastIndexOf(filename, "w");
  basename=substring(filename, 0, finalindex-1);

Problem was that filenames of images in folder started after a “\” and not after “/” as for images in subfolders. Maybe there’s a more elegant way to solve the issue, but the above seems to do the trick.
I’ll try to shorten the macro now.
Thank @Bio7 and @schmiedc for the help so far.