function sb2sl(cmd,opt)
%SB2SL Starts the GUI for the SystemBuild to Simulink converter.
%
%    SB2SL issued from the command line initializes the SB2SL translator. This
%    user-interface is used to load a SystemBuild model, view the model structure
%    and perform the translation.

% Initial coding by A. S. Bozin, 5-14-97.
% Copyright 1997-2000 The MathWorks, Inc.
% $Revision: 1.14 $ $Date: 2000/06/14 16:07:39 $

   if (nargin == 0)				   % Handle input arguments
      cmd = 'create';
   end
   %
   % Action depends on CMD
   %
   switch (cmd)
   case 'update'
      %
      % Wait bar display update
      %
      shh = get(0,'ShowHiddenHandles');
      set(0,'ShowHiddenHandles','on');
      kids = get(0,'Children');
      set(0,'ShowHiddenHandles',shh);
      hFig = findobj(kids,'flat','Tag','sb2slTag');
      ud = get(hFig,'UserData');
      xdata = get(ud.bar,'XData');
      xdata(2:3) = xdata(2:3)+1;
      set(ud.bar,'XData',xdata);
      drawnow;
   case 'select'
      %
      % Support for the top level superblock selection
      %
      hFig = get(0,'CurrentFigure');
      ud = get(hFig,'UserData');
      prop = get(ud.catalog,{'UserData';'Value'});
      [catalog,node] = deal(prop{:});
      if (size(node,2) ~= 1)
	 msg = {'More than one SuperBlock selected';...
		'Only one block is allowed to be selected as';...
		'a top level SuperBlocks.'};
	 sbboxerror('write',msg);
      else
	 if (catalog(node).type < 0)
	    %
	    % Selected end of superblock list
	    %
	    ud.node = 0;
	    set(hFig,'UserData',ud);
	 else
	    %
	    % Valid superblock selected. Find its kids.
	    %
	    ud.node = node;			   % Selected block
	    set(hFig,'UserData',ud);
	    sbkids = cell(size(catalog));
	    [sbkids{:}] = deal(catalog.sbChild);
	    bkkids = cell(size(catalog));
	    [bkkids{:}] = deal(catalog.bkChild);
	    ind = mgetkids(sbkids,bkkids,node);
	    set(ud.catalog,'Value',cat(1,node,ind));
	 end
      end
   case 'hook'
      %
      % Simulink hook functions
      %
      shh = get(0,'ShowHiddenHandles');
      set(0,'ShowHiddenHandles','on');
      kids = get(0,'Children');
      set(0,'ShowHiddenHandles',shh);
      hFig = findobj(kids,'flat','Tag','sb2slTag');
      ud = get(hFig,'UserData');
      bh = ud.system;
      switch (opt)
      case 'presave'
	 ud.state = bitor(ud.state,8);	   	   % Model saved
	 %
	 % Remove the hooks
	 %
	 set_param(bh,'PreSaveFcn','');
	 set_param(bh,'CloseFcn','');
	 ud.slName = get_param(bh,'Name');
      case 'close'
	 ud.state = bitand(ud.state,19);	   % Clear the flag
	 shh = get(0,'ShowHiddenHandles');	   % Reset bar position
	 set(0,'ShowHiddenHandles','on');
	 delete(get(ud.waitbar,'Children'));
	 set(0,'ShowHiddenHandles',shh);
      otherwise
      end
      set(hFig,'UserData',ud);
   case 'build'
      %
      % Build the Simulink model
      %
      hFig = get(0,'CurrentFigure');
      ud = get(hFig,'UserData');
      if (bitand(ud.state,1))
	 if (nargin == 1)
	    node = ud.node;			   % Get the node of the selected superblock
	 else				   	   % BAT
	    catalog = get(ud.catalog,'UserData');
	    node = catalog(end).sbChild(1);
	 end
	 if (node)
	    %
	    % Check the type of the top level superblock
	    %
	    prop = get([ud.catalog ud.convert],'UserData');
	    [catalog,code] = deal(prop{:});
	    if (bitand(catalog(node).type,1792))
	       %
	       % Procedure type superblock
	       %
	       msg = {'Procedure type super block cannot be used as';
		      'the top level super block. Please select another';
		      'super block and try again.'};
	       sbboxerror('write',msg);
	    elseif ((catalog(node).type == 129) & (catalog(node).signal(1) <= 0))
	       %
	       % Triggered superblock with enable selection of type parent or none
	       %
	       msg = {'Top level triggered superblock with either none';
		      'or parent trigger signal will never execute.';
		      'Please select another superblock and try again.'}
	       sbboxerror('write',msg);
	    else
	       %
	       % Valid superblock selected
	       %
	       path = 'untitled';	   	   % Model name
	       ans = 'Yes';
	       if ((exist(path) == 4) & ~exist(cat(2,path,'.mdl'),'file'))
		  msg = cell(2,1);
		  msg{1} = sprintf('A system named ''%s'' already exists.',path);
		  msg{2} = 'Do you want to remove it from the memory?';
		  ans = sbboxquery('write',msg);
		  if (strcmp(ans,'Yes'))
		     close_system(path,0);
		  end
	       end
	       if (strcmp(ans,'Yes'))
		  num = mgetnblk(catalog,node);	   % Get the number of blocks
		  shh = get(0,'ShowHiddenHandles');
		  set(0,'ShowHiddenHandles','on');
		  delete(get(ud.waitbar,'Children'));
		  set(0,'ShowHiddenHandles',shh);
		  set(ud.waitbar,'XLim',[0 num]);
		  ud.bar = patch('Parent',ud.waitbar,...
				 'HandleVisibility','callback',...
				 'XData',[0 0 0 0 0],...
				 'YData',[0 0 1 1 0],...
				 'EdgeColor',[0 0 0],...
				 'FaceColor',[0.6 0.6 0.6],...
				 'EraseMode','none');
		  set(hFig,'UserData',ud);  	   % Update userdata
		  libsb2sl([],[],[],'load');
		  sbhndlmsgs('write',sprintf('Building %s.',path));
		  pointer = get(hFig,'Pointer');
		  set(hFig,'Pointer','watch');
		  cws = warning;	  	   % Current warning state
		  warning('off');
		  %
		  % Perform the translation
		  %
		  bldopt = ud.bldopt;
		  catalog(node).partition = ud.wsList.names{ud.pind};
		  catalog(node).caller = 0;	   % End of list
		  dsblk = zeros(1,size(catalog,1));
		  bh = new_system(path,'Model');   % Get the block handle
		  ud.state = bitand(ud.state,19);
		  try
		     [stat,post,dsblk(:)] = blksuper(bldopt,bh,path,catalog,code,ud.wsList,node,dsblk);
		     dsbuild(bh,path,catalog,code,node,dsblk);
		     sb2sl('update');
		  catch
		     fprintf('\n%s\n',lasterr);
		     msg = {'Internal error encountered.';...
			    'Please check the Matlab command window for';...
			    'more information.'};
		     sbboxerror('write',msg);
		     stat = 1;
		  end
		  warning(cws);			   % Restore warning state
		  set(hFig,'Pointer',pointer);
		  if (stat)
		     %
		     % Translation failed
		     %
		     open_system(bh);
		     sbhndlmsgs('write','Translation failed.');
		  else
		     if (num == 2)
			blkString = 'block';
		     else
			blkString = 'blocks';
		     end
		     sbhndlmsgs('write',sprintf('Translation completed (%d %s).',num-1,blkString));
		     open_system(bh);
		     ud.state = bitor(ud.state,4); % Model converted
		     if (bldopt{2})
			%
			% Add terminators and ground blocks to unconnected ports
			%
			sbhndlmsgs('write','Adding terminators and ground blocks ...','append');
			pointer = get(hFig,'Pointer');
			set(hFig,'Pointer','watch');
			addterms(bh);
			set(hFig,'Pointer',pointer);
			sbhndlmsgs('write',' Done.','newline');
		     end
		     ud.system = bh;
		     ud.slName = path;
		     set(hFig,'UserData',ud);		   % Update userdata
		     %
		     % Add hooks
		     %
		     set_param(bh,'PreSaveFcn','sb2sl(''hook'',''presave'');');
		     set_param(bh,'CloseFcn','sb2sl(''hook'',''close'');');
		     set_param(bh,'Creator','SB2SL Translator');
		     %
		     % Update the lists of missing blocks and source files
		     %
		     sbhndlunkb('update',bh);
		     sbhndlcomp('update',bh);
		  end
	       end
	    end
	 else
	    %
	    % Nothing to build
	    %
	    msg = {'Nothing selected.';
		   'Please select the top level super block';
		   'and try again.'};
	    sbboxerror('write',msg);
	 end
      else
	 msg = {'Model not loaded.';
		'Please load a model and try again.'};
	 sbboxerror('write',msg);
      end
   case 'missing'
      %
      % Report on missing blocks
      %
      hFig = get(0,'CurrentFigure');
      ud = get(hFig,'UserData');
      kids = find_system('SearchDepth',0);
      indsys = find(strcmp(kids,ud.slName));
      msg = '';
      if (isempty(indsys))
	 msg = {'Converted model has been removed from';...
		'the memory. Convert the model and try again.'};
      elseif (get_param(kids{indsys},'Handle') == ud.system)
	 uBlocks = find_system(ud.system,'Tag','Unknown'); % Got handles
	 sbhndlunkb('create',uBlocks);
      else
	 msg = {'Model handle has been changed.';...
		'Please convert the model and try again.'};
      end
      if (~isempty(msg))
	 ud.state = bitand(ud.state,19);
	 set(hFig,'UserData',ud);
	 sbboxerror('write',msg);
      end
   case 'compile'
      %
      % Report on created source files
      %
      hFig = get(0,'CurrentFigure');
      ud = get(hFig,'UserData');
      kids = find_system('SearchDepth',0);
      indsys = find(strcmp(kids,ud.slName));
      msg = '';
      if (isempty(indsys))
	 msg = {'Converted model has been removed from';...
		'the memory. Convert the model and try again.'};
      elseif (get_param(kids{indsys},'Handle') == ud.system)
	 sBlocks = find_system(ud.system,'Tag','BlockScript'); % Got handles
	 sbhndlcomp('create',sBlocks);
      else
	 msg = {'Model handle has been changed.';...
		'Please convert the model and try again.'};
      end
      if (~isempty(msg))
	 ud.state = bitand(ud.state,19);
	 set(hFig,'UserData',ud);
	 sbboxerror('write',msg);
      end
   case 'load'
      %
      % Select and load the systembuild file
      %
      shh = get(0,'ShowHiddenHandles');
      set(0,'ShowHiddenHandles','on');
      kids = get(0,'Children');
      set(0,'ShowHiddenHandles',shh);
      hFig = findobj(kids,'flat','Tag','sb2slTag');
      ud = get(hFig,'UserData');
      ans = 'Yes';
      if (bitand(ud.state,4))		   	   % Model converted
	 mns = ~bitand(ud.state,8);		   % But not saved
	 dns = bitand(ud.state,2) & ~bitand(ud.state,16);
	 if (mns | dns)
	    msg = cell(2,1);
	    if (mns & dns)
	       msg{1} = 'Converted model and parameters not saved.';
	    elseif (mns)
	       msg{1} = 'Model converted but not saved.';
	    else
	       msg{1} = 'Model parameters not saved.';
	    end
	    msg{2} = 'Do you really want to continue?';
	    ans = sbboxquery('write',msg);
	    if (strcmp(ans,'Yes') & mns)
	       bh = ud.system;
	       set_param(bh,'PreSaveFcn','');
	       set_param(bh,'CloseFcn','');
	    end
	 end
      end
      if (strcmp(ans,'Yes'))
	 msg = '';				   % No errors
	 if (nargin == 1)
	    [fileName,pathName] = uigetfile('*.xmd','SB2SL: SystemBuild File',200,200);
	 else			   	   	   % BAT
	    [pathName,fileName] = deal(opt{:});
	 end
	 if (ischar(fileName))
	    pointer = get(hFig,'Pointer');
	    set(hFig,'Pointer','watch');
	    try
	       %[msg,catalog,code,ws,depth,versions] = readsb(pathName,fileName);
	       [msg,catalog,ws,versions] = readsb(pathName,fileName);
	       depth = catalog(1).depth;
	       code = catalog(1).code;
	       catalog = catalog(1).contents;
	    catch
	       fprintf('\n%s\n',lasterr);
	       msg = {'Internal error encountered.';...
		      'Please check the Matlab command window for';...
		      'more information.'};
	    end
	    set(hFig,'Pointer',pointer);
	    if (isempty(msg))
	       shh = get(0,'ShowHiddenHandles');
	       set(0,'ShowHiddenHandles','on');
	       delete(get(ud.waitbar,'Children'));
	       set(0,'ShowHiddenHandles',shh);
	       ud.depth = depth;
	       ud.versions = versions;
	       sbNum = catalog(end).nBlocks;
	       str = cell(size(catalog));
	       [str{:}] = deal(catalog.name);
	       str{end} = '<<end of superblock list>>';
	       ud.node = 0;		   	   % Nothing selected
	       if (isempty(ws))
		  names = {'main'};
		  pvars{1} = cell(0,0);
		  ind = 1;
		  ud.state = 1;	   	   	   % Only model loaded
	       else
		  names = fieldnames(ws);
		  nsize = size(names,1);
		  pvars = cell(nsize,1);
		  for (k = 1:nsize)
		     if (isempty(getfield(ws,names{k})))
			pvars{k} = cell(0,0);
		     else
			pvars{k} = fieldnames(getfield(ws,names{k}));
		     end
		  end
		  ind = find(strcmp(names,'main'));
		  if (isempty(ind))
		     names{end+1,1} = 'main';
		     pvars{end+1,1} = cell(0,0);
		     ind = size(names,1);
		  end
		  ud.state = 3; 		   % Model and data loaded
	       end
	       ud.sbName = catalog(end).name;
	       ud.workSpace = ws;		   % Partitions
	       [names(:),ind] = sort(names);	   % Sort in alphabetic order
	       pvars(:) = pvars(ind);
	       ud.wsList.names = names;
	       ud.wsList.pvars = pvars;
	       ind = find(strcmp(names,'main'));   % Find the position of the main partition
	       ud.pind = ind;		   	   % Index of the current working partition
	       set(ud.partition,'String',names{ind});
	       set(ud.catalog,'String',str,...
			      'Enable','on',...
			      'Value',sbNum+1,...
			      'ListboxTop',1,...
			      'UserData',catalog);
	       set(hFig,'Name',cat(2,'SB2SL: ',catalog(end).name),...
			'UserData',ud);
	       set(ud.toggle,'Enable','on');
	       set(ud.convert,'UserData',code,'Enable','on');
	       sbhndltree('inimenu');	   	   % Update the tree window if opened
	       sbhndltree('plot');
	       sbhndlpart('update');		   % Update a list of partitions
	    end
	 else
	    sbhndlmsgs('write','Command canceled by the user.');
	 end
	 %
	 % If msg not empty, error occured
	 %
	 if (~isempty(msg))
	    sbboxerror('write',msg);
	 end
      end
   case 'model'
      %
      % Simulink model save function
      %
      shh = get(0,'ShowHiddenHandles');
      set(0,'ShowHiddenHandles','on');
      kids = get(0,'Children');
      set(0,'ShowHiddenHandles',shh);
      hFig = findobj(kids,'flat','Tag','sb2slTag');
      ud = get(hFig,'UserData');
      if (bitand(ud.state,4))
	 switch (opt)
	 case 'asis'
	    fileName = ud.sbName;
	    pathName = pwd;
	 case 'ask'
	    [fileName,pathName] = uiputfile('*.mdl','SB2SL: Simulink File',200,200);
	    ind = mfindstr(fileName,1,'.');
	    if (ind ~= 0)
	       fileName = fileName(1:ind-1);
	    end
	 otherwise
	    fileName = 0;
	 end
	 if (ischar(fileName))
	    newName = fullfile(pathName,fileName);
	    try
	       save_system(ud.slName,newName);
	       ud.slName = fileName;
	       %
	       ud.state = bitor(ud.state,8);	   % Model saved
	       set(hFig,'UserData',ud);
	       sbhndlmsgs('write',sprintf('Model saved as %s.mdl.',fileName));
	    catch
	       fprintf('\n%s\n',lasterr);
	       msg = {'Internal error encountered.';...
		      'Please check the Matlab command window for';...
		      'more information.'};
	       sbboxerror('write',msg);
	    end
	 else
	    sbhndlmsgs('write','Command canceled by the user.');
	 end
      else
	 msg = {'Model not converted.';
		'Please convert the loaded model and try again.'};
	 sbboxerror('write',msg);
      end
   case 'param'
      %
      % Save the model parameters
      %
      shh = get(0,'ShowHiddenHandles');
      set(0,'ShowHiddenHandles','on');
      kids = get(0,'Children');
      set(0,'ShowHiddenHandles',shh);
      hFig = findobj(kids,'flat','Tag','sb2slTag');
      ud = get(hFig,'UserData');
      if (bitand(ud.state,2))
	 switch (opt)
	 case 'asis'
	    fileName = ud.sbName;
	    pathName = pwd;
	 case 'ask'
	    [fileName,pathName] = uiputfile('*.mat','SB2SL: Matlab File',200,200);
	    ind = mfindstr(fileName,1,'.');
	    if (ind ~= 0)
	       fileName = fileName(1:ind-1);
	    end
	 otherwise
	    fileName = 0;
	 end
	 if (ischar(fileName))
	    newName = fullfile(pathName,fileName);
	    try
	       Creator = 'SB2SL Translator';
	       save(newName,'Creator');
	       ws = ud.workSpace;
	       wsName = fieldnames(ws);
	       nws = size(wsName,1);
	       for (cws = 1:nws)
		  partition = wsName{cws};
		  cmd = cat(2,partition,'=getfield(ws,partition);');
		  eval(cmd);
		  save(newName,partition,'-append');
		  clear(partition);
	       end
	       ud.state = bitor(ud.state,16);	   % Data saved
	       set(hFig,'UserData',ud);
	       sbhndlmsgs('write',sprintf('Model parameters saved in %s.mat.',fileName));
	    catch
	       fprintf('\n%s\n',lasterr);
	       msg = {'Internal error encountered.';...
		      'Please check the Matlab command window for';...
		      'more information.'};
	       sbboxerror('write',msg);
	    end
	 else
	    sbhndlmsgs('write','Command canceled by the user.');
	 end
      else
	 msg = {'Nothing to save.';
		'Loaded model does not contain parameters.'};
	 sbboxerror('write',msg);
      end
   case 'help'
      %
      %
      %
      switch (opt)
      case 'sb2sl'
	 htmlfile = fullfile(docroot,'toolbox','sb2sl','sb2sl.html');
	 htmlargs = {htmlfile};
      case 'simulink'
	 htmlfile = fullfile(docroot,'mapfiles','simulink.map');
	 htmlargs = {htmlfile,'collection'};
      otherwise
	 htmlfile = '';
      end
      if (~isempty(htmlfile) & (exist(htmlfile,'file') == 2))
	 helpview(htmlargs{:});
      else
	 sbhndlmsgs('write','Help files not installed. Command aborted.');
      end
   case 'delete'
      %
      % Delete the figures
      %
      closefigures('Abnormal exit.');
   case 'resize'
      %
      %
      %
   case 'close'
      %
      % Close all windows and quit
      %
      hFig = get(0,'CurrentFigure');
      ud = get(hFig,'UserData');
      ans = 'Yes';
      if (bitand(ud.state,4))		   	   % Model converted
	 mns = ~bitand(ud.state,8);		   % But not saved
	 dns = bitand(ud.state,2) & ~bitand(ud.state,16);
	 if (mns | dns)
	    msg = cell(2,1);
	    if (mns & dns)
	       msg{1} = 'Converted model and parameters not saved.';
	    elseif (mns)
	       msg{1} = 'Model converted but not saved.';
	    else
	       msg{1} = 'Model parameters not saved.';
	    end
	    msg{2} = 'Do you really want to quit?';
	    ans = sbboxquery('write',msg);
	    if (strcmp(ans,'Yes') & mns)
	       bh = ud.system;
	       set_param(bh,'PreSaveFcn','');
	       set_param(bh,'CloseFcn','');
	    end
	 end
      end
      if (strcmp(ans,'Yes'))
	 closefigures('Normal exit.');
      end
   case 'create'
      %
      % Create the main window
      %
      shh = get(0,'ShowHiddenHandles');
      set(0,'ShowHiddenHandles','on');
      hFig = findobj(get(0,'Children'),'flat','Tag','sb2slTag');
      set(0,'ShowHiddenHandles',shh);
      if (length(hFig) > 1)			   % There is another figure with the same tag
	 error('sb2sl: sb2sl detected more than one window.');
      elseif (length(hFig) == 1)		   % Main window already created
	 set(0,'CurrentFigure',hFig);
      else
	 %
	 % Look for the resource file
	 %
	 if (exist('sb2slusr.rc','file') == 2)
	    rcfile = 'sb2slusr.rc';
	 else
	    rcfile = 'sb2sldef.rc';
	 end
	 try
	    load(rcfile,'-mat');
	 catch
	    error('sb2sl: could not load the resource file.');
	 end
	 if (strcmp(cookie,'default'))
	    switch (computer)
	    case 'PCWIN'
	       winpref = resource(1);
	    otherwise
	       winpref = resource(2);
	    end
	 end
	 % 
	 % Create a new window
	 %
	 bgc = get(0,'DefaultUIControlBackGroundColor');
	 rect = [100 300 380 280];
	 hFig = figure('Units','pixels',...
		       'Position',rect,...
		       'Color',bgc,...
		       'Resize','off',...
		       'Tag','sb2slTag',...
		       'IntegerHandle','off',...
		       'HandleVisibility','callback',...
		       'NextPlot','replacechildren',...
		       'MenuBar','none',...
		       'Name','SB2SL: untitled',...
		       'NumberTitle','off',...
		       'DeleteFcn','sb2sl(''delete'');',...
		       'ResizeFcn','sb2sl(''resize'');');
	 %
	 % Create menus
	 %
	 topLabls = {'&File';'&Build';'&Windows';'&Help'};
	 subLabls = {{'&Open';'Save';'Save As ...';'&Close'},...
		     {'&Partition';'&Convert';'&Unconverted Blocks';'Compile';'&Report';'Options'},...
		     {'&Tree';'Message';'Preferences'},...
		     {'SB2SL Help';'SIMULINK Help'}};
	 subAccel = {{'O';'';'';'W'},...
		     {'P';'C';'U';'';'R';''},...
		     {'T';'';''},...
		     {'';''}};
	 subCalls = {{'sb2sl(''load'');';'';'';'sb2sl(''close'');'},...
		     {'sbhndlpart(''create'');';'sb2sl(''build'');';'sb2sl(''missing'');';...
		      'sb2sl(''compile'');';'sbhndlgrep(''print'');';'sbhndlopts(''create'');'},...
		     {'sbhndltree(''create'');';'sbhndlmsgs(''create'');';'sbhndlpref(''create'');'},...
		     {'sb2sl(''help'',''sb2sl'');';'sb2sl(''help'',''simulink'');'}};
	 m = size(topLabls,1);
	 topHndls = zeros(m,1);
	 subHndls = cell(1,m);
	 for (k = 1:m)			   % Create top level menus and their kids
	    topMenu = uimenu('Parent',hFig,...
			     'Label',topLabls{k},...
			     'Position',k);
	    topHndls(k) = topMenu;
	    labls = subLabls{k};
	    accel = subAccel{k};
	    calls = subCalls{k};
	    n = size(labls,1);
	    subMenus = zeros(n,1);
	    for (l = 1:n)
	       subMenus(l) = uimenu('Parent',topMenu,...
				    'Label',labls{l},...
				    'Accelerator',accel{l},...
				    'CallBack',calls{l},...
				    'Position',l);
	    end
	    subHndls{k} = subMenus;
	 end
	 labls = {'Model';...
		  'Data'};
	 calls = {'sb2sl(''model'',''asis'');';...
		  'sb2sl(''param'',''asis'');'};
	 topMenu = subHndls{1}(2);
	 m = size(labls,1);
	 subsubHndls = zeros(m,1);
	 for (k = 1:m)
	    subsubHndls(k) = uimenu('Parent',topMenu,...
				    'Label',labls{k},...
				    'CallBack',calls{k},...
				    'Position',k);
	 end
	 calls = {'sb2sl(''model'',''ask'');';...
		  'sb2sl(''param'',''ask'');'};
	 topMenu = subHndls{1}(3);
	 m = size(labls,1);
	 subsubHndls = zeros(m,1);
	 for (k = 1:m)
	    subsubHndls(k) = uimenu('Parent',topMenu,...
				    'Label',labls{k},...
				    'CallBack',calls{k},...
				    'Position',k);
	 end
	 %
	 % Toolbar
	 %
	 hTool = uitoolbar('Parent',hFig,...
			   'HandleVisibility','off',...
			   'Interruptible','on',...
			   'Clipping','on');
	 tptLabls = {'Load a model';...
		     'Save the model';...
		     'Save the parameters';...
		     'Generate report';...
		     'Model tree structure';...
		     'Help on SB2SL'};
	 tptIcons = {'modLoad';...
		     'modSave';...
		     'parSave';...
		     'modDocument';...
		     'modTree';...
		     'modHelp'};
	 tptCalls = {'sb2sl(''load'');';...
		     'sb2sl(''model'',''asis'');';...
		     'sb2sl(''param'',''asis'');';...
		     'sbhndlgrep(''print'');';...
		     'sbhndltree(''create'');';...
		     'sb2sl(''help'',''sb2sl'');'};
	 m = size(tptLabls,1);
	 tptHndls = zeros(m,1);
	 for (k = 1:m)			   % Create the push and toggle tools
	    if (k == 5)
	       hPush = uitoggletool('Parent',hTool,...
				    'TooltipString',tptLabls{k},...
				    'CData',toolicon(tptIcons{k}),...
				    'ClickedCallback',tptCalls{k},...
				    'Separator','off',...
				    'Interruptible','on',...
				    'Clipping','on',...
				    'Enable','on',...
				    'HandleVisibility','callback');
	    else
	       hPush = uipushtool('Parent',hTool,...
				  'TooltipString',tptLabls{k},...
				  'CData',toolicon(tptIcons{k}),...
				  'ClickedCallback',tptCalls{k},...
				  'Separator','off',...
				  'Interruptible','on',...
				  'Clipping','on',...
				  'Enable','on',...
				  'HandleVisibility','callback');
	    end
	    tptHndls(k) = hPush;
	 end
	 %
	 % Catalog list box
	 %
	 rect = [10 246 230 20];
	 hText = uicontrol('Parent',hFig,...
			   'Style','text',...
			   'Units','pixels',...
			   'Position',rect,...
			   'Interruptible','off',...
			   'FontName','Helvetica',...
			   'FontSize',winpref.varSize(2),...
			   'Tag','varNormal',...
			   'HorizontalAlignment','left',...
			   'String','SuperBlock name');
	 set(hText,'Units','normalized');
	 rect = [10 60 260 186];
	 hCatalog = uicontrol('Parent',hFig,...
			      'Style','listbox',...
			      'Units','pixels',...
			      'Position',rect,...
			      'CallBack','sb2sl(''select'');',...
			      'Interruptible','on',...
			      'Enable','inactive',...
			      'UserData',[],...
			      'FontName','Courier',...
			      'FontSize',winpref.fixSize,...
			      'Tag','fixNormal',...
			      'HorizontalAlignment','left',...
			      'ListboxTop',1,...
			      'Min',0,...
			      'Max',2,...
			      'String','<<end of superblock list>>');
	 set(hCatalog,'Units','normalized');
	 %
	 % Current working partition
	 %
	 rect = [10 10 260 30];
	 hFrame = uicontrol('Parent',hFig,...
			    'Style','frame',...
			    'Enable','inactive',...
			    'ForeGround',bgc,...
			    'Position',rect);
	 set(hFrame','Units','normalized');
	 hCapt = uicontrol('Parent',hFig,...
			   'Style','text',...
			   'Units','pixels',...
			   'Position',rect,...
			   'Interruptible','off',...
			   'FontName','Helvetica',...
			   'FontSize',winpref.varSize(2),...
			   'Tag','varNormal',...
			   'HorizontalAlignment','left',...
			   'TooltipString','Click to change the current partition',...
			   'String','Current working partition',...
			   'Clipping','on');
	 captExt = get(hCapt,'Extent');
	 rect(:) = [rect(1)+6 rect(2)+rect(4)-captExt(4)/2 captExt(3)+1 captExt(4)];
	 set(hCapt,'Position',rect,'Units','normalized');
	 rect = [10 10 260 30];
	 hPart = uicontrol('Parent',hFig,...
			   'Style','text',...
			   'Units','pixels',...
			   'Position',rect,...
			   'Interruptible','on',...
			   'FontName','Courier',...
			   'FontSize',winpref.fixSize,...
			   'Tag','fixNormal',...
			   'HorizontalAlignment','left',...
			   'String','Extent',...
			   'Enable','inactive',...
			   'ButtonDownFcn','sbhndlpart(''create'');',...
			   'Clipping','on');
	 partExt = get(hPart,'Extent');
	 rect(:) = [rect(1)+6 rect(2)+(rect(4)-partExt(4))/2 rect(3)-12 partExt(4)];
	 set(hPart,'Position',rect,...
		   'String','',...
		   'Units','normalized');
	 %
	 % Command buttons
	 %
	 rect = [290 226 80 20];
	 hConvert = uicontrol('Parent',hFig,...
			      'Style','pushbutton',...
			      'Units','pixels',...
			      'Position',rect,...
			      'CallBack','sb2sl(''build'');',...
			      'Interruptible','on',...
			      'Enable','inactive',...
			      'FontName','Helvetica',...
			      'FontSize',winpref.varSize(2),...
			      'Tag','varNormal',...
			      'HorizontalAlignment','center',...
			      'TooltipString','Convert the SB model',...
			      'String','Convert');
	 set(hConvert,'Units','normalized');
	 rect = [290 166 80 20];
	 hExit = uicontrol('Parent',hFig,...
			   'Style','pushbutton',...
			   'Units','pixels',...
			   'Position',rect,...
			   'CallBack','sb2sl(''close'');',...
			   'Interruptible','on',...
			   'FontName','Helvetica',...
			   'FontSize',winpref.varSize(2),...
			   'Tag','varNormal',...
			   'HorizontalAlignment','center',...
			   'TooltipString','Quit the SB2SL translator',...
			   'String','Close');
	 set(hExit,'Units','normalized');
	 %
	 % Display wait bar
	 %
	 rect = [290 196 80 20];
	 hWait = axes('Parent',hFig,...
		      'Units','pixels',...
		      'Position',rect,...
		      'HandleVisibility','callback',...
		      'NextPlot','replacechildren',...
		      'Box','on',...
		      'Layer','top',...
		      'Color',[1 1 1],...
		      'DrawMode','normal',...
		      'Clipping','on',...
		      'XDir','normal',...
		      'YDir','normal',...
		      'XLimMode','manual',...
		      'YLimMode','manual',...
		      'XLim',[0 1],...
		      'YLim',[0 1],...
		      'XTick',[],...
		      'YTick',[],...
		      'XGrid','off',...
		      'YGrid','off',...
		      'XColor',[0 0 0],...
		      'YColor',[0 0 0]);
	 set(hWait,'Units','normalized');
	 % 
	 % Icon object creation
	 % 
	 rect = [290 10 80 80];
	 hAxes = axes('Parent',hFig,...
		      'Units','pixels', ...
		      'Position',rect,...
		      'Xgrid','off',...
		      'Ygrid','off',...
		      'XTick',[],...
		      'YTick',[],...
		      'XLimMode','manual',...
		      'YLimMode','manual',...
		      'XLim',[0 1],...
		      'YLim',[0 1],...
		      'Clipping','on',...
		      'Visible','off',...
		      'HandleVisibility','callback',...
		      'NextPlot','add');
	 set(hAxes,'Units','normalized');
	 drawicon(hAxes,'sb2sl');
	 %
	 % Save the useful information to be used later
	 %
	 ud = struct('state',0,...
		     'system',0,...
		     'slName','',...
		     'sbName','',...
		     'versions',0,...
		     'toggle',[subHndls{1}(2:3);subHndls{3}(1);tptHndls(2:5)],...
		     'message',subHndls{3}(2),...
		     'convert',hConvert,...	   % Start translation button
		     'node',0,...
		     'catalog',hCatalog,...	   % Superblock list
		     'depth',0,...
		     'waitbar',hWait,...	   % Translation progress bar
		     'bar',0,...
		     'partition',hPart,...	   % Current partition text handle
		     'pind',0,...
		     'workSpace',[],...	   	   % Partitions
		     'wsList',struct('names',[],...
				     'pvars',[]),...
		     'bldopt',{0},...
		     'repopt',{0},...
		     'conopt',{0},...
		     'winpref',winpref);
	 set(ud.toggle,'Enable','off');
	 ud.bldopt = {1;1;1;0;0;1};
	 ud.repopt = {1;0;0;0;1};
	 ud.conopt = {1;1;1};
	 set(hFig,'UserData',ud);
	 drawnow;				   % Flush the event queue
	 %
	 % Create the message window and load the rest of the modules
	 %
	 sbhndlmsgs('create');
	 sbhndlmsgs('write','Compiling ','append');
	 sbhndltree('compile');
	 sbhndlinfo('compile');
	 sbhndlpart('compile');
	 sbhndlopts('compile');
	 sbhndlpref('compile');
	 sbhndlunkb('compile');
	 sbhndlcomp('compile');
	 sbhndlgrep('compile');
	 sbboxerror('compile');
	 sbboxquery('compile');
	 sbboxerror('create');		   % Create windows
	 sbboxquery('create');
	 sbhndlmsgs('write',' Done.','newline');
	 sbhndlmsgs('write','Ready to start. Try the File menu.');
      end
   otherwise
      error('sb2sl: sb2sl called with incorrect argument.');
   end
   return					   % Last card of SB2SL

function closefigures(msg)
%CLOSEFIGURES Close all figures
%
%

   sbhndlmsgs('write',msg);
   shh = get(0,'ShowHiddenHandles');
   set(0,'ShowHiddenHandles','on');
   kids = get(0,'Children');
   set(0,'ShowHiddenHandles',shh);
   tags = {'boxerrorTag';...
	   'boxqueryTag';...
	   'hndltreeTag';...
	   'hndlinfoTag';...
	   'hndlunkbTag';...
	   'hndlcompTag';...
	   'hndlpartTag';...
	   'hndloptsTag';...
	   'hndlprefTag';...
	   'hndlmsgsTag';...
	   'sb2slTag'};				   % Must be the last one
   m = size(tags,1);
   for (k = 1:m)
      hFig = findobj(kids,'flat','Tag',tags{k});
      if (~isempty(hFig))
	 delete(hFig);
	 ind = find(kids == hFig);	   	   % Remove a handle from the
	 kids(ind) = [];		   	   % list of all handles
      end
   end
   return					   % Last card of CLOSEFIGURES
