When a GN4 script does not work as you expect, or you are developing a new functionality step-by-step, the best method to sort it out is to run a debugging session and to check, step-by-step, what's the reason of malfunctioning, if any, and which are values of variables on each step.