Major rewrite, code significantly simplified