Factor out common code

This avoids peppering the code with encode/decode calls.