function [y, isNeg] = sumlogprobmat2(x, dim, xIsNeg)
    % Sum a matrix of log probabilities in a specified dimension with
    % avoidance of underflow.
    %
    % This version allows for values on the nonlog scale to be negative. We
    % return isNeg, a matrix of binaries indicating which of the values
    % returned are negative on the nonlog scale.
    %
    % xIsNeg must be same size as x; this identifies (log inds) values of x
    % which are negative on the nonlog scale.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % CHANGELOG
    % 13.10.2014 - copied from old version.
    %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

    maxX = max(x, [], dim);
    maxX(maxX == -Inf) = 0;
    inter1 = exp(bsxfun(@minus, x, maxX));
    inter1(xIsNeg) = -inter1(xIsNeg);
    inter2 = sum(inter1, dim);
    isNeg = inter2 < 0;
    inter2(isNeg) = -inter2(isNeg);
    y = log(inter2) + maxX;
end