Constraint fixes

Fixed a couple of bugs in the constraint code, added tests and documentation.
Thanks @damirv for unearthing the bugs and helping with the fix!