How to run a script on subfolders to make image stacks

I have a folder called “input” which has subfolders named 0 to 23. Each folder named 0 to 23 has a folder named mask. In the folder mask there are a number of images say 60 which I like to have as a stack.

I tried to use the code below in a script window (not the process->batch->macro). However, when I run the code nothing is saved.

input_to_files = "path_to_folders";
output = "path_to_output";

list = getFileList(input_to_files);

for (i = 0; i < 1; i++){
		//folder0 is the list of subfolders which all reside in a folder names input
		folder0 = list[i];
		//mask_folder is the path a folder names 'mask' in each subfolder of 'input' folder
        mask_folder = getFileList(input_to_files + folder0);
        //imgages are the list of images in the 'mask' folder
        images = getFileList(input_to_files + folder0 + mask_folder[0]);
		//img_name is the name of the first image to be used in "image sequence" below
		img_name = input_to_files + folder0 + mask_folder[0]+images[0];

		//This part should open the images and stack them
		run("Image Sequence...", "open=["+img_name+"]" +"starting=1 increment=1 scale=100 file=[] or=[] sort"); 
		saveAs("Tiff", output+j); 
		run("Close All");
}

@Reza

Ok. So… I’m not sure I’m getting this 100%…

Something like this (note - I have not tested this … so you’ll have to modify it a bit to get things working):

#@ File (label = "Input directory", style = "directory") input

	list = getFileList(input);
	

	for (i = 0; i < list.length; i++) {
		if(File.isDirectory(input + File.separator + list[i])) {
			// step into the directory and check for mask folder
			subList = getFileList(input + File.separator + list[i]);
			for (j = 0; j < subList.length; j++) {
				if (File.getName(subList[j]) == "mask") { // if 'mask' directory name... do the stacks...
					maskList = getFileList(input + File.separator + list[i] + File.separator + subList[j]);
					for (k = 0; k < maskList.length; k++) {
						run("Bio-Formats", "open=[" + input + File.separator + list[i] + File.separator + subList[j] + File.separator + maskList[k] + "] autoscale color_mode=Default rois_import=[ROI manager] view=Hyperstack stack_order=XYCZT");
					}
					run("Images to Stack", "name=Stack title=[] use keep");
					saveAs("Tiff", input + File.separator + list[i] + File.separator + subList[j] + "/Stack.tif");
					run("Close All");
				}
			}
		}
	}