refactored code to make it easier to re-use