function rot = getRotationMatrix(vector, zerotol)
% obtain rotation matrix based on a vector (or set of vectors)
%
% Syntax: rot = getRotationMatrix(normalVector)
%
% The rotation matrix is calculated such that the given vector points to
%   the x-axis after the rotation. If a matrix of vectors is provided (each
%   column one vector), the vectors point to the first, second, third and
%   so on coordinate axis. Therefore, the given vectors must be orthogonal
%   to each other.
%
% See also: getRotationMatrix2d, getRotationMatrix4d, rotatePolytope

% 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/>.

%% input handling
if ~exist('zerotol', 'var') || isempty(zerotol)
    zerotol = elkZerotol;
end

%% check orthogonality
nVec = size(vector, 1);
for iVecOne = 1:nVec
    for iVecTwo = (iVecOne+1):nVec
        if abs(vector(iVecOne, :) * vector(iVecTwo,:)') > zerotol
            error('elk:polytope:wrongInput', ...
                  'provided vectors are not orthogonal');
        end
    end
end

%% obtain rotation matrix by svd
% normalize vectors
vector = bsxfun(@times, ...
    1./sqrt(sum(vector.^2, 2)), ...
    vector);

[U, S, V] = svd(vector);
rot = V';