function vrep = convertHrepToVrepByCddlib(hrep, maxTrial)
% convert the H-representation of a polytope into V-representation
%
% Syntax: vrep = convertHrepToVrep(hrep, zerotol, infinityBoxSize)
%
% The input should already be scaled by calling function.
% 
% Consider that cddlib applies an additional zerotol that is stored in the 
%   function zerotolCddlib during initialization of this library 
%   (buildCddlib).
%
% THIS FUNCTION 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/>.

%% conversion
% the try/catch environment and while-loop is connected to a currently 
%   "strange" numerical behavior of cddlib. It seems to be sensitive to
%   slight adjustments of the input (e.g. scaling).
callCddLibLoop = 1;
extraScalingVector = [1 (0.1 + linspace(0, 0.8, maxTrial-1))];
thisExtraScaling = extraScalingVector(1);
hrepExtraScaled = hrep;
while callCddLibLoop
    try
        resCddlib = callCddLib('extreme', ...
            struct('A', hrepExtraScaled.A, 'B', hrepExtraScaled.h));
        callCddLibLoop = 0;
    catch dumpError
        callCddLibLoop = callCddLibLoop + 1;
        if callCddLibLoop > maxTrial
          % we don't want to rethrow the error message that would be:
          %   "CDD returned an error, see above(!) for details", instead we
          %   use:
          error('elk:polytope:conversion', ['cddlib (MEX-interface) ' ...
                'returned an error']);
        end
        thisExtraScaling = extraScalingVector(callCddLibLoop);
        hrepExtraScaled = stretchHrep(hrep, thisExtraScaling);
    end
end
% strip everything except field V
vrepExtraScaled = struct('V', resCddlib.V);

% failure if there are rays (unbounded polytope)
if ~isempty(resCddlib.R)
    vrep = [];
else
    if thisExtraScaling ~= 1
        vrep = stretchVrep(vrep, 1/thisExtraScaling);
    else
        vrep = vrepExtraScaled;
    end
end