Slightly cleverer encoding.
Refactored to avoid encoding/decoding where possible.
Aligned to latest API changes.