Refactoring work, mostly to keep private things private (but the public API is still wrong).