Refactored Working Solution