fix some bugs and some optimizations