Fixes #948, pull some variables into the function that uses them, suggested by @LukeLin