move encoding logic into one for-loop

Now we can finally pull this loop out into its own method.