function [pass,results] = check_matlab_syntax(myfolder,varargin)
% pass = check_matlab_syntax(myfolder,varargin)
%
% Checks matlab syntax for all .m files in a folder.
% Returns false if a syntax error is found.
%
% Also checks and optionally displays McCabe complexity of code
%
% optional arguments:
%   verbosity: display detail level (0-4)
%             3 or higher shows McCabe complexity of each file
%   severity: level of severity that returns error
%             2 : Check only for errors (Default)
%             1 : Check also for warnings
%             0 : Check also harmless things
%
% [+GenLib General Purpose Library+] Swiss Plasma Center EPFL Lausanne 2022. All rights reserved.

% F. Felici SPC 2020

aa=ver('matlab');
assert(str2double(aa.Version)>=9.6,'check_matlab_syntax requires matlab version 9.6 or higher')

[verbosity,severity] = parse_inputs(varargin{:});

import matlab.unittest.parameters.Parameter
import matlab.unittest.TestSuite
import matlab.unittest.TestRunner

oldpwd = pwd;
try
  cd(myfolder)
  
  % pass external parameters to the parametrized test
  param = Parameter.fromData('MaxSeverity',{severity});
  % build test suite with this parameter
  suite = TestSuite.fromClass(?test_matlab_syntax,'ExternalParameters',param);
  
  % build a runner with the desired verbosity level
  runner = TestRunner.withTextOutput('LoggingLevel',verbosity);
  
  % run the tests
  results = runner.run(suite);
  
  % result
  pass = all([results.Passed]);
  
  % back to old dir
  cd(oldpwd)
  
catch ME
  % in case something goes wrong, go back to old dir
  cd(oldpwd)
  rethrow(ME);
end
%%
end

function [verbosity,severity] = parse_inputs(varargin)
p = inputParser();
addParameter(p,'verbosity',1,@(x) isnumeric(x) && isscalar(x) && (x>=0));
addParameter(p,'severity',2,@(x) isnumeric(x) && isscalar(x) && (x>=0));
parse(p,varargin{:});
verbosity = p.Results.verbosity;
severity = p.Results.severity;
end
