Fixes #248. Should fix most edge cases too.