You don't have to jump through all those hoops if you use the State Table Approach.
Here's one implementation of that approach: https://github.com/gfvalvo/NewEncoder