Refactored to avoid globals