Many refactorings and fixes