fix logic bugs and code improve