% CB_SAVEOBJECTS save the outputs of the currently selected blocks
%
% CALL: LTPDAworkbench.cb_saveObjects
%
% M Hewitson 13-11-08
%
% $Id: cb_saveObjects.m,v 1.3 2010/08/06 19:10:48 ingo Exp $
%
function cb_saveObjects(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 save them
  
  out = {};
  try
    if ~isempty(outvars)
      for kk=1:numel(outvars)
        disp(sprintf('** adding %s [%s] to collection', outvars{kk}, evalin('base', ['class(' outvars{kk} ')']) ));
        cmd = 'out = [out ';
        cmd = [cmd '{evalin(''base'', ''' outvars{kk} ''')}];'];
        
        eval(cmd);
      end
      
      if ~isempty(out)
        % get file name from user
        [filename, pathname] = uiputfile('*.xml','Pick an XML-file');
        if isequal(filename,0) || isequal(pathname,0)
        else
          fname = fullfile(pathname,filename);
          save(plist('collection', out), fname);
          disp(sprintf('*** Saved plist with %d AOs to %s', numel(out), fname));
        end
      end
    end
    
  catch err
    disp(err.message)
    utils.helper.errorDlg('Unable to save selected objects. Has the pipeline been executed? Are all the objects AOs?', 'Save block outputs error');
  end
  
end

