Refactored main loop in run() into internal subroutines.