Moved a lot of code around to arrange all the public/private stuff more clearly.