Fix a couple bugs + optimize.