Implemented encode.

Not yet tested.