Cleanup of write function