Code cleanup, documentation, and fixed some inconsistent error states.