Added conditions to avoid NoneType iteration problems.