fix some bugs and improve tests