some backports from @cvalenti and also some fixes