Fix a few bugs and improve its performance