. refactor some complicated logic into helpers