function [tensor tensorDim] = obtainTensorDec(dec, measureName, par, ...
    vecType, partIndex)
% extract the right tensor from decomposition
%
% THIS FUNCTION IS NO USER FUNCTION.

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2012 Alexander Reinhold
%
% This program is free software: you can redistribute it and/or modify it 
%   under the terms of the GNU General Public License as published by the 
%   Free Software Foundation, either version 3 of the License, or (at your 
%   option) any later version.
%
% This program is distributed in the hope that it will be useful, but 
%   WITHOUT ANY WARRANTY; without even the implied warranty of 
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU 
%   General Public License for more details.
%
% You should have received a copy of the GNU General Public License along 
%   with this program.  If not, see <http://www.gnu.org/licenses/>.

% shortcuts
thisMeasureStruct = dec.measureData.(measureName);
thisParitition = dec.simplexPartition{partIndex};
tensorDim = thisMeasureStruct.dim;

%% get parIndex
if thisMeasureStruct.isPar
    [~, parIndex] = eliminateRows(par, thisMeasureStruct.par, 0);
    
    if length(parIndex) < size(par, 1)
        error('elk:decomposition:wrongInput', ...
            'the provided parameter(s) were not found in the decomposition struct');
    end
else
    parIndex = 1;
end

switch lower(vecType)
    case 'hc'
        % handle parameter
        if thisMeasureStruct.isPar
            tensor = thisMeasureStruct.tensorHc{parIndex}{partIndex};
        else
            tensor = thisMeasureStruct.tensorHc{partIndex};
        end
    case 'se'
        % handle parameter
        if thisMeasureStruct.isPar
            tensor = thisMeasureStruct.tensorSe{parIndex};
        else
            tensor = thisMeasureStruct.tensorSe;
        end
        
        % handle dimension
        switch thisMeasureStruct.dim
            case 1
                tensor = tensor(thisParitition.seIndexVector);
            case 2
                tensor = tensor(thisParitition.seIndexVector, ...
                    thisParitition.seIndexVector);
            case 3
                tensor = tensor(thisParitition.seIndexVector, ...
                    thisParitition.seIndexVector, ...
                    thisParitition.seIndexVector);
        end
        
        % take care of nan
        tensor(isnan(tensor)) = 0;
        
    case 'fullse'
        error('elk:decomposition:wrongType', ...
            'the named vector type is unknow. This should not happen.');
    otherwise
        error('elk:decomposition:wrongType', ...
            'the named vector type is unknow. This should not happen.');
end