Trying to refactor. The worst loop depth noticed: 5