Various fixes and code refactoring.