Handle errors from write()

Fixes #964
Some style fixes
Use do_write function in place of self-written replacement
Merge pull request #967 from ZyX-I/handle-write-errors

Handle errors from write()