Rewrite completely from scratch.

With test units this time.