Thank you both for your great help! I think you meant %level rather than %node... it's a bit quirky. %node gets passed back to the function as %level, and then when it is modified becomes %node. I originally called it %level and %newlevel. I guess that way it made more sense.

Anyway it works properly now thanks to the combination of both of your tips. Cheers guys.