Added length check to write()