Refactored code a bit for reuse.