Weird behaviour with function variables leaking out of if blocks