Re-wrote part of the code into functions