% EXPORT the current pipeline as commands to an m-file or to the terminal.
%
% CALL:    wb.export          % export to terminal
%          wb.export('foo.m') % export to file
%
% M Hewitson 17-11-08
%
% $Id: export.m,v 1.3 2010/09/17 14:09:47 ingo Exp $
%
function export(wb, filename)
  
  % get commands
  wb.reset
  cmds = {};
  while awtinvoke(wb.mp, 'countReadyBlocks') > 0
    cmds = [cmds wb.parseReadyBlocks()];
    % move on
    wb.skipForward();
  end
  wb.reset
  
  if nargin == 2
    % open output file
    [path, fcnname, ext] = fileparts(filename);
    fd = fopen(filename, 'w+');
    
    % write header
    plineName = char(awtinvoke(wb.mp, 'getActiveDiagramName'));
    fprintf(fd, '%% Export of %s\n', plineName);
    fprintf(fd, '%% \n');
    fprintf(fd, '%% \n');
    fprintf(fd, '%% %s\n', datestr(now));
    fprintf(fd, '%% \n');
    fprintf(fd, '%% \n');
    
    fprintf(fd, 'function  %s\n', strrep(fcnname, ' ', '_'));
    for kk=1:numel(cmds)
      fprintf(fd, '\t%s\n', cmds{kk});
    end
    fprintf(fd, 'end\n');
    
    fclose(fd);
  else
    for kk=1:numel(cmds)
      fprintf('%03d: %s\n', kk, cmds{kk});
    end
  end
end
