function projectionData = appendProjectionData(projectionData, ...
    constraintMatrix, projectionMatrix, zerotol)
% append a projection for mapping
%
% Syntax: projectionData = appendProjectionData([], dim)
%  or     projectionData = appendProjectionData(projectionData, ...
%                            constraintMatrix)
%
% 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/>.

%% initialize
if isempty(projectionData)
    % constraintMatrix is dim in this case
    projectionData.A = zeros(0, constraintMatrix);
    projectionData.responsibleMatrix = zeros(0, 3);
    projectionData.projectionList = {};
    return
end

%% add projection
projectionData.projectionList{end+1} = projectionMatrix;
nProjection = length(projectionData.projectionList);

%% skip, if constraintMatrix is empty
if isempty(constraintMatrix)
    return
end

%% filter zero-rows from constraintMatrix
constraintMatrix = eliminateRows(constraintMatrix, ...
    constraintMatrix(1,:)*0, zerotol);

%% normalize constraints
constraintMatrix = bsxfun(@rdivide, constraintMatrix, ...
    sqrt(sum(constraintMatrix.^2, 2)));

%% add existing constraints (as is)
[constraintMatrix, thisIndexVector] = eliminateRows(...
    constraintMatrix, projectionData.A, zerotol);
projectionData.responsibleMatrix = [projectionData.responsibleMatrix; ...
    [thisIndexVector(:), thisIndexVector(:)*0+nProjection, ...
    thisIndexVector(:)*0+1]];

%% add existing negative constraints
[constraintMatrix, thisIndexVector] = eliminateRows(...
    constraintMatrix, -1*projectionData.A, zerotol);
projectionData.responsibleMatrix = [projectionData.responsibleMatrix; ...
    [thisIndexVector(:), thisIndexVector(:)*0+nProjection, ...
    thisIndexVector(:)*0-1]];

%% add remaining constraints
% add remaining constraints as is which means using -1
thisIndexVector = (1:size(constraintMatrix, 1)) + size(projectionData.A, 1);
projectionData.A = [projectionData.A; constraintMatrix];
projectionData.responsibleMatrix = [projectionData.responsibleMatrix; ...
    [thisIndexVector(:), thisIndexVector(:)*0+nProjection, ...
    thisIndexVector(:)*0+1]];