Various improvements and refactorings