Many fixes and refactorings