Improved encode to be tail-recursive