Refactored the code to make it a bit generic