add sanity check and fix minor bug