% PARSECMD parses a command string comming from hist2m to information
% needed to build a block.
%
% CALL: out = parseCmd(cmd)
%
%  Returns a structure:
%
%   out.outname
%   out.outports
%   out.innames
%   out.inports
%   out.method
%   out.class
%   out.plists
%
% M Hewitson 12-11-10
%
% $Id: parseCmd.m,v 1.3 2010/08/06 19:10:49 ingo Exp $
%
function  out = parseCmd(cmd)
  
  pcmd = LTPDAworkbench.parse(cmd);
  
  % check for block name from comment
  blockname = '';
  methodclass = '';
  if ~isempty(pcmd.comment)
    % look for block name
    st = regexp(pcmd.comment, '\|', 'split');
    if numel(st)==2
      blockname = strrep(strtrim(st{2}), ' ', '_');
    else
      blockname = '';
    end
    % and method class
    methodclass = strtrim(st{1});
  end
  
  % get output ports
  outnames = pcmd.outvars;
  outports = zeros(size(outnames));
  for kk=1:numel(outnames)
    pstrs = regexp(outnames{kk}, '_PORT(\d*)', 'tokens');
    if ~isempty(pstrs)
      outports(kk) = str2double(pstrs{1}{1});
    end
  end
  
  % get input ports
  innames = pcmd.invars;
  inports = zeros(size(innames));
  for kk=1:numel(innames)
    pstrs = regexp(innames{kk}, '_PORT(\d*)', 'tokens');
    if ~isempty(pstrs)
      inports(kk) = str2double(pstrs{1}{1});
    end
  end
  
  % either take the block name from the comment, or
  % from the first output name
  if isempty(blockname)
    if numel(outnames) > 0
      blockname = outnames{1};
    else
      blockname = 'unknown';
    end
  end
  
  % If methodclass is empty, we need an alternative
  % = just look for the first class method of LTPDA that
  % matches the function name
  if isempty(methodclass)
    cls = utils.helper.ltpda_userclasses;
    for kk=1:numel(cls)
      cl = cls{kk};
      mts = methods(cl);
      for ll=1:numel(mts)
        mt = mts{ll};
        if strcmp(mt, pcmd.method)
          methodclass = cl;
          break;
        end
      end
    end
  end
  if isempty(methodclass)
    error('### Unable to determine the class of method: %s', pcmd.method);
  end
  
  out.outname = strtrim(blockname);
  out.outports = outports;
  out.innames = pcmd.invars;
  out.inports = inports;
  out.method = pcmd.method;
  out.class = methodclass;
  out.plists = pcmd.pls;
  
end


