Refactorings and various little fixes