Fixes to serialization/unserialization

Partially tested.