Near-total reimplementation for massive performance gain

(Hurrah for automated tests!)

Also fixed up some line-ending issues, which makes the diffs worse than
they really are.