Checking in latest code, but it still has problems with various edge cases.