Fix for bugs #3141, #2686

This is a compilation of 9 commits from
https://github.com/cfengine/core/pull/1232