move some complicated logic out into helper functions.
refactor duplicate code into single helper.