Refactor serialization stuff

Fix #121