Updated to more efficient loop and renamed some variables for clarity