Refactor into functions to break down nesting