Fix various bugs around encodings

https://www.w3.org/Bugs/Public/show_bug.cgi?id=25211
https://www.w3.org/Bugs/Public/show_bug.cgi?id=25227
https://www.w3.org/Bugs/Public/show_bug.cgi?id=25228