function result = path2rc(outputfile)
%PATH2RC Save the current MATLAB path in the pathdef.m file.
%   PATH2RC saves the current MATLABPATH in the pathdef.m
%   which was read on startup.
%
%   PATH2RC outputFile saves the current MATLABPATH in the
%   specified file.
%
%   PATH2RC returns:
%     0 if the file was saved successfully
%     1 if the file could not be saved
% 
%   See also PATH and PATHTOOL.

%   Copyright 1984-2000 The MathWorks, Inc. 
%   $Revision: 1.20 $

% Assume that things are going well until we learn otherwise.
result = 0;

% Unless the user specifies otherwise, we're going to overwrite the
% pathdef.m file that MATLAB currently sees.
if nargin == 0
    outputfile = which('pathdef.m');
end

% This is a token string that we will look for in the template file.
magic_string = 'PLEASE FILL IN ONE DIRECTORY';

templatefile = fullfile(matlabroot, 'toolbox', 'local', 'template', 'pathdef.m');

% Try to read the template file.  If we can't, that's OK, we have a
% backup plan.
fid = fopen(templatefile, 'r');

if fid ~= -1
    template = char(fread(fid)');
    fclose(fid);
else
    template = ['function p = pathdef', 10, 'p = [...', 10, ...
        magic_string, 10, '...', 10, '];' 10, 'p = [userpath,p];', 10];
end

% Find the location of the "magic string" in the file.
magic_index = findstr(template, magic_string);

% Take everything that appears *before* the "magic string" line as
% "firstpart," and everything that appears after that line as
% "lastpart."
% We'll sandwich the path particulars between the two ends.
firstpart = template(1:magic_index-1);
lastpart = template(magic_index + 1:end);

lfs_in_firstpart = find(firstpart == 10);
firstpart = firstpart(1:lfs_in_firstpart(end)-1);
firstpart = [firstpart, 10];

lfs_in_lastpart = find(lastpart == 10);
lastpart = lastpart(lfs_in_lastpart(1)+1:end);

% Read the current path.
thepath = matlabpath;

% Get the exact form of the entries that we want to create in the
% new pathdef file based on the path.  all_path_lines will be a
% cell array of strings.
all_path_lines = getLines(thepath);

% Start constructing the contents of the new file.  We start with
% the firstpart.
cont = firstpart;

% Append the results of getLines, one line at a time.
for (i = 1:length(all_path_lines))
    cont = [cont all_path_lines{i} 10];
end

% Conclude with the lastpart.
cont = [cont lastpart];

% We have the completed new text of the file, so we try to write it out.
fid = fopen(outputfile, 'w');
if fid == -1
    % We failed to open the file for writing.  That might be
    % because we don't have write permission for that file.  Let's
    % try to make it read-write.
    
    if (isunix)
        [d1, d2] = unix(['chmod 666 ''', outputfile, '''']); 
    elseif (ispc & ~strncmpi('\\', pwd, 2))
        [d1, d2] = dos(['attrib -r "', outputfile, '"']);
    end
    % Last chance.  Can we write to it?  If we fail here, we have
    % no choice but to fail.
    fid = fopen(outputfile, 'w');
    if fid == -1
    	result = 1;
    	return;
    end
end

% Write it out.
count = fwrite(fid, cont);
if count < length(template)
    result = 1;
end
fclose(fid);

%---------------------------------------------
function all_path_lines = getLines(thePath)
% Given the current path, creates valid entries for the new
% pathdef.m file.

% First, Break the path down into a cell array of strings, one for
% each entry in the path.  We leave the pathsep on the end of each
% string.  The path might not actually *end* with a pathsep, but if
% not, we add one for consistency's sake.
lastsep = 0;
if (thePath(end) ~= pathsep)
    thePath = [thePath pathsep];
end

allseps = find(thePath == pathsep);
allseps = [0 allseps];

% Start constructing the cell array, "matlabroot-ifying" and
% formatting properly.
all_path_lines = cell(0);
for (i = 2:length(allseps))
    all_path_lines{end+1} = ...
        matlabrootify(thePath(allseps(i-1)+1 : allseps(i)));
end

%---------------------------------------------
function dirname = matlabrootify(dirname)
% Given a path entry, this performs two functions:
% (1) If the directory under consideration is a subdirectory of
% matlabroot, it encodes that information directly into the
% string.  Therefore, even if the location of the MATLAB
% installation is changed, pathdef.m will still point to the
% appropriate location.
% (2) Performs additional formatting.

mlroot = matlabroot;

% If we're on PC, we want to do our comparisone in a
% case-insensitive fashion.  Since it also doesn't matter what case
% the entries are made in, we might as well lowercase everything
% now - no harm done.
if ispc
    mlroot = lower(matlabroot);
    dirname = lower(dirname);
end

% If the directory is a subdirectory of matlabroot (or is
% matlabroot itself), start matlabroot-ifying it.
startloc = findstr(dirname, mlroot);
if ~isempty(startloc) & startloc == 1
    if length(mlroot) + 1 < length(dirname)
    	dirname = ['matlabroot,''', dirname(length(mlroot)+1:end), ''''];
    elseif length(mlroot) + 1 == length(dirname)
        dirname = ['matlabroot,''', pathsep, ''''];
    end
else
    % The directory isn't related to matlabroot in any meaningful
    % way.  Just do the formatting modifications.
    dirname = strrep(dirname, '''', '''''');
    dirname = ['''', dirname, ''''];
end

dirname = [dirname ',...'];
