Cleaned up serialization internals and fixed some smaller bugs for #341
Merged last two commits