Major performance improvements and small bugfixes

This pull request contains major performance improvements for message encoding/decoding plus various small bugfixes and cleanups.