Pre-1.0 rewrite. Much faster and a lot less code.