Refactored code considerably