more conditionals and loop refactor