Major rewrite: simpler and more flexible.