CP-6697-3

This is the same as #58 and #63 combined (which were reverted) with some bug fixing commits squashed into the relevant original commits.