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