Re-implement the changes which were removed in #9aa97cd466cbb459a3028a9cf7103e38b7d54e19 + fix a few things which were forgotten in the original patch