Some misc refactorings and fixes