Rewritten from scratch, much cleaner implementation. Not yet working.