Fix a weird bug and optimize code