Done! Or at least, it works for all of my test cases.
Tomorrow morning: Clean it up and comment shit!