Refactored to improve style and performance.