Removed duplicate code and put it in a function