Various improvments and refactoring