A lot more work added, as yet untested...

Untested, but hopefully quite close to what its final form needs to be.