This isn't finished, and has lots of debugging code still in, but it's working better...