Refactor to encapsulate discrete functionality, avoid recursion.