Refactored the code to make it a bit cleaner