function s = newext(old, new, fname, varargin)
%  1.  NAME
%
%  newext - Change the extension of file names
%
%  2.  SYNOPSIS
%
%  s = newext(old, new, fname, delim )
%
%  3.  DESCRIPTION
%
%  Return a string for a file name with a new extension. The extension
%  delimiter can be specified to allow other changes in file names. The
%  following rules take place:
%
%  o  item_( For multiple extensions, only the last occurence of old is
%     replaced with new.  )
%
%  o  If the string old is not present in fname,the last extension is
%     replaced by new.
%
%  o  If the file does not contain any extension,the extension new is
%     appended to it.
%
%  4.  PARAMETERS
%
%     old
%        String with old extension.
%
%     new
%        String with new extension.
%
%     fname
%        Name of file.
%
%     delim optional
%        Specifies the extension delimeter to use. Default is ''. If
%        delim is s tring with more than one character,all of them are
%        used as the extension delimiter.
%
%  5.  RETURNS
%
%  The new file name.
%
%  6.  AUTHORS
%
%  Pierre Jaccard, Geophysical Institute, University of Bergen, 1999
%

delim = '.';
if nargin > 3,
  delim = varargin{1};
end

% Split the file name:
f = strsplit(fname, delim);
f= cellstr(f);

% Get index to `old' occurences:
l = strcmp(f, old);
ind = find(l);

if length(ind) > 0,
  % Change the last occurence of `old' extension:
  l = length(ind);
  f{ind(l)} = strrep(f{ind(l)}, old, new);
elseif length(f) > 1,
  % Change the last extension:
  l = length(f);
  f{l} = new;
else
  % append the `new' extension:
  l = length(f);
  f{l+1} = new;
end

% Rebuild the file name:
s = f{1};
l = length(f);
for i=2:l,
  s = [s delim f{i}];
end

return;

  



