Final patches for any encoding

I have tested only on UTF-8 encoding
These fixes are final.