refactoring lots of duplicated code