Major rewrite. Not yet working.