Save Stacks as Image Sequence in Batch mode

Hello,
I have a list of stacks stack01, stack02 etc. from serial secitons and I’d like to Batch save them as image sequences maintaining the original order in the final sequence (stack01001, stack01002, stack02001 etc…). This is easily done with save as Image sequence as it ask for the number of digits in the counter, but I could not figure out how to use it in batch mode.

I thus tryed to use a Macro based on the “Make substack” function but I could not find a way of using a counter with a fixed number of digits.

My clumsy attempt of using an if statement did’nt work. (see code below; curiously it works only at the end of the loop thus omitting the plane number 1).
Any help will be greately appreciated!

Federico

macro split_stack{ 
dir1 = getDirectory("Choose source directory"); 
list = getFileList(dir1); 
dir2 = getDirectory("Choose destination directory"); 

	setBatchMode(true); 
	for (i=0; i<list.length; i++) { 
 		open(dir1+list[i]); 
 		getDimensions(width, height, channels, slices, frames); 
 		counter=01; 
 		if (counter<10) {
 				counter = "0"+counter; 
 				}	 
 		title = File.nameWithoutExtension;
 			for (j=1; j< slices; j++){ 
  				run("Make Substack...", "channels=1-"+channels+" slices="+j+"-"+ slices); 
  				saveAs("tif", dir2+title+counter+"_.tiff"); 
  				close(); 
  				counter+=1;
 			} 
 		close(); 
}

As padding numbers to a defined length is a common task, there’s a utility function for this (see the list of macro functions). The following should work for you:

IJ.pad(counter, 2);

Note that you’re mixing number and string variables here. The statement counter=01 is the same as counter=1, whereas counter="01" means something entirely different. See the documentation. This macro illustrates the difference:

a=01
print("a: " + a)
b=1
print("b: " + b)
c="01"
print("c: " + c)

Thank you very much Jan!
I’m still a bit confused on how to mix string and numbers (i.e in file names)
for instance the following code does what I need, but not in my original Macro.

for (i=0; i<11; i++) {
counter=i;
if (counter<10) {
counter = “0”+ counter;
}
print (counter);
counter+=1;
}

anyway, your suggestion work perfectly and it is much more clear and straightforward.
Many Thanks to you and to Kees Straatman from which I copied the original macro.

Here the final code (the number of pads must be manually adjusted):

macro batch_save_image_sequence{
dir1 = getDirectory(“Choose source directory”);
list = getFileList(dir1);
dir2 = getDirectory(“Choose destination directory”);

setBatchMode(true); 
for (i=0; i<list.length; i++) { 
	open(dir1+list[i]); 
	getDimensions(width, height, channels, slices, frames);  
	counter=1;
	title = File.nameWithoutExtension;
		for (j=1; j<=slices; j++){ 
			run("Make Substack...", "channels=1-"+channels+" slices="+j+"-"+ slices); 
			saveAs("tif", dir2+title+IJ.pad(counter, 3)+"_.tiff"); 
			close(); 
			counter+=1;
		} 
	close(); 

}