Fixed write function to do its work properly