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