Refactor top-level chunk into functions