Refactored the "loop" function.