An untested version. An attempt to fix some unexpected behaviour.