Refactor most of the logic into a function