function [tempDir, cgDir] = coderdemodir(tempSubDir)
% CODERDEMODIR - Create and change to a temporary working directory.
%
%   [TEMPDIR, CGDIR] = CODERDEMODIR(TEMPSUBDIR)
%
%   TEMPSUBDIR - name of temporary sub-directory
%   TEMPDIR    - full path to the temporary directory
%   CGDIR      - full path to the code generation directory
%
% TEMPDIR and CGDIR are the same directory when Simulink preference
% 'File generation control' is not set.
%
% Example usage:
%   >> currentDir = pwd;  % Save location of current working directory
%   >> [tmpdir, cgdir] = coderdemodir('sl'); % Create & move to temp directory
%   >> cd(currentDir) % Return to previous working directory
  
% Copyright 1994-2018 The MathWorks, Inc.

tempDir = fullfile(tempname,tempSubDir);

if strcmp(tempDir,pwd)
    cd('..')
end

if exist(tempDir,'dir') == 7
    try
        clear mex
        rmdir(tempDir,'s')
    catch ME
        sprintf('Unable to remove directory: %s\n%s',...
            tempDir',ME.identifier)
    end
end

if exist(tempDir,'dir') == 0
  mkdir(tempDir);
end
cd(tempDir);

cgDir = get(Simulink.fileGenControl('getConfig'),'CodeGenFolder');

end
