Refactored code to get rid of duplication and make it easier to reuse the code