Got a working version.
Hacking in some refinements.