Code cleanup and fixes

These changes are a drop in replacement and shouldn't break any existing features