Improved encoding handling, added tests