Automating ImageJ Stack Splitter Error


I am trying to make a simple macro that loops through all open 5D image stacks (XYCZT), splits the color channels (this part is working), selects the channel 1 image, reduces it to a stack, runs stack splitter on the channel 1 image stack, selects channel 2 image, reduces it to a stack, then runs stack splitter again on the channel 2 image stack.

I’m getting 2 errors using the code below. The first is it appears that in this code the channel 1 image is never split. Its almost as if the run stack splitter line is commented out. When the select divisor window opens for stack splitter and I enter the number of stacks I want, only the second color channel stack is split.

The second error is a second stack splitter dialog window opens after I run the first window,that asks me to split the image resulting from the previous split. So when I split the channel 2 stack, I’m asked to split the resulting stack from that operation.

I’m very confused as to why I’m seeing these errors, I thought the task was simple enough and I don’t see why my code is working like this. If anyone could provide advice that would be most appreciated!

Here’s my code:

dir = getDirectory("Choose a Directory");
for (i=0;i<nImages;i++) {
        title = getTitle;
	   if(!(matches(title, ".*C.*"))){
	   c1title = "C1-"+title;
	   c2title = "C2-"+title;
	   run("Split Channels");
	   run("Hyperstack to Stack");
	   run("Stack Splitter");
	   run("Hyperstack to Stack");
	   run("Stack Splitter");


Thank you!

EDIT: I found out that the issue is I needed to run select window again after running hyperstack to stack. I don’t know why the hyperstack to stack command changes the selected window, but this is working for now.