Refactored code and made it more sensible