

function [options, newvarargin] = parseArgs(options, varargin)

    % ---------------------------------------------------
    % CODE ORGINATED FROM STACKOVERFLOW & THEN MODIFIED
    %   http://stackoverflow.com/questions/2775263/how-to-deal-with-name-value-pairs-of-function-arguments-in-matlab
    % ---------------------------------------------------
    
    % GET OPTIONS NAMES
    optionNames = fieldnames(options);

    % COUNT ARGUMENTS
    nArgs = length(varargin);
    if round(nArgs/2)~=nArgs/2
       error('Function needs propertyName/propertyValue pairs')
    end
    
    
    % PARSE ARGUMENTS
    n = 1; flag = false;
    newvarargin = {};
    for m = 1:numel(varargin)
       if flag, flag = false; continue; end
       inpName = varargin{m}; % make case insensitive

       if any(strcmpi(inpName,optionNames)) && m < numel(varargin) && ~isempty(varargin{m+1})
          % overwrite options. If you want you can test for the right class here
          % Also, if you find out that there is an option you keep getting wrong,
          % you can use "if strcmp(inpName,'problemOption'),testMore,end"-statements
          options.(inpName) = varargin{m+1}; flag = true;
       else
          newvarargin{n} = varargin{m}; n = n + 1;
       end
    end

end


