Copied in relevant parts of the refence implementation