OP_WRITE optimization and simplification of WriteHandler

I'll clean up the commit history.

Fixes #4145