Reorganize/optimize serialization code, add tests