Adding the bulk of the logic, extracted from a repo that is currently
private.