move everything into functions and cleaned up variable names for clarity, will need to be tested