function dec = computeMappingAndConstraint(dec, zerotol, allowFixPosition)
% generate mapping matrix and constraint matrix and ensure fixed position
%
% THIS 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/>.

%% info
% This part ensures that the mapping matrix (for crystals group mapping 
%   matrix) and the constraint matrix are generated and consistent. It also
%   corrects the input if the position is not fixed.
% Not fixing the position might work, but results in cones that can hardly 
%   be imagined. Especially, unfixed positions might imply that polytopes 
%   become empty sets for h~=0, which is strongly unhandy.


%% input handling
% check sizes, if matrices are present
if ~isempty(dec.mappingReducedToFull) && ...
    size(dec.mappingReducedToFull, 1) ~= dec.nH
        error('elk:decomposition:wrongInput', ...
             ['the provided mapping matrix must have the same number ' ...
              'of rows like the matrix of facet normals A']);
end
if ~isempty(dec.constraintMatrix) && (...        
        size(dec.constraintMatrix, 2) ~= dec.nH )
    error('elk:decomposition:wrongInput', ...
        ['the provided constraint matrix must be square and must' ...
        'have the size of the row number of the matrix of facet normals A']);
end
  
if isempty(dec.constraintMatrix) && isempty(dec.mappingReducedToFull)
    %% nothing provided
    if allowFixPosition == 0
        error('elk:decomposition:fixPosition', ['you need to provide a ' ...
            'mapping or constraint matrix, or set allowFixPosition to -1']);
    elseif allowFixPosition == 1
        warning('elk:decomposition:fixPosition', ['Mapping and constraint ' ...
            'matrices are generated to fix the position of represented ' ...
            'polytopes, use allowFixPosition option with (-1) to supress ' ...
            'this warning']);
    end
    % need to fix position
    dec.constraintMatrix = fixPosition(dec.A, zeros(0, size(dec.A, 1)), zerotol);
    % generate mapping
    [~, s, v] = svd(dec.constraintMatrix);
    s = diag(s);
    s(isZero(s, zerotol)) = 0;
    dec.mappingReducedToFull = trimColumns(v(:, s==0), zerotol);    
    
elseif isempty(dec.constraintMatrix)
    %% constraint not provided
    % generate constraint
    dec.constraintMatrix = eye(dec.nH) - dec.mappingReducedToFull * ...
        pinv(dec.mappingReducedToFull);
    % incorporate fixed position
    additionalConstraintMatrix = fixPosition(dec.A, dec.constraintMatrix, zerotol);
    if rank(additionalConstraintMatrix) ~= 0
        % error/warning handle if modification is allowed
        if allowFixPosition == 0
            error('elk:decomposition:fixPosition', ['polytopes in the given ' ...
                'representation are not fixed in their position. change ' ...
                'allowFixPosition to 1 to automatically modify the ' ...
                'mapping matrix.']);
        elseif allowFixPosition == 1
            warning('elk:decomposition:fixPosition', ['Mapping matrix ' ...
                'is modified to fix the position of represented ' ...
                'polytopes. use allowFixPosition option with (-1) to supress ' ...
                'this warning']);
        end
        % we need to generate a new mapping matrix (reduced dimension)
        dec.mappingReducedToFull = [];
        dec.constraintMatrix = [dec.constraintMatrix; additionalConstraintMatrix];
        dec = computeMappingAndConstraint(dec, zerotol, allowFixPosition);
        
%         % merge constraint - additionalConstraintMatrix has only a single
%         %   1 in each row to fix that facet distance to zero. We can 
%         %   directly apply this for the mapping matrix:
%         dec.mappingReducedToFull(sum(additionalConstraintMatrix, 1) >= 1, :) = 0;
%         % this gives a new constraint matrix:
%         dec.constraintMatrix = eye(dec.nH) - dec.mappingReducedToFull * ...
%             pinv(dec.mappingReducedToFull);
    end
    
else
    %% constraint is provided
    % incorporate fixed position
    additionalConstraintMatrix = fixPosition(dec.A, dec.constraintMatrix, zerotol);
    if rank(additionalConstraintMatrix) ~= 0
        % error/warning handle if modification is allowed
        if allowFixPosition == 0
            error('elk:decomposition:fixPosition', ['polytopes in the given ' ...
                'representation are not fixed in their position. change' ...
                'allowFixPosition to 1 to automatically modify the ' ...
                'constraint matrix.']);
        elseif allowFixPosition == 1
            warning('elk:decomposition:fixPosition', ['Constraint matrix ' ...
                'is modified to fix the position of represented ' ...
                'polytopes. use allowFixPosition option with (-1) to supress ' ...
                'this warning']);
        end
        % append new constraints
        dec.constraintMatrix = [dec.constraintMatrix; additionalConstraintMatrix];
    end
    % generate mapping matrix
    [~, s, v] = svd(dec.constraintMatrix);
    s = diag(s);
    s(isZero(s, zerotol)) = 0;
    dec.mappingReducedToFull = trimColumns(v(:, s==0), zerotol);    
    
end

%% check consistency of mapping and constraint
if ~all(isZero(dec.constraintMatrix * dec.mappingReducedToFull, zerotol))
    error('elk:decomposition:wrongInput', ...
         ['the provided constraint matrix is not consistent with the ' ...
          'provided mapping matrix: constraint*mapping should result ' ...
          'in a matrix with all elements close to zero. This should not ' ...
          'happen.']);
end

%% generate reverse mapping
dec.mappingFullToReduced = pinv(dec.mappingReducedToFull);

end