various cleanups and small bugfixes

Various cleanups and small bugfixes. No changes or additions to the API or functionality.