complete rewrite of read and write functions