Fix bugs caught by UT