Refactored and ready for code review