function varargout = hapticTool(varargin)
% function [transformsOut, volumesOut, pointSetsOut, indexedLineSetsOut, ...
%     clipPlanesOut] = ...
%     hapticTool(transforms, volumes, pointSets, indexedLineSets,
%     clipPlanes, options)
%
%   A 3d haptic viewer based on H3DApi. 
%  
%   Author: Johann Strasser
%   Date: 061123 (YYMMDD)
%
%   Revisions:
%
%   Date: 090320
%
%   Added options structure and therefore changed the calling method
%   to variable argument list to enable code calling hapticTool
%   with 5 argument to remain unchanged. Note, however, that we still
%   assume the same order of arguments as in the old conventional
%   5 argument interface.

error(nargchk(0, 6, nargin));

% Process input arguments
transforms = varargin{1} ;
volumes = varargin{2};
pointSets = varargin{3};
indexedLineSets = varargin{4};
clipPlanes = varargin{5};

if nargin == 6
    options = varargin{6};
else
    options = getHTDefaultOptions();
end

% Determine location of m-file, cd() to hapticTool directory, then cd()
% back to original location when finished executing. This is necessary as
% the native hapticTool code reads files at startup and file paths are
% given relative in order to be deployable on different machines.
hapticToolFullPath = which('hapticTool');

originalDir = pwd;
[path, name, ext, versn] = fileparts(hapticToolFullPath);
cd(path);

for i = 1:size(volumes, 2)
    dims = size(volumes(i).volume);
    volumes(i).volume = shiftdim(volumes(i).volume, 3);
    volumes(i).volume = reshape(volumes(i).volume, dims);
end

debug = 0;

if debug

% Use the debug version of the mex-file
 [transformsOut, volumesOut, pointSetsOut, indexedLineSetsOut, ...
     clipPlanesOut] =...
    hapticToolMexd(transforms, volumes, pointSets, indexedLineSets, clipPlanes, options);

% Clear the native function. This is necessary to circumvent the
% disappearing fonts issue, where fonts are not rendered on repeated
% execution of the native hapticTool function. Without invoking clear after
% each call only the first invokation displays the ftgl fonts used by
% H3DApi. The reasons for this are unknown.
clear hapticToolMexd;
else
    
% Use the release version of the mex-file
 [transformsOut, volumesOut, pointSetsOut, indexedLineSetsOut, ...
     clipPlanesOut] =...
    hapticToolMex(transforms, volumes, pointSets, indexedLineSets, clipPlanes, options);

% Clear the native function. This is necessary to circumvent the
% disappearing fonts issue, where fonts are not rendered on repeated
% execution of the native hapticTool function. Without invoking clear after
% each call only the first invokation displays the ftgl fonts used by
% H3DApi. The reasons for this are unknown.
clear hapticToolMex;
end

varargout{1} = transformsOut;
varargout{2} = volumesOut;
varargout{3} = pointSetsOut;
varargout{4} = indexedLineSetsOut;
varargout{5} = clipPlanesOut;

% Return to original working directory
cd(originalDir);
