D2 port

Sorry, I accidentally ran an indenter over it. I guess you could adapt what you need from the changeset and just take the required fixes instead of merging this pull.