Port dm writer code

Still needs unit tests.