refactor code, placed repetitive code in function