Works with Python 3
It is a bit kludgy in parts, explicitly checking for string type
(as opposed to array of bytes), but it works.