Refactored the code a lot