Unit tests, integration tests and some fixes to code based on tests