function volume = computeVolumeVrep(vrep, zerotol)
% compute the volume of a polytope in V-representation
%
% Syntax: volume = computeVolumeVrep(vrep)
%
% Compute the volume based on MATLAB function convhulln that itself relies
%   on qhull.
%
% computeVolumeVrep(..., zerotol) allows to set the tolerance for 
%   underlying algorithms (e.g. determining flat polytopes) (Default in 
%   elkZerotol).
%
% See also: computeVolumeHrep, computeFacetAreaVrep,
%   computeProjectionAreaVrep, computeFeretVrep, computeSupportValueVrep

% 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')
    zerotol = elkZerotol;
end

%% Collect 1-dim and 2-dim
% they are not properly treated by convhulln.
if size(vrep.V, 2) == 0
    volume = 0;
    return;
elseif size(vrep.V, 2) == 1
    volume = max(vrep.V) - min(vrep.V);
    return
elseif size(vrep.V, 1) <= size(vrep.V, 2)
    % a polytope requires at least (nDim+1) extreme points
    volume = 0;
    return
end

%% Collect obviously degenerates and simplices
if size(vrep.V, 1) <= size(vrep.V, 2)
    volume = 0;
    return
elseif size(vrep.V, 1) == size(vrep.V, 2) + 1
    volume = abs(1/factorial(size(vrep.V, 2)) * ...
                 det(bsxfun(@minus, vrep.V(2:end, :), vrep.V(1,:)))...
                 );
    return
end

%% Scaling
[vrepScaled, scale, ~] = scaleVrep(vrep, zerotol, 1);

%% Checking, whether Vrep is full-dimensional
% Sometimes it is hard for qhull to recognise flat polytopes. In n 
%   dimensions n+1 'proper' vertices are required to form a simplex. One of
%   them can be moved to the origin at all times which leaves n verties 
%   that simply must have the full rank to form a full-dimesnional 
%   polytope.
vrepTmp = moveVrep(vrepScaled, -1*vrepScaled.V(1,:));
if rank(vrepTmp.V, zerotol) < size(vrepTmp.V, 2)
    volume = 0;
    return
end

%% Volume calculation
%! debug: the enclosed try/catch is debug code, you may uncomment it to
%         have a look on the polytope that causes troubles. It should not %
%         be flat polytope.
% unfortunatelly, convhulln sometimes throws errors on non-singular
% polytopes so that the command is enclosed in a try/catch environment.
try  
    % Option 'Qs' selected because generic_paracetamol_15 throws an error
    %   during decomposition otherwise. From this error, the following line
    %   was contained: "use 'Qs' to search all points for the initial
    %   simplex"
    [~, volume] = convhulln(vrepScaled.V, {'Qt', 'Qs'});
catch errMsg
%     try
%         % joggling input for qhull. This may be required for some
%         % examples. (http://www.qhull.org/html/qh-optq.htm#QJn)
%         [~, volume] = convhulln(vrep, {['QJ1e' num2str(log(zerotol)/log(10))]});
%     catch
      
        % if this does not work, save the case for further analysis
        if exist('log_computeVolumeVrep.mat', 'file')
            load log_computeVolumeVrep.mat
            logVrep{end+1} = vrep;
        else
            logVrep{1} = vrep;
        end
        save log_computeVolumeVrep.mat logVrep
        error('elk:polytope:computeMeasure', ...
            ['Something is wrong. Polytope stored in ' cd filesep 'log_computeVolumeVrep.mat']);
        
%     end %/
end

%% consider scaling
volume = volume * scale^(size(vrep.V, 2));

end
    