Refactored the code so that it is more modular and readable