Fix index out of range bug