fixed bugs in write function