Factor out common code

This avoids peppering the code with encode/decode calls.
Merge pull request #48 from myint/clean

Factor out common code (without Travis CI)