CopyOnWrite implementation.

This is useful to implement transactions.
Fixes for supporting nested transactions.