% CB_EXPORTWS stores the selected blocks outputs to the workspace
%
% CALL: LTPDAworkbench.cb_exportWS
%
% M Hewitson 13-11-08
%
% $Id: cb_exportWS.m,v 1.5 2010/08/06 19:10:48 ingo Exp $
%
function cb_exportWS(varargin)
  
  wb = varargin{1};
  
  % Get all selected blocks
  sbs = awtinvoke(wb.mp, 'getSelectedBlocks');
  
  outvars = {};
  for ii=0:sbs.size()-1
    block = sbs.get(ii);
    
    % if this is a MElementWithPorts
    if isa(block, 'mpipeline.canvas.MElementWithPorts')
      
      % loop over all outputs
      outports = block.getOutputs();
      for kk=0:outports.size()-1
        op = outports.get(kk);
        % get variable name
        outvar = LTPDAworkbench.getWS_VarName(wb.UUID, block, op.getNumber);
        outvars = [outvars {outvar}];
      end
    end
  end
  
  % Check if each var exists in the workspace, and then store in workspace
  try
    for kk=1:numel(outvars)
      
      % get class of the object
      cl = evalin('base', [ 'class(' outvars{kk} ')']);
      
      % get new var name
      %   - this means split the outvar at the last '.'
      nv = getVar(outvars{kk});
      
      if ismember(cl, utils.helper.ltpda_userclasses)
%         cmd  = [nv ' = ' cl '(' outvars{kk} ');'];
        cmd  = [nv ' = copy(' outvars{kk} ',1);'];
      else
        cmd  = [nv ' = ' outvars{kk} ';'];
      end
      evalin('base', cmd);
    end
  catch
    utils.helper.errorDlg('Unable to export selected objects. Has the pipeline been executed?', 'Export to workspace error');
  end
  
  
end

function nv = getVar(ov)
  
  nv = '';
  
  for kk=length(ov):-1:1
    if ov(kk) == '.'
      break
    else
      nv = [nv ov(kk)];
    end
  end
  
  nv = nv(end:-1:1);
  
end
