Some refactoring, error handling, serialization