% RUN runs all, or some of the pipelines in the given Workbench file.
%
% CALL:
%
%  id = LTPDAworkbench.run('foo.lwb') % run all
%  id = LTPDAworkbench.run('foo.lwb', 'pipeline1') % run 'pipeline1'
%
%
% Hewitson 20-07-10
%
% $Id: run.m,v 1.6 2011/04/07 14:52:22 hewitson Exp $
%

% TODO
%  LTPDAworkbench.run('foo.lwb', 'plan') % run the plan (if there is one)


function UUID = run(varargin)
  
  % Sort out the filename
  filename = varargin{1};
  [path, name, ext] = fileparts(filename);
  
  if isempty(path)
    filename = fullfile(pwd, filename);
  end
  
  if exist(filename, 'file') == 0
    error(['File not found at ' filename]);
  end
  
  % Parse the XML file
  f = java.io.File(filename);
  parserFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
  parserFactory.setValidating(false);
  db = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
  doc = db.parse(f);
  
  % Get the main document node
  node = doc.getDocumentElement();
  
  % Create a workbench instance
  prefs = getappdata(0, 'LTPDApreferences');
  mp = javaObjectEDT('mpipeline.main.MainWindow', prefdir, prefs);
  UUID = ['LWB_' num2str(round(cputime.*100))];
  javaMethodEDT('setInstanceIdentifier', mp, UUID);
  
  disp(['Processing pipeline: ' filename]);
  disp([' results will be in: ' UUID]);
  
  % Read the pipelines
  pipelines = mp.readPipelines(f, node);
  pipelines = pipelines.toArray();
  
  % read plan
  
  % If execute plan
  
  % else we do the stuff below
  
  pnames = {};
  if nargin == 2
    if strcmpi(varargin{2}, 'plan')
      
      plan = mp.readExecutionPlan(f, node);
      
      error('LTPDA:LTPDAworkbench:Run', 'Plan execution needs to be written!');
    else
      pnames = varargin(2);
    end
  end
  
  if nargin > 2
    pnames = varargin(2:end);
  end
  
  % Run over the pipelines
  for kk=1:numel(pipelines)
    
    
    % Get the pipeline and canvas
    pl = pipelines(kk);
    canvas = pl.getCanvas;
    
    if ~isempty(pnames)
      if ~ismember(char(pl.getTitle), pnames)
        continue;
      end
    end
    
    % Reset all blocks
    canvas.resetAllBlocks
    
    % Execute constant blocks
    LTPDAworkbench.executeConstants(canvas);
    
    % Run until all blocks are executed
    while canvas.getReadyBlocks.size > 0
      
      % Get the blocks ready to run
      blocks = canvas.getReadyBlocks;
      
      % parse the ready blocks
      [cmds, rbs] = LTPDAworkbench.parseBlocks(blocks, pl, genvarname(name));
      
      % Execute commands
      LTPDAworkbench.executeCommands(pl, cmds);
      
      % Move forward
      canvas.stepForwards();
      
      % Clear old variables
      LTPDAworkbench.clearBlockVariables(rbs);
      
    end % End while blocks not executed
  end % End loop over pipelines
  
  % Dispose of the pipeline
  mp.setLtpdaPreferences2([]);
  mp.dispose();
  
  disp(['Completed processing pipeline: ' filename]);
  disp(['               results are in: ' UUID]);
  
  
end

