Refactoring, bug fixes and integration test