refactor main logic