Refactor main program loop