Bugfix, and make a ton of variables local.