removed duplicate lines of code, refactored common logic into separate functions