Major rewrite for testability.