implement decode and fix really dumb bug in encode