added support for serializing an object; rearranged code