Fix a few bugs and add some tests