added a more robust read & write routine