finalized write and close functionality