Rewrote, with tests. Probably usable now.