Fix bugs and optimize