Adding tests and some bugfixes