function createDriverProject(projectDir)
%createDriverProject Create a new device driver project folder.
%
% Example:
%
%createDriverProject('C:\Work\tmp102_driver')

% Copyright 2016-2018 The MathWorks, Inc.
projectDir = convertStringsToChars(projectDir);
validateattributes(projectDir,{'char'},{'row','nonempty'},'','projectDir');

% Check if project folder is under MATLAB root
projectDir = i_reduceDotDot(projectDir);
if startsWith(projectDir,matlabroot)
    error('codertarget:utils:InvalidProjectFolder',...
        'Device driver project folder cannot be under MATLAB installation folder.');
end

% Create project directory structure
i_createFolder(projectDir);
i_createFolder(fullfile(projectDir,'src'));
i_createFolder(fullfile(projectDir,'include'));

% Copy System object templates to project folder
i_copySysObjects(projectDir);
fprintf('Created device driver project folder "%s"...\n',projectDir);
end

%% Local functions
function i_createFolder(folderName)
if ~exist(folderName,'dir')
    mkdir(folderName);
end
end

function i_copySysObjects(projectDir)
src = {which('codertarget.Source'),...
    which('codertarget.Sink')};
for k = 1:numel(src)
    [~,n,ext] = fileparts(src{k});
    srcName = [n,ext];
    if ~exist(fullfile(projectDir,srcName),'file')
        copyfile(src{k},projectDir,'f');
    else
        warning('codertarget:utils:SystemObjectExists',...
            '%s already exists in %s. Skipping this file.',...
            srcName,projectDir);
    end
end
end

function pathOut = i_reduceDotDot(pathIn)
%I_REDUCEDOTDOT simplifies a path containing ./.. characters
[p,f,e] = fileparts(pathIn);
parts = {};
while ~isempty(f)
    folder = [f e];
    if ~isempty(parts) && ~strcmp(folder, '..') && strcmp(parts{end}, '..')
        parts = parts(1:end-1);
    else
        parts{end+1} = folder; %#ok<AGROW>
    end
    [p,f,e] = fileparts(p);
end

pathOut = p;
while ~isempty(parts)
    pathOut = fullfile(pathOut,parts{end});
    parts = parts(1:end-1);
end
end
%[EOF]
