Various fixes and refactoring