Refactored to remove global variables.