refactoring and cleaning up code removing duplication