Some fixes and refactoring.