Refactored the code a bit and removed duplication.