Changing the output encoding based on comments and refactoring the
encoding function to provide more robust output.