Major rewrite and simplifications.