Fix some bugs and add some tests