Probably working (but inefficient) version of decode, encode is next