DRY'd and refactored a bit.