Refactored code so that it is a little more modular and readable