Proper refactor, remove those ugly globals. Tests still pass.