Backport #169 and #171 from develop

This is a rebase of #169 and #171 from develop, plus some other things that seem not up-to-date.