Refactoring, various minor bug fixes.