Major rewrite and cleanup