Fixed various edge cases and added tests for them.