Refactor and simplify main logic.