Some refactoring, and a few fixes.