Various bug fixes, tests pass now.