Fix some bugs and improve unit tests