Added length test, to avoid index out of bounds