Various fixes

Sorry that it is just two big commits...

Changes released under the MIT license.