Refactored and improved