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