%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Open VisualStudio 20xx project with MATLAB build environment
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Beckhoff Automation GmbH
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

% find visual studio install dir
function OpenVsProjectWithMatlabEnvironment(projectPath)
    
    % define mex build environment
    setenv('MATLAB_RELEASE',['R' version('-release')]);
    setenv('MATLAB_ROOT',[matlabroot '\']);

    % start Visual Studio and open project
    system(['"' devEnvDir() 'devenv.exe" ' projectPath ' &']);
end


function devEnvDir = devEnvDir()
	% find visual studio installation folder
    devEnvDir = '';
	for vsVer = [16 15 14 12 11 10]
        if (~isempty(devEnvDir))
            break;
        end
        for vsKey={'SOFTWARE\Microsoft\VisualStudio\' 'SOFTWARE\Wow6432Node\Microsoft\VisualStudio\'}
            if (~isempty(devEnvDir))
                break;
            end
            try
                key = [vsKey{1} num2str(vsVer) '.0'];
                devEnvDir = winqueryreg('HKEY_LOCAL_MACHINE', key , 'InstallDir');
            end
        end
    end
    if isempty(devEnvDir)
        error('Could not find "VisualStudio 2010..19" on your system. Please make sure, you installed it correctly.');
    end
	setenv('DevEnvDir',devEnvDir);
end