Fix some bugs. Add some tests