I didn't read the script throroughly, but one thing that stood out as likely to be the source of bugs is that you're using the incorrect format for the var command. You should be using var %variable = value, the = is important to prevent errors in many situations.