Rebased from #1293

Had to open a new pull request for #1293 since it didn't let me rebase it neither with the suggested command nor by git checkout, sorry.