Refactored and commented. Removed redundant loop.