Refactor to remove (some) global variables