Some more refactoring, documentation, doctests, diagnostics.