Fix array index out of bounds error