refactored some code, factored out shared functionality