Improved checking, fixed edge cases.