rebased version of #1172