Refactored functions to run outside of while loop