Use immutable data structures in a few appropriate places.

Some of these are to prevent inappropriate mutations of internal data structures of e.g. state machines when they are accessed.