backport #960, #961 and #970