Fixes issue 4226.
Huge megacommit because a lot of things needed to be modified to make this possible.