Fix a few bugs and improve tests