%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Build SFunctions and link static libraries located inside
% the default TwinCAT Target custom libraries folder
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% Beckhoff Automation GmbH
% 02.04.2015
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function BuildSFunctionWithTctLibDependencies(srcFiles,libName,libdir)

    % Neccessary simulink include directory, which is
    % not set by default in all matlab versions:
    includedir = [matlabroot '\simulink\include'];

    % Default tct custom libraries folder
    if (nargin<3)
        tc3InstallDir = getenv('TwinCAT3Dir');
        libdir = [tc3InstallDir '..\Functions\TE1400-TargetForMatlabSimulink\Libraries'];
    end
    linkdir = [libdir '\' computer('arch') '\R' version('-release')];
    addpath(linkdir);

    % Check compiler configuration
    CheckCompilerConfiguration();
    
    % Run MEX-Compiler
	if (nargin < 2)
		mex(['-I' includedir ''],srcFiles);
    else
        mex(['-I' includedir ''],['-l' libName ''],['-L' linkdir ''],srcFiles);
    end
end