Add encode() method, as well as other improvements