Refactored the code to make it DRYer and more readable