Fix index out of range crashes