function mExceptionCauseFlat = util_get_error_causes(mException, getIntermediateCauses)

%   Copyright 2009-2010 The MathWorks, Inc.
    if nargin < 2
        getIntermediateCauses = false;
    end

    mExceptionCauseFlat = {};    
    assert(isa(mException,'MException'),'Input must be MException');    
    mExceptionCauseFlat = checkCauses(mException,mExceptionCauseFlat,true,getIntermediateCauses);    
end

function mExceptionCauseFlat = checkCauses(mException,mExceptionCauseFlat,isRoot, getIntermediateCauses)
    if nargin<3
        isRoot = false;
    end
    if ~isempty(mException.cause) 
        if ~isRoot && getIntermediateCauses
            mExceptionCauseFlat{end+1} = mException;
        end
        for i=1:length(mException.cause)
            mExceptionCauseFlat = checkCauses(mException.cause{i},mExceptionCauseFlat,false, getIntermediateCauses);                
        end 
    elseif ~isRoot
        mExceptionCauseFlat{end+1} = mException;
    end    
end

% LocalWords:  MException
