Added length test to the loop to avoid out of bounds error