%---------------------------------------------------------------------  
% function [cells]=FT_split_line(textline,delimiter)
% 
% Splits a text line into separate cells
%
% textline: string, text input 
% delimiter: string filled with characters to separate
%            (leave empty for 'any whitespace')
% cells: array of cells containing the parts of the string
%
% Part of the SimTools package
% Andreas Freise 04.07.08 afreise@googlemail.com
%---------------------------------------------------------------------  

function [cells]=FT_split_line(textline,delimiter)
  
  baseid='FT_line_split';

  if (~isstr(textline))
    msgid=[baseid,':checkinarg'];
    msg='first input argument must be a string';
    error(msgid,msg);
  end

  if (~isstr(delimiter) && ~isempty(delimiter))
    msgid=[baseid,':checkinarg'];
    msg='second input argument must be a string';
    error(msgid,msg);
  end
  
  % initialise return variable
  cells={};
  
  % new Matlab versions can do 'split'. For the
  % moment we use old code that runs also on former
  % versions. TODO make an intelligent check for the
  % MATLAB version
  new=0;
  if (new)
    if (isempty(delimiter))
      delimiter='\s+';
    end
    cells=regexp(textline, delimiter, 'split');
  else
    % following code provided by Bryan Barr
    tmp_line=textline;
    n=length(tmp_line);
    for i=1:n
      if (isempty(delimiter))
        [tmp_cell,tmp_line]=strtok(tmp_line);
      else
        [tmp_cell,tmp_line]=strtok(tmp_line,delimiter);
      end        
      cells{1,i}=strtrim(tmp_cell);
      if (isempty(tmp_line))
        break;
      end
    end
  end
  
  % remove empty cells
  index=cellfun(@(x) isempty(x),cells); 
  cells=cells(~index);
  