Reorganized main iteration to avoid code duplication.