StereoBM disparity block edge smoothing inner workings

In the StereoBM::compute -code the edges of the search block used to compute the sum of absolute differences are smoothed using these 5 lines of code:

sad[-1] = sad[1];
sad[ndisp] = sad[ndisp-2];
int p = sad[mind+1], n = sad[mind-1];
d = p + n - 2*sad[mind] + std::abs(p - n);
dptr[y*dstep] = dispDescale<mType>(ndisp - mind - 1 + mindisp, p-n, d);

How exactly does this p-n-d trick work? The only discussion relating to it I was able to find is here, but the trick isn’t really explained there either.

Also, wouldn’t ndisp - mind - 1 + mindisp cause the disparity data to be inverted? Where is this taken care of later in the code?
I did ask this question earlier yesterday in the opencv subreddit, but to no avail.