Refactored and cleaned up some duplicated code.