write.c: cleanups and bug fixes