Refactored code (not finished)