Refactor writeback code. cc #5527

As part of #5527 I had to make some changes here and I just couldn't take it anymore. Refactor the writeback code. Should be functionally equivalent to the old stuff.

r? @pcwalton