Bug-squashing!

It should be working now. Just needs final review, more testing and code cleanup.