Refactored some duplicate code into a single method.