Refactored the inside loop.