Fix serialisation code and tests