Tried to fix edge cases. It's not much better...