%
%--------------------------------------------------------------------------
% function [outstring] = FT_replace_underscores(instring, new_char)
%
% A function for Matlab which replaces the underscores (_) in a string
% by a given character.
%
% instring: input string
% new_char: char or string that should be used to replace '_'
% outstring: output string
%
% Charlotte Bond  18.07.2008
%--------------------------------------------------------------------------
%

function [outstring] = FT_replace_underscores(instring, new_char)

baseid='replace_underscores';

if(~ischar(new_char))
  msgid=[baseid,':checkinputargument'];
  result='new_char must a chararcter or string';
  error(msgid,result);
end

% Identify all underscore characters and replace them the new character.
index=find(instring=='_');
% if no '_' are found, return full string
if (isempty(index))
  outstring=instring;
elseif (length(new_char)==1) 
  % if new character is single char, use a simple replace
  outstring=instring;
  outstring(index)=new_char;
else  
  % if '_' should be replaced by a string, we have to split and merge the instring
  lidx=length(index);
  lstr=length(instring);
  if (index(1)==1)
    outstring='';
  else
    outstring=instring(1:index(1)-1);
  end
  outstring=[outstring,new_char];  
  for i=2:lidx
    outstring=[outstring,instring(index(i-1)+1:index(i)-1),new_char];
  end  
  if (index(lidx)<lstr)
    outstring=[outstring,instring(index(lidx)+1:lstr)];
  end
end

        
