Complete rewrite.

Previous version was poorly written and didn't work. So, I gave it
another go.