Sanitize code

Cleaned up the codebase and made some sane changes. No changes to API.