Several fixes and refactoring