WIP

Got it working, but it's ugly as hell and probably needs additional test
coverage.