function meanWidth = computeMeanWidthVrep(vrep, zerotol)
% compute the mean width of a polytope in V-representation
%
% Syntax: meanWidth = computeMeanWidthVrep(vrep)
%
% computeMeanWidthHrep(.., zerotol) allows to set the tolerance for 
%   underlying algorithms (determining flat polytopes; default in
%   elkZerotol).
%
% See also: computeMeanWidthHrep, computeVolumeHrep, computeFacetAreaHrep, 
%   computeFeretHrep, obtainMeasureInfo

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

% default zerotol
if ~exist('zerotol', 'var')
    zerotol = elkZerotol;
end

% check dimension
if size(vrep.V, 2) > 3
    error('elk:polytope:inputError', ...
        'Only 1-, 2- or three dimensional polytopes can be handled');
elseif size(vrep.V, 2) == 2
    meanWidth = computeFacetAreaVrep(vrep, [], zerotol) / pi;
    return
elseif size(vrep.V, 2) == 1
    meanWidth = computeVolumeVrep(vrep, zerotol);
    return
elseif size(vrep.V, 2) == 0
    meanWidth = 0;
    return
end
% from here on, we only treat 3D polytopes
    
% obtain edge-information
hrep = convertVrepToHrep(vrep, zerotol);
vrepReduced = reduceVrepDimension(vrep, zerotol);

if size(vrepReduced.V, 2) < size(vrep.V, 2)
    meanWidth = computeMeanWidthVrep(vrepReduced, zerotol);
    if size(vrep.V, 2) == 3 && size(vrepReduced.V, 2) == 1
        meanWidth = 0.5*meanWidth;
    elseif size(vrep.V, 2) == 3 && size(vrepReduced.V, 2) == 2
        meanWidth = 0.25*pi*meanWidth;
    end
else
    edgeStruct = computeEdgeSetVrep(vrep, 'hrep', hrep, ...
        'zerotol', zerotol, 'output', 'full');
    % call mean width core algorithm
    meanWidth = computeMeanWidthCore(hrep, vrep, edgeStruct);
end