Tests and some bug fixes