add comments and refactor, but still stuck in encode