%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Check MEX compiler settings for use with TwinCAT Target
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Beckhoff Automation GmbH
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function configValid = CheckCompilerConfiguration(invokeMexSetup)
	if (nargin < 1)
		invokeMexSetup = true;
    end
    mexSetupExecuted = false;
    
    configValid = true;
    
	% check mex compiler settings
    CC = mex.getCompilerConfigurations();
    CC = CC(1);
    if (~strcmpi(CC.Name,'Microsoft Visual C++ 2010') && ~strcmpi(CC.Name,'Microsoft Visual C++ 2012') && ~strcmpi(CC.Name,'Microsoft Visual C++ 2013') && ~strcmpi(CC.Name,'Microsoft Visual C++ 2015') && ~strcmpi(CC.Name,'Microsoft Visual C++ 2017') && ~strcmpi(CC.Name,'Microsoft Visual C++ 2019'))
        configValid = false;
        warning ('A compiler other than "Microsoft Visual C++ 2010..2019" was configured.');
        if (invokeMexSetup)
            disp('Please select a compatible C++ combiler in the next promts to complete the setup.');
            disp('Recommended compilers are "Microsoft Visual C++ 2010..2019".');
            mex -setup;
            mexSetupExecuted = true;
        end
    end
    
    x64Configured = ~isempty(strfind(upper(CC.Details.CommandLineShellArg),'64'));
    if (x64Configured)
        archConfigured = 'win64';
    else
        archConfigured = 'win32';
    end
    arch = computer('arch');
    x64Arch = strcmpi(arch,'win64');
    if xor(x64Configured,x64Arch)
        configValid = false;
        if (invokeMexSetup)
            warning (['The MEX compiler is configured for architecture "' archConfigured '" but you are working on "' arch '".']);
            disp('Please select a compatible C++ combiler in the next promts to complete the setup.');
            disp('The recommended compiler is "Microsoft Visual C++ 2017".');
            mex -setup;
            mexSetupExecuted = true;
        else
            warning (['The MEX compiler is configured for architecture "' archConfigured '" but you are working on "' arch '".']);
        end
    end
    if (mexSetupExecuted)
        configValid = CheckCompilerConfiguration(false);
    end
end