Almost finalized the encode function.