Fix some mistakes and optimize some code