Fixed several bugs reported by EndlessCheng