massive variable scope refactor