Refactored code significantly