refactoring this logic so that it can be reused