Final fixes, now just needs tests.