Bug fixes and implementation cleanup from ed60e4d4.