replaced duplicate code with function