function ccsVersionVal = CCSVersionDetect(hCS)
% CCSVERSIONDETECT Function to determine installed CCS version to be used

%   Copyright 2018-2021 The MathWorks, Inc.

targetFolder = codertarget.target.getTargetFolder(hCS);
attribFileName = codertarget.target.getThirdPartyToolsRegistrationFileName(targetFolder);
h = codertarget.thirdpartytools.ThirdPartyToolInfo(attribFileName);
attributes = h.getThirdPartyTools();

scriptTokenName = 'CCSSCRIPTINGDIR';
if exist(attribFileName, 'file')
    for i=1:numel(attributes)
        if strcmp(attributes{i}{:}.TokenName, scriptTokenName)
            scriptFilePath = attributes{i}{:}.RootFolder;
            break;
        else
            scriptFilePath = '';
        end
    end
else
    scriptFilePath = '';
end

if ~(exist(attributes{i}{:}.RootFolder, 'dir') == 7)
    error(message('TIC2000:codegen:ThirdPartyToolNotSetup', 'TI Code Composer Studio'));
end
verFilePath = fullfile(scriptFilePath,  '..', '..', 'doc');
verFiles = dir(fullfile(verFilePath, '*.htm'));
verFilesName = {verFiles.name}';
%Filter the .htm files to be read in directory with key words Release
%Note
verFileMatch = '\w*Release\w*Note\w*';
%Function handle to handle all the htm files at once
verFileFunHandle = @(str) cellfun(@(c) ~isempty(c), regexp(verFilesName, str, 'once'));
verFile = verFilesName(verFileFunHandle(verFileMatch));
%Only one or atleast one release not file should be present
if numel(verFile) == 1
    ccsVersion = '';
    verPattern  = 'Code\s\Composer\sStudio\W*v(\d.)';%read the main version X of vX.Y.Z
    fid = fopen(fullfile(verFilePath, verFile{1}));
    versionContent = fread(fid, 32768, '*char').'; % Read up to 32Kb chars
    fclose(fid);
    verInfo = regexp(versionContent, verPattern, 'tokens');
    %Convert all the values to char for further proxessing
    verInfoStr = cellfun(@(c) cellstr(c), verInfo);
    if ~isempty(verInfo)
        ccsVersion = cellfun(@(c) regexprep(c, '_', '.'), verInfoStr, 'UniformOutput',false);
        % Remove trailing dots
        ccsVersion = cellfun(@(c) regexprep(c, '\.+$', ''), ccsVersion, 'UniformOutput',false);
    end
    %Out of multiple versions read from the release note file, consider
    %the maximum version as valid one.
    ccsVersionVal = max(str2double(ccsVersion));
else
    %No valid Release Note file present or more than one Release Note
    %file is present. Nothing to be done
    ccsVersionVal = 0;
end
end