Initial refactoring to using local variables rather than global variables