Fix a memory leak, a missing break, and some index out of bounds errors.