Refactored code to remove dependence on global variables