Adding the beginnings of sync functionality, but it's very difficult to write this code nicely.