function projectionMatrix = computeProjectionFromGrass(x, grassStruct)
% compute projection matrix from grassmann coordinates
%
% THIS IS NO USER FUNCTION

% The elk-library: convex geometry applied to crystallization modeling.
%   Copyright (C) 2013 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/>.

%% projection matrix in scaled-PCA space
% set tangent space in grassmann manifold (see documentation for details)
tanMatrix = grassStruct.baseNull * reshape(x, ...
            grassStruct.nDim - grassStruct.targetDim, ...
            grassStruct.targetDim);
[U S V] = svd(tanMatrix,'econ');
baseMatrix = grassStruct.baseRange * V * diag(cos(diag(S))) * V'...
           +  U * diag(sin(diag(S))) * V';

% we check orthonormality by comparing (baseMatrix'*baseMatrix) which should
%   result in a unity matrix by summing up all squarred matrix elements of
%   the difference:
if abs(norm(baseMatrix'*baseMatrix - eye(size(baseMatrix,2)),'fro')) > grassStruct.zerotol
    error('elk:decomposition:numericalError', ['The basis obtained from ' ...
        'the Grassmann manifold is not orthogonal. This should not happen.']);
    % This would be the code to obtain an orthonormal baseMatrix again:
    baseMatrix = orth(baseMatrix);  
end

% transform basis to real-data space
baseMatrix = grassStruct.mapToRealSpace * baseMatrix;
% after this coordinate transformation, the base Matrix is NOT orthonormal
%   anymore and the projection must be computed as:
projectionMatrix = baseMatrix*inv(baseMatrix'*baseMatrix)*baseMatrix';