Fix bugs, some optimization