Refactored most of the code into functions