Fix tests and some bugs