Refactored to remove globals