corrected for loop index out of range