function varargout=ctlpanel(varargin)
%CTLPANEL Initialization of GUIDE control panel.
%   CTLPANEL is the initialization function for the Guide
%   Control Panel.  CTLPANEL(HandleList) initializes all tools
%   to the figure(s) containing all handles in the HandleList.  
%   
%
%   See also GUIDE, ALIGN, CBEDIT, MENUEDIT, PROPEDIT.

%   Loren Dean
%   Copyright (c) 1984-98 by The MathWorks, Inc.
%   $Revision: 1.84 $ $Date: 1998/11/11 14:58:16 $

ToolFig=findall(0,'Tag','Guide Control Panel');

Data=[];WatchFlag=0;
if ~isempty(ToolFig),
  Data=get(ToolFig,'UserData');
  if ~isempty(Data),  
    Data=get(Data.All.DataHandle,'UserData');      
    if nargin==1 & strcmp(varargin{1},'SelectObject'),    
      [Data,WatchFlag]=setwatch('on',Data,1);
    else,      
      [Data,WatchFlag]=setwatch('on',Data);
    end      
  end    
end  

% Wrap try catch around the callback area
%try,

switch nargin,
  %%%%%%%%%%%%%%%%%%%%%%%%
  %%% Peform an action %%%
  %%%%%%%%%%%%%%%%%%%%%%%%
  case 1,
    if isstr(varargin{1}),
      Action=varargin{1};
      
      switch Action,
        %%%%%%%%%%%%%%%%%
        %%% AddFigure %%%
        %%%%%%%%%%%%%%%%%        
        case 'AddFigure',
          if isempty(Data.All.ControlledFigList),
            NewList=figure('Units','points','Toolbar','none');
          else,            
            NewList=[Data.All.ControlledFigList
                     figure('Units','points','Toolbar','none')];
          end            
          [Data,UpdateType]=LocalChangeFigList(Data,NewList);
          Data=guide('Update',Data);          
          
        %%%%%%%%%%%%%
        %%% Apply %%%
        %%%%%%%%%%%%%        
        case 'Apply',
          set(Data.ToolFig.ApplyHandle,'Enable','off');
          Val=get(Data.ToolFig.ListHandle,'Value');
          UsData=get(Data.ToolFig.ListHandle,'UserData');
          LString=char(get(Data.ToolFig.ListHandle,'String'));
          Loc=find(LString(:,4)=='C');          
          NewList=UsData{1}(Loc);
          [Data,UpdateType]=LocalChangeFigList(Data,NewList);
          Data=guide('Update',Data);
          
        %%%%%%%%%%%%%
        %%% Close %%%
        %%%%%%%%%%%%%        
        case 'Close',
          % This is only called by the ctlpanel closerequestfcn and the 
          % close menus on ctlpanel          
          Data=LocalActivate(Data,Data.All.ControlledFigList);
          Data=guide('HandleUpdate',Data);          
          
          if isempty(Data.All.ControlledFigList),          
            Data=guide('ToolUpdate',Data,ToolFig,'delete');
          end          
          
        %%%%%%%%%%%%%%%%%%
        %%% FigClosing %%%
        %%%%%%%%%%%%%%%%%%        
        case 'FigClosing',
          % Note: using gcf because otherwise if close is used from the
          % command line then gcbf is empty.          
          CurrentFig=gcf;        
          Data=LocalActivate(Data,CurrentFig,1);
          Loc=find(Data.All.ControlledFigList==CurrentFig);
          if isempty(Loc),          
            close(CurrentFig);
          end            
          Data=guide('HandleUpdate',Data);
          % This following line is done again because the HandleList changes   
          Data=guide('HandleUpdate',Data);
          
        %%%%%%%%%%%%%%%%%%%
        %%% FigMenuCall %%%
        %%%%%%%%%%%%%%%%%%%        
        case 'FigMenuCall',
          [CurrentMenu,Fig]=gcbo;
          switch get(parent(CurrentMenu),'Label'),
            case 'File'   ,Data=LocalFigFileMenu(Data);
            case 'Edit'   ,Data=LocalFigEditMenu(Data,ToolFig);
            case 'Options',Data=LocalFigOptionsMenu(Data);
            otherwise, % Add Object
              Data.ToolFig.NewObjectType=get(CurrentMenu,'label');  
              Data=LocalAddObject(Data,Fig,[0 0 0 0],ToolFig);
              Data=guide('HandleUpdate',Data);
            
          end % switch                    
        
        %%%%%%%%%%%%%%%%%
        %%% FigResize %%%
        %%%%%%%%%%%%%%%%%        
        case 'FigResize',
          FigLoc=find(Data.All.ControlInfo.Figures.Handle==gcbf);
          eval(Data.All.ControlInfo.Figures.Property(FigLoc).ResizeFcn,'');
          Data=optnfun('Display Grid',Data,gcbf);
          Data=guide('PropertyUpdate',Data);
          
        %%%%%%%%%%%%%%%%
        %%% KeyPress %%%
        %%%%%%%%%%%%%%%%        
        case 'KeyPress',
          % Check for delete being pressed
          if isequal(abs(get(gcbf,'CurrentCharacter')),127),
            DeleteHandle=Data.All.DeleteHandle( ...
                Data.All.DeleteHandle(:,1)==gcbf,2);
            HandleList=Data.All.HandleList( ...
                ismember(Data.All.HandleList,allchild(gcbf)));
            if ~isempty(HandleList) & ~isempty(DeleteHandle) & ...
                  strcmp(get(DeleteHandle,'Enable'),'on'), 
              Data.All.HandleList=HandleList;
              Data=editfun('Delete',Data);
              Data.All.HandleList=gcbf;
              Data=guide('HandleUpdate',Data);
            end
          end
        
        %%%%%%%%%%%%%%%%%%%%%%
        %%% ListboxFigCtrl %%%
        %%%%%%%%%%%%%%%%%%%%%%        
        case 'ListboxFigCtrl',
          if strcmp(get(ToolFig,'SelectionType'),'open'),            
            UsData=get(Data.ToolFig.ListHandle,'UserData');
            Val=UsData{3};            
            if ~isempty(Val),            
              Handle=UsData{1}(Val);
              NewList=UsData{2};
              
              if ~isempty(NewList),              
                Loc=find(NewList==Handle);
                if ~isempty(Loc),
                  NewList(Loc)=[];                
                else,
                  NewList=[NewList;Handle];         
                end % if ~isempty(Loc)
                
              else,
                 NewList=Handle;
                 
              end % if ~isempty
              
              [Data,UpdateType]=LocalChangeFigList(Data,NewList);
              Data=guide('Update',Data);
            end
            
          else,            
            [Data,UpdateType]=LocalRefreshList(Data);
            Data=LocalToggleState(Data,UpdateType);            
          end

        %%%%%%%%%%%%%%%%
        %%% MenuCall %%%
        %%%%%%%%%%%%%%%%        
        case 'MenuCall',
          CurrentMenu=gcbo;
          switch get(parent(CurrentMenu),'Label'),
            case 'File'   ,Data=LocalFileMenu(Data);
            
            case 'Options',
              [Data,UpdateType]=LocalOptionsMenu(Data);
              if strcmp(UpdateType,'Update'),
                Data=guide('Update',Data);
              end % switch
              
            case 'Help'   ,helpfun(get(gcbo,'Label'),Data);
            
          end % switch                    
        
        %%%%%%%%%%%%%
        %%% RbBox %%%
        %%%%%%%%%%%%%        
        case 'RbBox',        
          [AddFlag,Data]=LocalRbBox(gcbf,Data,ToolFig);          
          if AddFlag,          
            Data=guide('HandleUpdate',Data);
          else,            
            Data=guide('SelectionUpdate',Data,[]);
          end            
          
        %%%%%%%%%%%%%%%%%%%
        %%% RefreshList %%%
        %%%%%%%%%%%%%%%%%%%        
        case 'RefreshList',
          [Data,UpdateType]=LocalRefreshList(Data);
          
        %%%%%%%%%%%%%%
        %%% Resize %%%
        %%%%%%%%%%%%%%
        case 'Resize',
          Data=LocalResize(ToolFig,Data);        
          
        %%%%%%%%%%%%%%%%%%%%%%%
        %%% SelectionUpdate %%%
        %%%%%%%%%%%%%%%%%%%%%%%        
        case 'SelectionUpdate',
          Data=LocalSetMenu(Data,ToolFig);        
          
        %%%%%%%%%%%%%%%%%%%%%%%%
        %%% SelectMoveResize %%%
        %%%%%%%%%%%%%%%%%%%%%%%%        
        case 'SelectMoveResize',
          CurFig=gcbf;        
          switch get(CurFig,'SelectionType'),
            case 'open',
              set(Data.All.DataHandle,'UserData',Data);            
              propedit(Data.All.HandleList);
              Data=get(Data.All.DataHandle,'UserData');
               
            otherwise,              
              [UpdateType,Data]=LocalSelectMoveResize(CurFig,Data);
 
              switch UpdateType,
                case 'Select',    
                  Data=guide('SelectionUpdate',Data,[]);
              
                case 'MoveResize',            
                  Data=guide('SelectionUpdate',Data,-1);
                  Data=guide('PropertyUpdate',Data);
              
                case 'CopyMoveNewFig',              
                  Data=guide('HandleUpdate',Data);
              
              end % switch
              
          end % switch              

        %%%%%%%%%%%%%%%%%%%%
        %%% SelectObject %%%
        %%%%%%%%%%%%%%%%%%%%        
        case 'SelectObject',
          Data=LocalSelectObject(get(gcbo,'Tag'),Data,ToolFig);         
        
        %%%%%%%%%%%%%%%%%%%%%
        %%% ToolsMenuCall %%%
        %%%%%%%%%%%%%%%%%%%%%        
        case 'ToolsMenuCall',
          if ~strcmp(get(gcbo,'Type'),'uimenu'),
            String=get(gcbo,'Tag');
            Handle=findall(ToolFig,'Style','togglebutton','Tag',String);
            set(Handle,'Value',1);
          end
          Data=gnrlfun('ToolsMenuCall',Data);        
          
        %%%%%%%%%%%%%%
        %%% Update %%%
        %%%%%%%%%%%%%%        
        case 'Update',
          if Data.All.GuideFlag,          
            Data=LocalTakeGuideControl(Data);
            Data=gnrlfun('TakeGeneralControl',Data);
          end            
          Data=LocalSelectObject('pointer',Data,ToolFig);         
          Data=LocalSetMenu(Data,ToolFig);          
          [Data,UpdateType]=LocalRefreshList(Data);
          
      end % switch Action
    else,
      Data=LocalInitFig(varargin{1},1,ToolFig);
      
    end % if isstr
  
  case 2,
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%% Activate from command line %%%
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%        
    if strcmp(varargin{1},'Activate'),
      if ~isempty(Data),
        Loc=find(ismember(varargin{2},Data.All.ControlledFigList));
        if ~isempty(Loc),
          Data=LocalActivate(Data,varargin{2}(Loc));
          Data=guide('HandleUpdate',Data);          
        end
        Loc=find(ismember(varargin{2},Data.All.ControlledFigList));
        varargout{1}=varargin{2}(Loc);
      else,
        varargout{1}=[];
      end

    else,
      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      %%% Custom Initialization %%%
      %%%%%%%%%%%%%%%%%%%%%%%%%%%%%
      Data=LocalInitFig(varargin{1:2},ToolFig);
    end
    
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  %%% Initialize to Current Figure %%%
  %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  case 0,
    HandleList=gnrlfun('InitializeHandleList',Data);    
    Data=LocalInitFig(HandleList,0,ToolFig);

  %%%%%%%%%%%%%
  %%% Error %%%
  %%%%%%%%%%%%%
  otherwise,
    Data=setwatch('off',WatchFlag,Data);
    set(Data.All.DataHandle,'UserData',Data);
    error('Wrong number of input arguments for CTLPANEL');

end % switch nargin

%catch, 
% Data=gnrlfun('CatchErrors',Data);  
%end % try catch

if ~isempty(Data),
  Data=setwatch('off',WatchFlag,Data);
  set(Data.All.DataHandle,'UserData',Data);          
end

%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalActivate %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalActivate(Data,FigList,ClosingFig)

Data.All.ControlledFigList= ...
    Data.All.ControlledFigList(ishandle(Data.All.ControlledFigList));
FigList=FigList(ishandle(FigList));
ToolFig=findall(0,'Tag','Guide Control Panel');

for lp=1:length(FigList),  
  CurrentFig=FigList(lp);
  if ~isempty(Data.All.ControlledFigList),  
    Data.All.ControlledFigList(Data.All.ControlledFigList==CurrentFig)=[];  
  end    
  SaveHandle=findall(ToolFig,'Tag','MenuOptionsSave');
  if strcmp(get(SaveHandle,'Checked'),'on'),  
    Name=get(CurrentFig,'FileName');    
    if isempty(Name),
      FigName=get(CurrentFig,'Name');
      if ~isempty(FigName),
        FigName=[' ( ' FigName ' )'];
      end        
      
      if nargin==3,
        % The figure is being closed and must be activated before closing
        Answer=questdlg( ...
			sprintf('Save Figure %s%s before closing?',...
			num2str(CurrentFig),FigName), 'Save Figure');
      else,
        Answer=questdlg( ...
			sprintf('Save Figure %s%s before activating?',...
			num2str(CurrentFig),FigName), 'Save Figure');
      end % if nargin
      
      switch Answer,
        case 'Yes',                 
          Name=LocalSaveAs(CurrentFig);
          if isequal(Name,[0 0])| isempty(Name),
            Data.All.ControlledFigList= ...
              [Data.All.ControlledFigList;CurrentFig]; 
            %return
          end
        case 'Cancel',
          if isempty(Data.All.ControlledFigList),
            Data.All.ControlledFigList=CurrentFig;
          else,            
            Data.All.ControlledFigList=[Data.All.ControlledFigList;CurrentFig];
          end            
          %return
        case 'No',
          Name='';        
      end        
    end
  else,
    Name='';
  end    
  Data=LocalSave(Data,Name,CurrentFig,0);
end  

%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalAddObject %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalAddObject(Data,CurFig,Rectangle,ToolFig)
% Add an object to a working figure

FigFlag=any(Data.All.ControlledFigList==CurFig);
FigUnits=get(CurFig,'Units');
Info={'Parent',CurFig;'Visible','off'};
RectFlag=all(Rectangle(3:4));
DropFlag=isequal(Rectangle,[0 0 0 0]);

if FigFlag,
  switch Data.ToolFig.NewObjectType,
    case 'pushbutton',
      Info=[Info;{'Style','pushbutton'}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');
    
      
    case 'radiobutton',
      Info=[Info;{'Style','radiobutton'}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'checkbox',
      Info=[Info;{'Style','checkbox'}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'edit',
      Info=[Info;{'Style','edit';'BackgroundColor',[1 1 1]}];
           
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'text',
      Info=[Info;{'Style','text'}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'slider',
      Info=[Info;{'Style','slider'}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'frame',
      Info=[Info;{'Style','frame'}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'listbox',
      Info=[Info;{'Style' ,'listbox';'Value'          ,1
                  'String',' '      ;'BackgroundColor',[1 1 1]
                 }];
           
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'popupmenu',
      Info=[Info;{'Style','popupmenu';'String'  ,' '}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');

      
    case 'togglebutton',
      Info=[Info;{'Style','togglebutton'}];
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Info=[Info;{'Units','points'}];      
      Handle=uicontrol(Info(:,1),Info(:,2)');
    
      
    case 'axes',
      if RectFlag,
        Info=[Info;{'Units',FigUnits;'Position',Rectangle}];
      end               
      Handle=axes(Info(:,1),Info(:,2)');
      % force Labels to appear
      get(Handle,{'XLabel','YLabel','ZLabel','Title'});

      
  end % switch  

  if ~RectFlag & ~DropFlag,
    TempUnits=get(Handle,'Units');
    set(Handle,'Units',FigUnits);
    TempPos=get(Handle,'Position');
    TempPos(1:2)=Rectangle(1:2);
    set(Handle,'Position',TempPos,'Units',TempUnits);    
  end % if ~RectFlag    
  
  set(Data.All.HandleList,'Selected','off');
  set(Handle,'Selected','on','Visible','on');

  Data.All.HandleList=Handle;
  Data=LocalSelectObject('pointer',Data,ToolFig);  
  
end % if FigFlag  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalAddToolMenus %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Data,MenuHandles]=LocalAddToolMenus(Data,FigHandles)
% Create New Ctlpanel menus on Controlled Figures
%%% Other Info
ButtonTags=get(Data.ToolFig.ObjHandles,{'Tag'});
MenuFileLabels={'File'                  ;'>Close';
                '>Save Figure'          
                '>Save Figure As...'    ;'>-'
                '>Print...'             
               };
MenuFileTags={'FigMenuFile'          ;'FigMenuFileClose'
              'FigMenuFileSaveFigure';'FigMenuFileSaveFigureAs'
              ''                     ;'FigMenuFilePrint'            
             };
Call(1:14,1)={'ctlpanel FigMenuCall'};
Blank={''};
MenuFileCalls=[Blank;Call(1:3,1);Blank;Call(1,1)];

Temp(1:size(ButtonTags,1)-1,1)={'>>'};
Temp=strcat(Temp,ButtonTags(2:end));

MenuEditLabels=[{'Edit'
                 '>Undo';'>Add Object'}
                   Temp
                {'>Cut^x';'>Copy^c';'>Paste^v';'>Delete';'>Select All^a'}
               ];
                
Temp(1:size(ButtonTags,1)-1,1)={'FigMenuEditAdd'};
Temp=strcat(Temp,ButtonTags(2:end));

MenuEditTags=[{'FigMenuEdit'
                'FigMenuEditUndo';'FigMenuEditAdd'}
                Temp
               {'FigMenuEditCut';'FigMenuEditCopy';'FigMenuEditPaste'
                'FigMenuEditDelete';'FigMenuSelectAll'}
             ];
MenuEditCalls=[Blank;Call(1,1);Blank;Call(1:size(ButtonTags,1)-1,1)
               Call(1:5,1)];

%                   '>Use Inline Callbacks'    ;'>--
%                 'FigMenuOptionsUseInline'  ;''
MenuOptionsLabels={'Options'                  ;'>Activate Figure'         
                   '>--'
                   '>Snap Objects To Grid'
                   '>Display Grid'            ;'>Set Grid Spacing...'
                   '>--'                      ;           
                   '>Bring To Front'          ;'>Send To Back'               
                  };
MenuOptionsTags={'FigMenuOptions'           ;'FigMenuOptionsActivate'   
                 ''
                 'FigMenuOptionsSnapTo'
                 'FigMenuOptionsDisplayGrid';'FigMenuOptionsSetGrid'
                 ''                         ;
                 'FigMenuOptionsBringFront' ;'FigMenuOptionsSendBack'
                };
MenuOptionsCalls=[Blank;Call(1,1);Blank;Call(1:3,1);Blank;Call(1:2,1)];
                 
[MenuToolsLabels,MenuToolsCalls,MenuToolsTags]= ...
    gnrlfun('AddToolsMenu','Controlled Figure');

[MenuHelpLabels,MenuHelpCalls,MenuHelpTags]= ...
    gnrlfun('AddHelpMenu','Controlled Figure');

MenuInfoLabels=[MenuFileLabels   ;MenuEditLabels
                MenuOptionsLabels;MenuToolsLabels;MenuHelpLabels];
MenuInfoTags=[MenuFileTags   ;MenuEditTags
              MenuOptionsTags;MenuToolsTags;MenuHelpTags];
MenuInfoCalls=[MenuFileCalls   ;MenuEditCalls
               MenuOptionsCalls;MenuToolsCalls;MenuHelpCalls];
             
MenuInfoLabels=char(MenuInfoLabels);
MenuInfoTags=char(MenuInfoTags);
MenuInfoCalls=char(MenuInfoCalls);

for FigLp=1:length(FigHandles),
  NewHandles=makemenu(FigHandles(FigLp),MenuInfoLabels, ...
                      MenuInfoCalls,MenuInfoTags);
  MenuHandles{FigLp,1}=NewHandles;
  set(NewHandles       , ...
     'HandleVisibility','off', ...
     'BusyAction'      ,'queue'     ...
     );
  % set the Save Menu off initially
  % For debugging purposes 
    [num2str((1:length(MenuInfoLabels))') MenuInfoLabels MenuInfoCalls];

  % Undo    
  set(NewHandles(7),'Visible','off');    
  
  % Save
  if isempty(get(FigHandles(FigLp),'FileName')),
    set(NewHandles(3),'Enable','off'); 
  end

  % Delete  
% set(NewHandles(22),'Accelerator',char(127));

  Data.All.UndoHandle=[Data.All.UndoHandle
                         FigHandles(FigLp) NewHandles(7)];
  Data.All.CutHandle=[Data.All.CutHandle
                      FigHandles(FigLp) NewHandles(19)];
  Data.All.CopyHandle=[Data.All.CopyHandle
                       FigHandles(FigLp) NewHandles(20)];
  Data.All.PasteHandle=[Data.All.PasteHandle
                        FigHandles(FigLp) NewHandles(21)];
  Data.All.DeleteHandle=[Data.All.DeleteHandle
                         FigHandles(FigLp) NewHandles(22)];

  Data.All.BtFStBHandles=[Data.All.BtFStBHandles
                          FigHandles(FigLp) NewHandles(29:30)'];

  SnapHandle=findobj(NewHandles,'flat','Tag','FigMenuOptionsSetGrid');
  set(SnapHandle,'UserData',{25,25});
end % FigLp

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalChangeFigList %%%%%       
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Data,UpdateType]=LocalChangeFigList(Data,NewList)
UpdateType='none';

OldList=Data.All.ControlledFigList;
if ~isequal(sort(NewList),sort(OldList)),
  RmFigsLoc=find(ismember(OldList,NewList));  
  RmFigs=OldList;RmFigs(RmFigsLoc)=[];      
  Data.All.ControlledFigList=NewList;
  Data.All.GuideFlag=~isempty(Data.All.ControlledFigList);  
  if ~isempty(RmFigs),      
    Data=LocalActivate(Data,RmFigs);        
  end        
  UpdateType='Update';  
  %Data.All.HandleList=NewList;      
  %Data.All.CurrentHandles=NewList;      
  Data.All.CurrentHandles=Data.All.HandleList;  
end      

%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalCreateTag %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
function LocalCreateTag(H)
% Create Tags for new handles
H=findobj(H,'flat','Tag','');
Handles=H;
ObjectTypes={'root'          'Root'
             'figure'        'Fig'
             'uitoolbar'     'UIToolbar'
             'uipushtool'    'UIPushtool'
             'uitoggletool'  'UIToggletool'
             'uicontextmenu' 'UIContextMenu'
             'uimenu'        'UIMenu'
             'uicontrol'     'UIControl'
             'axes'          'Axes'
             'line'          'Line'
             'text'          'Text'
             'surface'       'Surface'             
             'patch'         'Patch'
             'image'         'Image'
             'light'         'Light'
             'rectangle'     'Rectangle'
             };

ObjCt=1;            
NumObj=size(ObjectTypes,1);
TagStr=cell(length(H),1);

while ~isempty(Handles) & ObjCt<=NumObj,
  ObjHandles=findobj(H,'flat','Type',ObjectTypes{ObjCt,1});
  if ~isempty(ObjHandles),  
    HandleLoc=find(ismember(H,ObjHandles));  
    
    switch ObjectTypes{ObjCt,1},
      case 'root',    
        TagStr{HandleLoc,1}='Root';

      case 'figure',        
        NonIntFigs=findobj(H(HandleLoc),'flat','IntegerHandle','off');
        if ~isempty(NonIntFigs),        
          NonIntFigsLoc=find(ismember(H,NonIntFigs));        
          TagStr(NonIntFigsLoc,1)=LocalGetTag(NonIntFigs,'Figni',0);
        end
        
        IntFigs=findobj(H(HandleLoc),'flat','IntegerHandle','on');
        if ~isempty(IntFigs),        
          IntFigsLoc=find(ismember(H,IntFigs));
          for inlp=1:length(IntFigsLoc),          
            TagStr{IntFigsLoc(inlp),1}=['Fig',int2str(H(IntFigsLoc(inlp)))];
          end % for inlp            
        end
        
      case 'uimenu',
        for HLp=1:length(HandleLoc),      
          TempTagStr=get(H(HandleLoc(HLp)),'Label');
          if isempty(TempTagStr),
            TempTagStr='Menu';
          end
        
          FigureList=allchild(0);
          UIContextList=findall(0,'Type','uicontextmenu');
          FigUIList=[FigureList;UIContextList];
          Parent=parent(H(HandleLoc(HLp)));
         
          while ~any(Parent==FigUIList),
            TempStr=get(Parent,'Label');        
            if isempty(TempStr)|strcmp(TempStr,'uimenu'),TempStr='Sub';end
            TempTagStr=[TempStr TempTagStr];
            Parent=parent(Parent);
          end % while
          TagStr(HandleLoc(HLp),1)= ...
            LocalGetTag(H(HandleLoc(HLp)),TempTagStr,Parent);
        end % for HLp          
        
      case 'uicontrol',
        SH=H(HandleLoc);
        %Styles=set(SH(1),'Style');
        Styles={'pushbutton', 'Pushbutton' 
                'radiobutton','Radiobutton'
                'checkbox',   'Checkbox'  
                'edit',       'EditText'  
                'text',       'StaticText'
                'slider',     'Slider'   
                'frame',      'Frame'    
                'listbox',    'Listbox'  
                'togglebutton','Togglebutton'
                'popupmenu',  'PopupMenu'
               };                
        NumS=size(Styles,1);        
        Parent=get(SH,{'Parent'});
        Parent=cat(1,Parent{:});
        UniqueParents=unique(Parent);
        
        for PLp=1:length(UniqueParents),        
          SCt=1;
          SPH=findobj(SH,'flat','Parent',UniqueParents(PLp));
          while SCt<=NumS & ~isempty(SPH),
            NewSPH=findobj(SPH,'flat','Style',Styles{SCt});
            if ~isempty(NewSPH),
              NewSPHLoc=find(ismember(H,NewSPH));
              TagStr(NewSPHLoc,1)= ...
                LocalGetTag(NewSPH,Styles{SCt,2},UniqueParents(PLp));
            end % if ~isempty
            SPH(find(ismember(SPH,NewSPH)))=[];            
            SCt=SCt+1;            
          end % while
        end % for PLp          

      case 'axes',
        SH=H(HandleLoc);
        Parent=get(SH,{'Parent'});
        Parent=cat(1,Parent{:});
        UniqueParents=unique(Parent);
        
        for PLp=1:length(UniqueParents),        
          SPH=findobj(SH,'flat','Parent',UniqueParents(PLp));
          NewSPHLoc=find(ismember(H,SPH));
          TagStr(NewSPHLoc,1)=LocalGetTag(SPH,'Axes',UniqueParents(PLp));
          % This set is done so that axes children will be able to use
          % their parent's tag as part of their tag.        
          set(H(NewSPHLoc),{'Tag'},TagStr(NewSPHLoc,1));
        end % for PLp
        
      otherwise, % axes children
        SH=H(HandleLoc);
        Parent=get(SH,{'Parent'});
        Parent=cat(1,Parent{:});
        UniqueParents=unique(Parent);
        
        for PLp=1:length(UniqueParents),        
          SPH=findobj(SH,'flat','Parent',UniqueParents(PLp));
          NewSPHLoc=find(ismember(H,SPH));
          TempTag=get(UniqueParents(PLp),'Tag');
          if isempty(TempTag),
            TempTag=ObjectTypes{ObjCt,2};
          else,
            TempTag=[TempTag ObjectTypes{ObjCt,2}];            
          end            
          
          TagStr(NewSPHLoc,1)= ...
            LocalGetTag(SPH,TempTag,parent(UniqueParents(PLp)));
        end % for PLp
        
      
    end  % switch        
    Handles(find(ismember(Handles,H(HandleLoc))))=[];
  end % if ~isempty
  
  ObjCt=ObjCt+1;
end % while  

set(H,{'Tag'},TagStr);
  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalFigEditMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalFigEditMenu(Data,ToolFig);
% Take care of actions underneath the Edit menu

switch get(gcbo,'Label'),
  case 'Cut'   ,
    Data.All.HandleList=Data.All.HandleList( ...
        ismember(Data.All.HandleList,allchild(gcbf)));
    Data=editfun('Cut',Data);
    Data.All.HandleList=gcbf;
    Data=guide('HandleUpdate',Data);
    
  case 'Copy'  ,
    Data.All.HandleList=Data.All.HandleList( ...
        ismember(Data.All.HandleList,allchild(gcbf)));
    Data=editfun('Copy',Data);
    Data=LocalSetMenu(Data,ToolFig);
    editfun('SetMenus',Data);

  case 'Paste' ,
    Data=editfun('Paste',Data) ;Data=guide('HandleUpdate',Data);
    
  case 'Delete',
    Data.All.HandleList=Data.All.HandleList( ...
        ismember(Data.All.HandleList,allchild(gcbf)));
    Data=editfun('Delete',Data);
    Data.All.HandleList=gcbf;
    Data=guide('HandleUpdate',Data);
    
  case 'Undo',
    Data=editfun('Undo',Data);Data=guide('HandleUpdate',Data);
    
  case 'Select All',
    Handles=findall(gcbf);
    Handles(Handles==gcbf)=[];
    HandlesLoc=find(ismember(Handles,Data.All.StringInfo(:,1)));
    Data.All.HandleList=Handles(HandlesLoc);
    set(Data.All.StringInfo(:,1),'Selected','off');
    set(Data.All.HandleList,'Selected','on');
    Data=guide('SelectionUpdate',Data,[]);
end % switch  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalFigFileMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalFigFileMenu(Data);
% Take care of actions underneath the File Menu

[CurObj,CurrentFig]=gcbo;

switch get(CurObj,'Label'),
  case 'Close',
    set(Data.All.DataHandle,'UserData',Data);  
    close(CurrentFig)  
    Data=get(Data.All.DataHandle,'UserData');
    
  case 'Save Figure As...',
    Name=LocalSaveAs(CurrentFig);
    if ~isequal(Name,[0 0]),
      Data=LocalSave(Data,Name,CurrentFig,1);
      SaveHandle=findall(CurrentFig,'Tag','FigMenuFileSaveFigure');
      if ~isempty(get(CurrentFig,'FileName')),
        set(SaveHandle,'Enable','on');
      else,
        set(SaveHandle,'Enable','off');
      end
    end      
    
  case 'Save Figure',
    Name=get(CurrentFig,'FileName');
    if isempty(Name),
      Name=LocalSaveAs(CurrentFig);
      if isequal(Name,[0 0]),
        return
      end
    end
    
    Data=LocalSave(Data,Name,CurrentFig,1);
    
  case 'Print...',
    Data=LocalRelinquishGuideControl(Data,CurrentFig);
    Data=gnrlfun('RelinquishGeneralControl',Data);
    Handle=printdlg(CurrentFig);
    if isunix|isvms,
      waitfor(Handle);
    end
    Data=LocalTakeGuideControl(Data);
    Data=gnrlfun('TakeGeneralControl',Data);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalFigOptionsMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalFigOptionsMenu(Data);
% Take care of actions underneath the Options menu

[CurObj,CurFig]=gcbo;
Label=get(CurObj,'Label');

switch Label,
  case {'Bring To Front','Send To Back'},
    Data=optnfun(Label,Data);
    Data=guide('HandleUpdate',Data);
    
  case 'Activate Figure'  ,
    Data=LocalActivate(Data,CurFig);
    Data=guide('Update',Data);
    
  otherwise,
    Data=optnfun(Label,Data);

end % switch    


%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalFileMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalFileMenu(Data);
% Take care of actions underneath the File Menu

switch get(gcbo,'Label'),
  case 'Close Control Panel',
    set(Data.All.DataHandle,'UserData',Data);  
    ctlpanel Close
    Data=gnrlfun('GetUserData','NoFigure');
    
  case 'Close All Tools',
    Figures=allchild(0);    

    ToolFig=findobj(Figures,'flat','Tag','Guide Control Panel');
    PropFig=findobj(Figures,'flat','Tag','Guide Property Editor');
    CBFig=findobj(Figures,'flat','Tag','Guide Callback Editor');
    AlignFig=findobj(Figures,'flat','Tag','Guide Alignment Tool');
    MenuFig=findobj(Figures,'flat','Tag','Guide Menu Editor');

    set(Data.All.DataHandle,'UserData',Data);    
    if ~isempty(PropFig),propedit Close;end
    if ~isempty(CBFig),cbedit Close;end
    if ~isempty(AlignFig),align Close;end
    if ~isempty(MenuFig),menuedit Close;end
    if ~isempty(ToolFig),ctlpanel Close;end
    Data=gnrlfun('GetUserData','NoFigure');
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetControlledFigList %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function CntrldFigs=LocalGetControlledFigList(HandleList)

AvailFig=allchild(0);

CntrldFigs=[];
for ALp=1:length(AvailFig),
  Match=find(ismember(findobj(AvailFig(ALp)),HandleList));  
  if Match,
    if isempty(CntrldFigs),
      CntrldFigs=AvailFig(ALp);
      
    else,      
      if ~any(AvailFig(ALp)==CntrldFigs),   
        CntrldFigs=[CntrldFigs;AvailFig(ALp)];
      end % if ~any
      
    end % if isempty      
    
  end % if Match
end % for ALp

%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetTag %%%%%
%%%%%%%%%%%%%%%%%%%%%%%
function TagStr=LocalGetTag(Handles,TString,Parent)
% Determine Tag
AllTags=get(findall(Parent),{'Tag'});
MatchingTags=find(strncmp(AllTags,TString,length(TString)));
if isempty(MatchingTags),
  Indices=1:length(Handles);  
else,
  SmallTagList=char(AllTags(MatchingTags));
  SmallTagList(:,1:length(TString))=[];
  [Row,Column]=find( (SmallTagList<abs('0') | SmallTagList>abs('9')) & ...
                      SmallTagList~=abs(' '));
  SmallTagList(Row,:)=[];
  Numbers=sort(str2num(SmallTagList));
  PossibleIndices=1:(length(Handles)+length(Numbers));
  Indices=setdiff(PossibleIndices,Numbers);  
    
end  
for lp=1:length(Handles),
  TagStr(lp,1)={[TString int2str(Indices(lp))]};
end  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalOptionsMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Data,UpdateType]=LocalOptionsMenu(Data);
% Take care of actions underneath the Options menu
UpdateType='none';

[CurObj,ToolFig]=gcbo;

FigMenu=findall(ToolFig,'Label','Show Figure List');
ToolMenu=findall(ToolFig,'Label','Show Guide Tools');

FrameHandle=Data.ToolFig.FrameHandle;
ListHandle=Data.ToolFig.ListHandle;
ButtonHandles=Data.ToolFig.ButtonHandles;
ToolHandles=Data.ToolFig.ToolHandles;

switch get(CurObj,'Label'),
  case 'Save Figures when Activating'  ,
    switch get(CurObj,'Checked'),
      case 'off', set(CurObj,'Checked','on');  
      case 'on' , set(CurObj,'Checked','off');  
    end


  case 'Show Guide Tools',
    switch get(ToolMenu,'Checked'),
      case 'off', 
        set(ToolMenu,'Checked','on');  
        set([ToolHandles ButtonHandles(6) FrameHandle(3)],'Visible','on');
        
      case 'on' , 
        set(ToolMenu,'Checked','off');  
        set([ToolHandles ButtonHandles(6) FrameHandle(3)],'Visible','off');
       
    end % switch
    Data=LocalResize(ToolFig,Data,'menu');
    
  case 'Show Figure List',  
  
    switch get(FigMenu,'Checked'),
      case 'off', 
        set(FigMenu,'Checked','on');
        set([ListHandle FrameHandle(2) ButtonHandles(2:5)],'Visible','on');
      case 'on' , 
        set(FigMenu,'Checked','off');  
        set([ListHandle FrameHandle(2) ButtonHandles(2:5)],'Visible','off');
    end % switch
    Data=LocalResize(ToolFig,Data,'menu');
    
end % switch    


%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalPos2Poly %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
function [PolyX,PolyY]=LocalPos2Poly(Pos)
PolyX=[Pos(1);Pos(1)+Pos(3);Pos(1)+Pos(3);Pos(1)       ;Pos(1)];
PolyY=[Pos(2);Pos(2)       ;Pos(2)+Pos(4);Pos(2)+Pos(4);Pos(2)];

%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalRbBox %%%%%
%%%%%%%%%%%%%%%%%%%%%%
function [AddFlag,Data]=LocalRbBox(CurrentFig,Data,ToolFig)
% perform rbbox actions

FigUnits=get(CurrentFig,'Units');
set(CurrentFig,'Units','pixels','Pointer','arrow'); 
SelectionType=get(CurrentFig,'SelectionType');

GridSize={0};
SnapHandle=findall(CurrentFig,'Tag','FigMenuOptionsSnapTo');
if strcmp(get(SnapHandle,'Checked'),'on'),
  SnapHandle=findall(CurrentFig,'Tag','FigMenuOptionsSetGrid');
  GridSize=get(SnapHandle,'UserData');
end


AddFlag=~strcmp(Data.ToolFig.NewObjectType,'pointer');

if AddFlag,  
  InitRect=[get(CurrentFig,'CurrentPoint') 0 0];
  %Rectangle=rbbox(InitRect,InitRect(1:2),[GridSize{:}]);
  Rectangle=rbbox(InitRect,InitRect(1:2),[GridSize{1}]);

  set(CurrentFig,'Pointer','watch');
  Data=LocalAddObject(Data,CurrentFig,Rectangle,ToolFig);
  XYLoc=[];


  
else, % No object is slated to be added
  Rectangle=rbbox;
  set(CurrentFig,'Pointer','watch');


  % Take care of problem of objects being added or removed behind Guide's 
  % back  
  BadHandles=find(~ishandle(Data.All.StringInfo(:,1)));
  if ~isempty(BadHandles),
    Data=guide('Update',Data);
  end    
  
  if sum(Rectangle(3:4))<4,  
    XYLoc=Rectangle(1:2);
  else,
    XYLoc=[];
  end    

  % there are objects available to select  
  if ~isempty(Data.All.StringInfo),
    Loc=[find(Data.All.StringInfo(:,6)==abs('A'))
         find(Data.All.StringInfo(:,6)==abs('C'))]; 
    InLoc=[];
    
    if ~isempty(Loc),    
      Parent=get(Data.All.StringInfo(Loc,1),{'Parent'});
      Parent=cat(1,Parent{:});
      Loc=Loc(Parent==CurrentFig);
    end      
        
    % The CurrentFigure has objects which can be selected    
    if ~isempty(Loc),           
      FigSelectFlag=logical(0);      
      UICAxesUnits=get(Data.All.StringInfo(Loc,1),{'Units'});
      set(Data.All.StringInfo(Loc,1),'Units','pixels');            
      UICAxesPos=get(Data.All.StringInfo(Loc,1),{'Position'});
      set(Data.All.StringInfo(Loc,1),{'Units'},UICAxesUnits);            

      UICAxesPos=cat(1,UICAxesPos{:});
      XPos=[UICAxesPos(:,1)           ; sum(UICAxesPos(:,[1 3])')'
            sum(UICAxesPos(:,[1 3])')'; UICAxesPos(:,1)               
           ];
      YPos=[UICAxesPos(:,2)           ; UICAxesPos(:,2)         
            sum(UICAxesPos(:,[2 4])')'; sum(UICAxesPos(:,[2 4])')'
           ];
      XRect=[Rectangle(1)           ; sum(Rectangle([1 3])')'     
             sum(Rectangle([1 3])')'; Rectangle(1)
            ];         
      YRect=[Rectangle(2)           ; Rectangle(2)
             sum(Rectangle([2 4])')'; sum(Rectangle([2 4])')'
            ];         
      InFlag=inpolygon(XPos,YPos,XRect,YRect);
      InFlag=reshape(InFlag,size(XPos,1)/4,4);
      InLoc=find(any(InFlag'));
         
      % The RbBox did not enclose anything      
      if isempty(InLoc),
        FigSelectFlag=logical(1);
      end        
    % The current figure has no objects which can be selected      
    else,      
      FigSelectFlag=logical(1);      
      
    end % if ~isempty

    switch SelectionType,
      case 'normal',
        if FigSelectFlag,
          Data.All.HandleList= ...
            Data.All.StringInfo(find(Data.All.StringInfo(:,1)==CurrentFig),1);
  
        else,      
          Data.All.HandleList=Data.All.StringInfo(Loc(InLoc),1);
        end % if FigSelectFlag

      case 'extend',
        Data.All.HandleList= ...
          findobj(Data.All.StringInfo(Loc,1),'flat','Selected','on');
        Data.All.HandleList=[Data.All.HandleList 
                             Data.All.StringInfo(Loc(InLoc),1)
                            ];
      case 'alt',
        Data.All.HandleList= ...
            findobj(Data.All.StringInfo(Loc,1),'flat','Selected','on');
        Data.All.HandleList=[Data.All.HandleList 
                             Data.All.StringInfo(Loc(InLoc),1)
                            ];
      case 'open',
        set(Data.All.DataHandle,'UserData',Data);      
        propedit(Data.All.HandleList);
        Data=get(Data.All.DataHandle,'UserData');      
        
    end % switch
    
    set(Data.All.StringInfo(:,1),'Selected','off');
    set(Data.All.HandleList,'Selected','on');

  % Nothing is available to select so nothing should be selected
  % This is hopefully redundant  
  else,
    Data.All.HandleList=[];
    
  end % if ~isempty
  
end % if ~strcmp  
Data.All.ControlInfo.Figures.Misc( ...
  Data.All.ControlInfo.Figures.Handle==CurrentFig).XYLoc=XYLoc;

set(CurrentFig,'Units',FigUnits);

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalRefreshList %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Data,UpdateType]=LocalRefreshList(Data)
% Refresh the list of figures
CurrentList=allchild(0);
CurrentList=sort(reshape(CurrentList,prod(size(CurrentList)),1));
CurrentList(find(ismember(CurrentList,Data.All.Figs.Handles)))=[];
CurrentList=gnrlfun('RemoveSpecialHandles',CurrentList);

OldList=get(Data.ToolFig.ListHandle,'UserData');
UpdateType='none';

% Refresh the list
if ~isequal(CurrentList,OldList{1})| ...
   ~isequal(sort(Data.All.ControlledFigList),sort(OldList{2})),
   UpdateType='refresh';
   
   NumFig=length(CurrentList);
   
   if NumFig~=0,   
     String1(1:NumFig,1)={'       Active  '};   
     Loc=find(ismember(CurrentList,Data.All.ControlledFigList));
     String1(Loc,1)={'   Controlled  '};
     
     for FigLp=NumFig:-1:1,
       String2{FigLp,1}=gnrlfun('GetFigString',CurrentList(FigLp),14);
     end       
     AllStrings=strcat(String1,String2);
     
   else,
     AllStrings={' '};
     
   end
   
   set(Data.ToolFig.ListHandle, ...
      'String'  ,AllStrings, ...
      'Value'   ,[]        , ...      
      'UserData',{CurrentList Data.All.ControlledFigList []});   
  
   set(Data.ToolFig.ApplyHandle,'Enable','off','UserData',AllStrings);
   
else,
   Value=get(Data.ToolFig.ListHandle,'Value');
   UsData=get(Data.ToolFig.ListHandle,'UserData');
   if ~isempty(Value) & ...
      ~isempty([UsData{1}(:);UsData{2}(:);UsData{3}(:)]),
     UsData{3}=Value;     
     set(Data.ToolFig.ListHandle,'UserData',UsData);   
   end     
end  


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalRelinquishGuideControl %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalRelinquishGuideControl(Data,FigureList)
% Replace everything that was done when taking control

if ~isempty(Data.All.ControlInfo.Figures.Handle),
  ControlledFigs=Data.All.ControlInfo.Figures.Handle;

  if ~isempty(ControlledFigs),
    FigLoc=find(ismember(ControlledFigs,FigureList));

    FigureHandles=Data.All.ControlInfo.Figures.Handle(FigLoc);
    AxisHandles=[Data.All.ControlInfo.Figures.Misc(FigLoc).AxisHandle]';

    TempInfo=Data.All.ControlInfo.Figures.Property(FigLoc);
    set(FigureHandles,fieldnames(TempInfo),struct2cell(TempInfo)');
    
    for FLp=1:length(FigureHandles),
      Children=allchild(AxisHandles(FLp));
      % There should be 4 labels and nothing else
      if length(Children==4),
        delete(AxisHandles(FLp))
      end % if ~isempty    

      HandleList=findall(FigureHandles(FLp));

      HandleList=gnrlfun('RemoveToolbarHandles',HandleList);
      
      if ~isempty(Data.All.HandleList),      
        HandleLoc=find(ismember(Data.All.HandleList,HandleList));
        set(Data.All.HandleList(HandleLoc),'Selected','off');
        Data.All.HandleList(HandleLoc)=[];
      end        
      
      if ~isempty(Data.All.ControlInfo.AllObjects.Handle),  
        ControlledHandles=Data.All.ControlInfo.AllObjects.Handle;  
      
        HandleLoc=find(ismember(ControlledHandles,HandleList));
        
        if ~isempty(HandleLoc),      
          TempInfo=Data.All.ControlInfo.AllObjects.Property(HandleLoc);
          set(ControlledHandles(HandleLoc), ...
              fieldnames(TempInfo),struct2cell(TempInfo)');
        end % if ~isempty
              
        Data.All.ControlInfo.AllObjects.Handle(HandleLoc)=[];   
        Data.All.ControlInfo.AllObjects.Property(HandleLoc)=[];   

        % Need to check to see if handles were accidentally removed behind
        % guide's back.  if so, clean things up.
        if ~isempty(Data.All.ControlInfo.AllObjects.Handle),        
          BadHandleLoc = ...
              ~ishandle(Data.All.ControlInfo.AllObjects.Handle);
          if any(BadHandleLoc), 
            Data.All.ControlInfo.AllObjects.Handle(BadHandleLoc)=[];   
            Data.All.ControlInfo.AllObjects.Property(BadHandleLoc)=[];   
          end % if any 
        end % if          
        
      end % if ~isempty
  
      if ~isempty(Data.All.ControlInfo.UIControls.Handle),  
        UIControlledHandles=Data.All.ControlInfo.UIControls.Handle;  
        HandleLoc=find(ismember(UIControlledHandles,HandleList));
      
        if ~isempty(HandleLoc),      
          TempInfo=Data.All.ControlInfo.UIControls.Property(HandleLoc);
          set(UIControlledHandles(HandleLoc), ...
              fieldnames(TempInfo),struct2cell(TempInfo)' ...
             );
        end % if any
      
        Data.All.ControlInfo.UIControls.Handle(HandleLoc)=[];   
        Data.All.ControlInfo.UIControls.Property(HandleLoc)=[];   
      end % if ~isempty   
 
      if ~isempty(Data.All.ControlInfo.UIMenus.Handle),  
        UIMenuControlledHandles=Data.All.ControlInfo.UIMenus.Handle;
        HandleLoc=find(ismember(UIMenuControlledHandles,HandleList));
        
        if any(HandleLoc),      
          TempInfo=Data.All.ControlInfo.UIMenus.Property(HandleLoc);
          set(UIMenuControlledHandles(HandleLoc), ...
              fieldnames(TempInfo),struct2cell(TempInfo)');
        end % if any
      
        Data.All.ControlInfo.UIMenus.Handle(HandleLoc)=[];   
        Data.All.ControlInfo.UIMenus.Property(HandleLoc)=[];   
      end % if ~isempty   
 
      GMenuHandles = ... 
          Data.All.ControlInfo.Figures.Misc(FigLoc(FLp)).MenuHandles;
      ParHandles=get(GMenuHandles,{'Parent'});      
      TopLevelLoc=cat(1,ParHandles{:})== ...
                       Data.All.ControlInfo.Figures.Handle(FigLoc(FLp));
           
      delete(GMenuHandles(TopLevelLoc));

    end % for FLp

    Data.All.ControlInfo.Figures.Handle(FigLoc)=[];
    Data.All.ControlInfo.Figures.Property(FigLoc)=[];
    Data.All.ControlInfo.Figures.Misc(FigLoc)=[];

  end % if ~isempty

  Loc=ishandle(Data.All.CutHandle(:,2));  
  Data.All.CutHandle=Data.All.CutHandle(Loc,:);  
  Data.All.CopyHandle=Data.All.CopyHandle(Loc,:);  
  Data.All.PasteHandle=Data.All.PasteHandle(Loc,:);  
  Data.All.DeleteHandle=Data.All.DeleteHandle(Loc,:);
  Data.All.UndoHandle=Data.All.UndoHandle(Loc,:);
  Loc=ishandle(Data.All.BtFStBHandles(:,2));  
  Data.All.BtFStBHandles=Data.All.BtFStBHandles(Loc,:);

end  
Data.All.GuideFlag=~isempty(Data.All.ControlledFigList);
% Make sure something is selected
if isempty(Data.All.HandleList),
  if isempty(Data.All.ControlledFigList),
    % set it to root    
    Data.All.HandleList=0; 
  else,
    % Set it to a controlled figure    
    Data.All.HandleList=Data.All.ControlledFigList(1); 
  end    
end    

%%%%%%%%%%%%%%%%%%% 
%%% LocalResize %%%
%%%%%%%%%%%%%%%%%%%        
function Data=LocalResize(ToolFig,Data,varargin);

FigMenu=findall(ToolFig,'Label','Show Figure List');
ToolMenu=findall(ToolFig,'Label','Show Guide Tools');

set([ToolFig Data.ToolFig.ListHandle Data.ToolFig.ButtonHandles ...
     Data.ToolFig.FrameHandle Data.ToolFig.StatusHandle ...
     Data.ToolFig.ObjHandles Data.ToolFig.ToolHandles], ...
    'Units','points');

FigPos=get(ToolFig,'Position');
TempFigPos=FigPos;

FramePos=get(Data.ToolFig.FrameHandle,{'Position'});
FramePos=cat(1,FramePos{:});

ListPos=get(Data.ToolFig.ListHandle,'Position');
StatusPos=get(Data.ToolFig.StatusHandle,'Position');

ObjPos=get(Data.ToolFig.ObjHandles,{'Position'});
ObjPos=cat(1,ObjPos{:});

ToolPos=get(Data.ToolFig.ToolHandles,{'Position'});
ToolPos=cat(1,ToolPos{:});

ButtonPos=get(Data.ToolFig.ButtonHandles,{'Position'});
ButtonPos=cat(1,ButtonPos{:});

HOffset=max(1,StatusPos(1));
VOffset=max(1,StatusPos(2));

ButtonWidth=min(Data.ToolFig.OrigPos(2,1),(FigPos(3)-5*HOffset)/2);
ButtonHeight=Data.ToolFig.OrigPos(2,2);

StatusPos(1,4)=ButtonHeight;

ObjPos(1,3:4)=Data.ToolFig.OrigPos(4,:);
ObjPos(2:end,3)=Data.ToolFig.OrigPos(1,1);
ObjPos(2:end,4)=Data.ToolFig.OrigPos(1,2);

ObjPos(2:6,2)=sum(StatusPos(1,[2 4]))+VOffset;
ObjPos(7:11,2)=sum(ObjPos(2,[2 4]))+VOffset;
ObjPos([6 11],1)=FigPos(3)-HOffset-ObjPos(6,3);
ObjPos(2:6,:)=align(ObjPos(2:6,:),'Distribute','Bottom');
ObjPos(7:11,:)=align(ObjPos(7:11,:),'Distribute','Bottom');

ObjPos(1,2)=ObjPos(2,2)+(sum(ObjPos(7,[2 4]))-ObjPos(2,2)-ObjPos(1,4))/2;

ButtonPos(:,4)=ButtonHeight;
ButtonPos(1,2)=sum(ObjPos(end,[2 4]));
FramePos(1,4)=sum(ButtonPos(1,[2 4]))+VOffset;
FramePos(2,2)=sum(FramePos(1,[2 4]));

ButtonPos(2:4,3)=ButtonWidth;
ButtonPos(3,1)=FramePos(2,1)+(FramePos(2,3)-ButtonPos(3,3))/2;
ButtonPos(4,1)=sum(FramePos(2,[1 3]))-HOffset-ButtonPos(4,3);

ToolPos(:,3)=Data.ToolFig.OrigPos(5,1);
ToolPos(:,4)=Data.ToolFig.OrigPos(5,2);

if strcmp(get(ToolMenu,'Checked'),'on'),
  FramePos(2,4)=FigPos(4)-FramePos(2,2)-ButtonPos(6,4)-ToolPos(1,4)-VOffset;
else,
  FramePos(2,4)=FigPos(4)-FramePos(2,2);
end

ButtonPos(2:4,2)=FramePos(2,2)+VOffset;
ListPos(1,2)=sum(ButtonPos(2,[2 4]))+VOffset;

% check to see if not menu call
if isempty(varargin),
  ListPos(1,4)=max(50,FramePos(2,4)-2*ButtonHeight-3*VOffset);
end % if isempty  

ButtonPos(5,2)=sum(ListPos(1,[2 4]));
FramePos(2,4)=sum(ButtonPos(5,[2 4]))+VOffset-FramePos(2,2);


ToolPos(4,1)=FigPos(3)-HOffset-ToolPos(4,3);
ToolPos=align(ToolPos,'Distribute','Bottom');

if strcmp(get(FigMenu,'Checked'),'on'),
  FramePos(3,2)=sum(FramePos(2,[2 4]));
else,  
  FramePos(3,2)=sum(FramePos(1,[2 4]));
end % if  

ToolPos(:,2)=FramePos(3,2)+VOffset;  
ButtonPos(6,2)=sum(ToolPos(1,[2 4]));
FramePos(3,4)=sum(ButtonPos(6,[2 4]))+VOffset-FramePos(3,2);

% Check to see if this was called by the options menu
if ~isempty(varargin),
  if strcmp(get(ToolMenu,'Checked'),'on'),
    FigPos(4)=sum(FramePos(3,[2 4]));
  else,
    if strcmp(get(FigMenu,'Checked'),'on'),
      FigPos(4)=sum(FramePos(2,[2 4]));
    else,
      FigPos(4)=sum(FramePos(1,[2 4]));
    end    
  end % if ToolMenu  

  FigPos(2)=FigPos(2)+Data.ToolFig.OldFigPos(4)-FigPos(4);
  ResizeFunc=get(ToolFig,'ResizeFcn');
  set(ToolFig,'ResizeFcn','','Position',FigPos)
  drawnow
  set(ToolFig,'ResizeFcn',ResizeFunc)
%else,
%  FigPos(2)=FigPos(2)+TempFigPos(4)-FigPos(4);  
end % if ~isempty  

ToolPos=num2cell(ToolPos,2);
ObjPos=num2cell(ObjPos,2);
ButtonPos=num2cell(ButtonPos,2);
FramePos=num2cell(FramePos,2);

set(Data.ToolFig.FrameHandle,{'Position'},FramePos);
set(Data.ToolFig.ListHandle,'Position',ListPos);
set(Data.ToolFig.StatusHandle,'Position',StatusPos);
set(Data.ToolFig.ButtonHandles,{'Position'},ButtonPos);
set(Data.ToolFig.ToolHandles,{'Position'},ToolPos);
set(Data.ToolFig.ObjHandles,{'Position'},ObjPos);

Data.ToolFig.OldFigPos=FigPos;

set([Data.ToolFig.ListHandle Data.ToolFig.ButtonHandles ...
     Data.ToolFig.FrameHandle Data.ToolFig.StatusHandle ...
     Data.ToolFig.ToolHandles Data.ToolFig.ObjHandles], ...
    'Units','normalized');

%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalSave %%%%%
%%%%%%%%%%%%%%%%%%%%%
function Data=LocalSave(Data,Name,CurrentFig,SaveFlag)

Data=LocalRelinquishGuideControl(Data,CurrentFig);
Data=gnrlfun('RelinquishGeneralControl',Data);

try,
  if ~isequal(Name,[0 0])& ~isempty(Name),
    print(['-f' num2str(CurrentFig,16)],'-dmfile',Name);
  end
catch,
  answer=questdlg( ...
      ['Figure could not be saved as ' Name '. Would you like to' ...
          ' save it under another name?'], ...
      'Problem Saving Figure','Yes','No','Yes');
  if strcmp(answer,'Yes'),
    Name=LocalSaveAs(CurrentFig);
    Data=LocalSave(Data,Name,CurrentFig,SaveFlag);
  end      
end

if SaveFlag,
  Data=LocalTakeGuideControl(Data);
  Data=gnrlfun('TakeGeneralControl',Data);
end  
    
%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalSaveAs %%%%%
%%%%%%%%%%%%%%%%%%%%%%%
function Name=LocalSaveAs(CurrentFig)
Name=get(CurrentFig,'FileName');
if isempty(Name),Name='*.m';end
[FileName,PathName]=uiputfile(Name, ...
    ['Save Figure ',num2str(CurrentFig), ' ' get(CurrentFig,'Name')]);

if ~isequal(FileName,0),
  if ~strcmp(FileName(end-1:end),'.m'),
    FileName=[FileName '.m'];
  end
end

Name=[PathName FileName];    
if ~isequal(FileName,0),
  set(CurrentFig,'FileName',Name);
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalSelectMoveResize %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [UpdateType,Data]=LocalSelectMoveResize(CurrentFig,Data)
% perform selectmoveresize actions

% Unfortunately, all of this has to be done before SMR occurs because of
% one case below

SquareHandlesLoc=[find(Data.All.StringInfo(:,6)==abs('A'));
                  find(Data.All.StringInfo(:,6)==abs('C'))];
SquareHandles=findobj(Data.All.StringInfo(SquareHandlesLoc,1),'flat', ...
                     'Parent',CurrentFig);

TempSquareUnitsPos=get(SquareHandles,{'Units','Position'});

GridSize={0};
SnapHandle=findall(CurrentFig,'Tag','FigMenuOptionsSnapTo');
if strcmp(get(SnapHandle,'Checked'),'on'),
  SnapHandle=findall(CurrentFig,'Tag','FigMenuOptionsSetGrid');
  GridSize=get(SnapHandle,'UserData');
end

%SMR=selectmoveresize(GridSize{:});
SMR=selectmoveresize(GridSize{1});

% Clear out the last point clicked on
Data.All.ControlInfo.Figures.Misc( ...
    Data.All.ControlInfo.Figures.Handle==CurrentFig).XYLoc=[];

Data.All.HandleList=findall(Data.All.ControlledFigList,'Selected','on');
Data.All.HandleList(strcmp(get(Data.All.HandleList,'Type'),'figure'))=[];
AxisHandles=[Data.All.ControlInfo.Figures.Misc.AxisHandle]';
Loc=find(ismember(Data.All.HandleList,AxisHandles));
if ~isempty(Loc),
  set(Data.All.HandleList(Loc),'Selected','off');
  Parent=get(Data.All.HandleList(Loc),{'Parent'});
  Parent=[Parent{:}];
  Data.All.HandleList(Loc)=[];
  if isempty(Data.All.HandleList),
    Data.All.HandleList=Parent;
  end
end

switch SMR.Type,
  case 'Select',
    UpdateType='Select';

  case 'Resize',    
    UpdateType='MoveResize';

  % Copy or Move    
  otherwise,

    % The following 2 lines need to be done to get a consistent set of
    % unit values.  For instance, if units are normalized, then the 
    % figures position is relative to the root and the currentpoint
    % is relative to the figure.      
    OrigFigUnits=get(CurrentFig,'Units');
    set(CurrentFig,'Units','pixels');    
    % Check to see if the object(s) has been dragged out of the fig
    OrigFigPos=get(CurrentFig,'Position');
    NewPointerLoc=get(CurrentFig,'CurrentPoint')+OrigFigPos(1:2);
    [X,Y]=LocalPos2Poly(OrigFigPos);

    if ~inpolygon(NewPointerLoc(1),NewPointerLoc(2),X,Y),
      InsideFlag=0;
      OtherFigs=Data.All.ControlledFigList;
      OtherFigs(OtherFigs==CurrentFig)=[];    
      
      if ~isempty(OtherFigs),    
        TempFigUnits=get(OtherFigs,{'Units'});
        set(OtherFigs,'Units',get(CurrentFig,'Units'));

        FigPos=get(OtherFigs,{'Position'});
        FigPos=cat(1,FigPos{:});

        NumFigs=length(OtherFigs);
        FLp=1;        
        while FLp<=NumFigs & ~InsideFlag,
          [X,Y]=LocalPos2Poly(FigPos(FLp,:));
          if inpolygon(NewPointerLoc(1),NewPointerLoc(2),X,Y),
            InsideFlag=1;            
          end            
          FLp=FLp+1;          
        end % while FLp
        set(OtherFigs,{'Units'},TempFigUnits);
      end % if ~isempty(OtherFigs)        
      
      
      % The drag ended inside another controlled figure so a copy occurred
      if InsideFlag,
        set(SquareHandles,{'Units'},TempSquareUnitsPos(:,1));
        TSUPLoc=find(ismember(SquareHandles,SMR.Handles(:,1)));
        set(SMR.Handles(:,2),{'Units'},TempSquareUnitsPos(TSUPLoc,1));
       
        UpdateType='Copy';
        MoveCopy=UpdateType;
       
      % The drag ended out of the figure and not inside another figure       
      else,      
        switch SMR.Type,
          case 'Move',
            % Cancel the move
            set(SquareHandles,{'Units','Position'},TempSquareUnitsPos);

          case 'Copy',
            delete(SMR.Handles(:,2));

        end % switch
        Data.All.HandleList=SMR.Handles(:,1);            

        UpdateType='Select';
        MoveCopy=UpdateType;

      end % if InsideFlag
      
      set(Data.All.HandleList,'Selected','on');    

    % The drag ended inside the figure      
    else,
      MoveCopy=SMR.Type;  
        
    end % if ~inpolygon

    switch MoveCopy,
      case 'Move',    
        UpdateType='MoveResize';
    
      case 'Copy',
        NewParent=get(SMR.Handles(:,2),{'Parent'});
        NewParent=[NewParent{:}];    
        Temp=find(ismember(Data.All.ControlledFigList,NewParent));

        UpdateType='CopyMoveNewFig';
        set(Data.All.HandleList,'Selected','off');    
        Data.All.HandleList=SMR.Handles(:,2);
        set(Data.All.HandleList,'Selected','on');    
        editfun('DealWithCopiedObjects', ...
                SMR.Handles(:,2),SMR.Handles(:,1),Data);  
    end % switch MoveCopy
    set(CurrentFig,'Units',OrigFigUnits);    
    
end  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalSelectObject %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalSelectObject(OString,Data,ToolFig)
% Select an object type to be added to a working figure

OldHandle=findall(ToolFig, ...
                 'Tag'  ,Data.ToolFig.NewObjectType, ...
                 'Style','togglebutton');
Handle=findall(ToolFig,'Tag',OString,'Style','togglebutton');

% Handle 1st time occurrence
if ~isempty(Handle),
  set(OldHandle,'Value',0);
  if isequal(OldHandle,Handle) & strcmp(Data.ToolFig.State,'in'),  
    Handle=findall(ToolFig,'Tag','pointer','Style','togglebutton');
    OString='pointer';  
    Data.ToolFig.State='out';    
  else,
    Data.ToolFig.State='in';    
  end    
  Data.ToolFig.NewObjectType=OString;
  
  set(Handle,'Value',1);

  switch OString,
    case 'pointer',
      statmsg(ToolFig,'');
      if ~isempty(Data.All.ControlInfo.AllObjects.Handle)    
        set(Data.All.ControlInfo.AllObjects.Handle, ...
           'ButtonDownFcn','ctlpanel SelectMoveResize');    
      end       
      Data.ToolFig.NewObjectType='pointer';      
    otherwise,
      statmsg(ToolFig, ...
        ['Please select a region in a controlled figure to place the ', ...
          OString '.']);
      if ~isempty(Data.All.ControlInfo.AllObjects.Handle)    
        set(Data.All.ControlInfo.AllObjects.Handle, ...
           'ButtonDownFcn','ctlpanel RbBox');    
      end     
  end % switch  
end % if ~isempty 

%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalSetMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalSetMenu(Data,ToolFig)
% Set the uimenus appropriately based on selection
if isempty(Data.All.ControlledFigList)|~Data.All.GuideFlag,
  if ~strcmp(Data.ToolFig.State,'off'),
    btnctrl('off',Data.ToolFig.ObjHandles);
    Data.ToolFig.State='off';
  end
else,
  if ~strcmp(Data.ToolFig.State,'on'),
    btnctrl('on',Data.ToolFig.ObjHandles);
    Data.ToolFig.State='on';
  end

end % if isempty

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalTakeGuideControl %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalTakeGuideControl(Data)
% Take control of a figure(s)

Data.All.GuideFlag=logical(1);

          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%% Check all handles are valid %%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%% Make sure all controlled handles are valid
if ~isempty(Data.All.ControlInfo.AllObjects.Handle),
  ControlledHandles=Data.All.ControlInfo.AllObjects.Handle;
  BadHandleLoc=~ishandle(ControlledHandles);
  if any(BadHandleLoc),
    Data.All.ControlInfo.AllObjects.Handle(BadHandleLoc)=[];
    Data.All.ControlInfo.AllObjects.Property(BadHandleLoc)=[];
    if ~isempty(Data.All.ControlInfo.AllObjects.Handle),
      ControlledHandles=Data.All.ControlInfo.AllObjects.Handle;
    else,
      ControlledHandles=[];      
    end      
  end  
else,  
  ControlledHandles=[];
end % if ~isempty

%%% Make Sure that all Currently Controlled Figures are valid
if ~isempty(Data.All.ControlInfo.Figures.Handle),
  ControlledFigures=Data.All.ControlInfo.Figures.Handle;
  BadHandleLoc=~ishandle(ControlledFigures);
  if any(BadHandleLoc),
    Data.All.ControlInfo.Figures.Handle(BadHandleLoc)=[];
    Data.All.ControlInfo.Figures.Property(BadHandleLoc)=[];
  end  
end % if ~isempty  

%%% Make sure that all Current UIControlled Handles are valid
if ~isempty(Data.All.ControlInfo.UIControls.Handle),
  UIControlledHandles=Data.All.ControlInfo.UIControls.Handle;
  BadHandleLoc=~ishandle(UIControlledHandles);
  if any(BadHandleLoc),
    Data.All.ControlInfo.UIControls.Handle(BadHandleLoc)=[];
    Data.All.ControlInfo.UIControls.Property(BadHandleLoc)=[];
  end
end % if ~isempty  

%%% Make sure that all Current UIMenu Controlled Handles are valid
if ~isempty(Data.All.ControlInfo.UIMenus.Handle),
  UIMenuControlledHandles=Data.All.ControlInfo.UIMenus.Handle;
  BadHandleLoc=~ishandle(UIMenuControlledHandles);
  if any(BadHandleLoc),
    Data.All.ControlInfo.UIMenus.Handle(BadHandleLoc)=[];
    Data.All.ControlInfo.UIMenus.Property(BadHandleLoc)=[];
  end
end % if ~isempty  


          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%% Determine New Handles %%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%% The following line may be redundant because it is also on setwatch       
Data.All.ControlledFigList(~ishandle(Data.All.ControlledFigList))=[];

if ~isempty(Data.All.ControlledFigList),
  
  AxesHandles=findall(Data.All.ControlledFigList,'Type','axes');
  get(AxesHandles,{'XLabel','YLabel','ZLabel','Title'});
  
  AllHandles=findall(Data.All.ControlledFigList);  
  
  AllHandles=gnrlfun('RemoveToolbarHandles',AllHandles);
      

  NewFigs=findobj(AllHandles,'flat','Type','figure');
  OldFigsLoc=find(ismember(NewFigs,ControlledHandles));
  NewFigs(OldFigsLoc)=[];
  % Take care of Plot Editor Tools
  plotedit(NewFigs,'off');
  
  tbAutoLoc=strcmp(get(NewFigs,{'Toolbar'}),'auto');
  set(NewFigs(tbAutoLoc),'Toolbar','none');
  %for lp=1:length(tbAutoLoc),
  %  if ~isempty(findall(NewFigs(tbAutoLoc(lp)),'Tag','ScribeSelectToolBtn'))
  %    set(NewFigs(tbAutoLoc(lp)), 'Toolbar', 'figure');
  %  else,
  %    set(NewFigs(tbAutoLoc(lp)),'toolbar','none');
  %  end
  %end
    
  
  if ~isempty(Data.All.ControlInfo.Figures.Handle),
    GuideMenus=[Data.All.ControlInfo.Figures.Misc.MenuHandles];
    GuideMenus=GuideMenus(:);  
    Temp=find(ismember(AllHandles,GuideMenus));
    MenuHandleLoc=1:length(AllHandles);MenuHandleLoc(Temp)=[]; 
    AllHandles=AllHandles(MenuHandleLoc);
  end    
  Temp=find(ismember(AllHandles,ControlledHandles));
  NewHandleLoc=1:length(AllHandles);NewHandleLoc(Temp)=[]; 
  NewHandles=AllHandles(NewHandleLoc);

  
  if ~isempty(NewFigs),
    Property=Data.All.ControlInfo.Figures.Properties;
    MiscProperty=Data.All.ControlInfo.Figures.MiscProperties;
    
    TempProperty= cell2struct(get(NewFigs,Property),Property,2);
    TempMisc    = cell2struct(cell(length(NewFigs),length(MiscProperty)), ...
                         MiscProperty,2);
    TempData.Handle=NewFigs(:);
    TempData.Property=TempProperty;
    TempData.Misc=TempMisc;

    if ~feature('figuretools'),
      for FigLp=1:length(NewFigs),  
        Menus=flipud(findobj(allchild(NewFigs(FigLp)),'flat','Type','uimenu'));
        set(Menus,'Parent',Data.All.HiddenFigure(1));
        set(NewFigs(FigLp),'MenuBar','none');% This delete's the original menus
        set(Menus,'Parent',NewFigs(FigLp));
      end      
    end
    [Data,NewMenuHandles]=LocalAddToolMenus(Data,NewFigs);
    [TempData.Misc(:).MenuHandles]=deal(NewMenuHandles{:});
    
    Data.All.ControlInfo.Figures.Handle = ...
        [Data.All.ControlInfo.Figures.Handle;TempData.Handle];
    Data.All.ControlInfo.Figures.Property = ...
        [Data.All.ControlInfo.Figures.Property;TempData.Property];
    Data.All.ControlInfo.Figures.Misc = ...
        [Data.All.ControlInfo.Figures.Misc;TempData.Misc];
    
  end % if ~isempty NewFigs

          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%% Add Axis to Figure if necessary %%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  Figures=Data.All.ControlledFigList;          
  for FLp=1:length(Figures),
  
    %%% Determine if an axis that covers the entire figure with no labels
    %%or ticklabels
    AxisHandle=findall(Figures(FLp), ...
                      'Type'        ,'axes'               , ...
                      'Units'       ,'normalized'         , ...
                      'Tag'         ,'GuideSelectionAxes' , ...
                      'XTickLabel'  ,''                   , ...
                      'YTickLabel'  ,''                   , ...
                      'ZTickLabel'  ,''                     ...
                      );           
                
    if ~isempty(AxisHandle),
      AxisHandle=AxisHandle(1);    
      Loc=find(NewHandles==AxisHandle);
      LabHandle=get(AxisHandle,{'XLabel','YLabel','ZLabel','Title'});
      LabHandle=[LabHandle{:}]';   
      LabLoc=find(ismember(NewHandles,LabHandle));
      NewHandles([Loc;LabLoc])=[];    
      
      Loc=find(AllHandles==AxisHandle);
      LabLoc=find(ismember(AllHandles,LabHandle));
      AllHandles([Loc;LabLoc])=[];    
      
      set(AxisHandle        , ...
         'Tag'              ,'GuideSelectionAxes', ...
         'Color'            ,'none'              , ...        
         'XColor'           ,[1 1 1]             , ...
         'YColor'           ,[1 1 1]             , ...
         'Box'              ,'on'                , ...
         'HitTest'          ,'off'               , ...
         'Interruptible'    ,'off'               , ...         
         'BusyAction'       ,'queue'             , ...
         'HandleVisibility' ,'off'                 ...
         );    
    
    else,
      AxisHandle=axes('Parent'          ,Figures(FLp)        , ...
                      'Units'           ,'normalized'        , ...
                      'Position'        ,[0 0 1 1]           , ...
                      'Color'           ,'none'              , ...
                      'XColor'          ,[1 1 1]             , ...
                      'YColor'          ,[1 1 1]             , ...
                      'Tag'             ,'GuideSelectionAxes', ...
                      'HandleVisibility','off'               , ...
                      'HitTest'         ,'off'               , ...
                      'Box'             ,'on'                , ...
                      'BusyAction'      ,'queue'             , ...
                      'Interruptible'   ,'off'               , ...         
                      'XGrid'           ,'on'                , ...
                      'YGrid'           ,'on'                , ...
                      'ZGrid'           ,'off'               , ...
                      'GridLineStyle'   ,':'                 , ...
                      'XTickLabel'      ,''                  , ...
                      'YTickLabel'      ,''                  , ...
                      'ZTickLabel'      ,''                    ...
                      );

    end % if ~isempty

    Loc=find(Data.All.ControlInfo.Figures.Handle==Figures(FLp));
    Data.All.ControlInfo.Figures.Misc(Loc).AxisHandle=AxisHandle;
    
    Children=allchild(Figures(FLp));
    Loc=find(Children==AxisHandle);
    if Loc~=length(Children),    
      Children=[Children(1:Loc-1);Children((Loc+1:end)');Children(Loc)];
      set(Figures(FLp),'Children',Children);
    end      
    
    % Set the grid spacing correctly on the figure
    Data=optnfun('Display Grid',Data,Figures(FLp));
    
  end % for FLp

          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          %%%%% Take Control of Properties %%%%%
          %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
          
  %%%%% Figures          
  if ~isempty(NewFigs),
    % Note that MenuBar is set above    
    PtrData=setptr('add');PtrData{2}='watch';
    
    % The following drawnow forces all pending draw events to occur so
    % that the ResizeFcn does not get called.
    drawnow;
    
    set(NewFigs, ...
       'CloseRequestFcn'      ,'ctlpanel FigClosing', ...
       'ResizeFcn'            ,'ctlpanel FigResize' , ...
       PtrData{:}                                   , ...       
       'WindowButtonDownFcn'  ,''                   , ...
       'KeyPressFcn'          ,'ctlpanel KeyPress'  , ...
       'WindowButtonMotionFcn',''                   , ...
       'WindowButtonUpFcn'    ,''                   , ...
       'WindowStyle'          ,'normal'               ...       
       );
  end % if ~isempty

  % Check for reparenting of objects  
  if ~isempty(Data.All.ControlInfo.AllObjects.Handle),  
    ExistingLoc=find(ismember(ControlledHandles,AllHandles));
    Data.All.ControlInfo.AllObjects.Handle= ...
      Data.All.ControlInfo.AllObjects.Handle(ExistingLoc);
    Data.All.ControlInfo.AllObjects.Property= ...
      Data.All.ControlInfo.AllObjects.Property(ExistingLoc);
  end  
  %%%%% AllHandles  
  if ~isempty(NewHandles),
    Property=Data.All.ControlInfo.AllObjects.Properties;
    TempProperty=cell2struct(get(NewHandles,Property),Property,2);
    
    NewHandleInfo.Handle= NewHandles(:);
    NewHandleInfo.Property=TempProperty;
 
    ExistingLoc=find(ismember(AllHandles,ControlledHandles));
    NewLoc=find(ismember(AllHandles,NewHandles));  
    AllObjInfo.Properties=Property;
    
    AllObjInfo.Handle(ExistingLoc,1) = ...
        Data.All.ControlInfo.AllObjects.Handle;
    AllObjInfo.Property(ExistingLoc,1) = ...
        Data.All.ControlInfo.AllObjects.Property;
    AllObjInfo.Handle(NewLoc,1)=NewHandleInfo.Handle;    
    AllObjInfo.Property(NewLoc,1)=NewHandleInfo.Property;    
    
    Data.All.ControlInfo.AllObjects=AllObjInfo;
    set(NewHandles, ...
        'ButtonDownFcn'   ,'ctlpanel SelectMoveResize', ...
        'HandleVisibility','on'                       , ...         
        'BusyAction'      ,'queue'                    , ...        
        'UIContextMenu'   ,[]                         , ...
        'Interruptible'   ,'off'                        ...        
       );  


    %%%%% UIControls
    NewUIHandles=findobj(NewHandles,'flat','Type','uicontrol');
    
    if ~isempty(NewUIHandles),
      Property=Data.All.ControlInfo.UIControls.Properties;
      TempProperty=cell2struct(get(NewUIHandles,Property),Property,2);
    
      NewHandleInfo.Handle= NewUIHandles(:);
      NewHandleInfo.Property= TempProperty;
      
      Data.All.ControlInfo.UIControls.Handle= ...
        [Data.All.ControlInfo.UIControls.Handle;NewHandleInfo.Handle];       
      Data.All.ControlInfo.UIControls.Property= ...
          [Data.All.ControlInfo.UIControls.Property;NewHandleInfo.Property];

     set(NewUIHandles,'Enable','inactive');  
    end % ~isempty      
    


    %%%%% UIMenus
    NewUIMenuHandles=findobj(NewHandles,'flat','Type','uimenu');
    
    if ~isempty(NewUIMenuHandles),
      Property=Data.All.ControlInfo.UIMenus.Properties;
      TempProperty =cell2struct(get(NewUIMenuHandles,Property),Property,2);
    
      NewHandleInfo.Handle =NewUIMenuHandles(:);
      NewHandleInfo.Property=TempProperty;
 
      Data.All.ControlInfo.UIMenus.Handle= ...
        [Data.All.ControlInfo.UIMenus.Handle;NewHandleInfo.Handle];       
      Data.All.ControlInfo.UIMenus.Property= ...
        [Data.All.ControlInfo.UIMenus.Property;NewHandleInfo.Property];       
      set(NewUIMenuHandles,'Visible','off');  
    end % ~isempty
    
  
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    %%%%% Check all tags and prompt for correction %%%%%
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    LocalCreateTag(NewHandles);
    
  end % if ~isempty(NewHandles)

end % if ~isempty(Data.All.ControlledFigList)  

Data=objbrwser('CreateInfo',Data);
% Set enabling on all menus correctly
editfun('SetMenus',Data)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalToggleState %%%%%       
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalToggleState(Data,UpdateType)

if UpdateType(1)=='n', % none    
  Value=get(Data.ToolFig.ListHandle,'Value');
  if ~isempty(Value),    
    ListTop=get(Data.ToolFig.ListHandle,'ListboxTop');    
    LString=char(get(Data.ToolFig.ListHandle,'String'));
    if prod(size(LString))~=1,
      for vlp=1:length(Value),
        switch LString(Value(vlp),3:4),
          case '>C',Str='       Active';
          case '> ',Str='   Controlled';
          case '  ',Str='-->Controlled';
          case ' C',Str='-->    Active';
        end % switch
         
        LString(Value(vlp),1:13)=Str;
  
      end % for vlp
      LString=cellstr(LString);      
  
      set(Data.ToolFig.ListHandle, ...
         'String'    ,LString, ...
         'ListboxTop',ListTop  ...
         );
      if ~isequal(get(Data.ToolFig.ApplyHandle,'UserData'),LString),
        set(Data.ToolFig.ApplyHandle,'Enable','on');
        statmsg(get(Data.ToolFig.StatusHandle,'Parent'), ...
            'Press Apply to Activate or Control figures');

      else,      
        set(Data.ToolFig.ApplyHandle,'Enable','off');
        statmsg(get(Data.ToolFig.StatusHandle,'Parent'),'')
      end      
    end % if prod
  end % if ~isempty
end % if UpdateType
  

%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalInitFig %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalInitFig(HandleList,CustomFlag,ToolFig)
% Initialize the Control Panel

[HandleFlag,Data]=gnrlfun('InitializeHandles',ToolFig,HandleList);
if ~isempty(Data.All.HandleList),
  % Root is no longer a valid handle  
  Data.All.HandleList(Data.All.HandleList==0)=[];
end

if strcmp(studio,'on'),
  jguide;
  delete(Data.All.HiddenFigure);
  return
end % if strcmp java


if HandleFlag==2,
  if isempty(Data.All.ControlledFigList),
    FigList=Data.All.HandleList;
  else,
    FigList=[Data.All.ControlledFigList;Data.All.HandleList];
  end
  Data.All.ControlledFigList=LocalGetControlledFigList(FigList);
  if ~isempty(Data.All.ControlledFigList),  
    Data.All.GuideFlag=logical(1);  
  else,
    Data.All.GuideFlag=logical(0);    
  end    
  Data=guide('Update',Data);
  return
end

%if ~isstruct(CustomList),
%  CustomFlag=CustomList;
%  CustomList=[];  
%  if CustomFlag,
%    CustomList=getpref('Guide','CustomList');
%  end
%else,
%  CustomFlag=1;  
%end % if ~isstruct
CustomFlag=0;
CustomList={};

% Set up colors
White=[1 1 1];Black=[0 0 0];
FigColor=get(0,'defaultuicontrolbackgroundcolor');

%%% Set up positions
Offset=3;
ToolDir=which('ctlpanel');
ToolDir=ToolDir(1:end-10);
load(fullfile(ToolDir,'private','toolbtn'));

ObjHeight=1;
ObjWidth=1;
for lp=2:length(uicData)-2,
  CurSize=size(uicData(lp).data);
  ObjHeight=max(ObjHeight,CurSize(1)+4);
  ObjWidth=max(ObjWidth,CurSize(2)+6);
end

ListHeight=50;
ButtonHeight=20;
ButtonWidth=70;

FramePos=zeros(3,4);

StatusPos=[Offset Offset 0 ButtonHeight];
  
ObjPos=zeros(11,4);
Ct=1;
PtrHeight=size(uicData(1).data,2);
PtrWidth= size(uicData(1).data,1);

ObjPos(1,:)=[Offset                                                ...
                sum(StatusPos(1,[2 4]))+Offset+ObjHeight-PtrHeight/2 ...
                PtrHeight PtrWidth];
for VertLp=1:-1:0,
  for HorizLp=0:4,
    Ct=Ct+1;
    ObjPos(Ct,:)=[sum(ObjPos(1,[1 3]))+Offset+HorizLp*ObjWidth+1 ...
                     sum(StatusPos(1,[2 4]))+Offset+VertLp*ObjHeight+1 ...
                     ObjWidth                                          ...
                     ObjHeight                                         ...
                    ];
  end % VertLp
end % HorizLp
ButtonPos=zeros(6,4);
ButtonPos(1,:)=[ObjPos(1,1) sum(ObjPos(2,[2 4])) 0 ButtonHeight];
FramePos(1,:)=[0 0 sum(ObjPos(6,[1 3]))+Offset sum(ButtonPos(1,[2 4]))+Offset];
FramePos(2,:)=[0 sum(FramePos(1,[2 4])) FramePos(1,3) 0];
  
ButtonPos(1,3)=FramePos(2,3)-2*Offset;

ButtonPos(2,:)=[FramePos(2,1:2)+Offset ButtonWidth ButtonHeight];
ButtonPos(3,:)=ButtonPos(2,:);
ButtonPos(3,1)=FramePos(2,1)+(FramePos(2,3)-ButtonPos(3,3))/2;
ButtonPos(4,:)=ButtonPos(2,:);
ButtonPos(4,1)=sum(FramePos(2,[1 3]))-ButtonPos(4,3)-Offset;

ListPos=[FramePos(2,1)+Offset sum(ButtonPos(2,[2 4]))+Offset ...
         ButtonPos(1,3) ListHeight];

ButtonPos(5,:)=[ListPos(1) sum(ListPos(1,[2 4])) ListPos(3) ButtonHeight];

FramePos(2,4)=sum(ButtonPos(5,[2 4]))+Offset-FramePos(2,2);

ToolHeight=1;
ToolWidth=1;
for tlp=1:length(toolData),
  CurSize=size(toolData(tlp).data);
  ToolHeight=max(ToolHeight,CurSize(1)+4);
  ToolWidth=max(ToolWidth,CurSize(2)+6);
end

FramePos(3,:)=[0 sum(FramePos(2,[2 4])) FramePos(2,3) 0];

ToolPos=FramePos(3,:)+[Offset Offset 0 0];
ToolPos=ToolPos(ones(4,1),:);
ToolPos(:,3)=ToolWidth;
ToolPos(:,4)=ToolHeight;

FigWidth=sum(FramePos(end,[1 3]));

Gap=(FigWidth-2*Offset-4*ToolWidth)/3;
ToolPos(:,1)=ToolPos(:,1)+(0:3)'*(Gap+ToolWidth);

ButtonPos(6,:)=ButtonPos(1,:);
ButtonPos(6,2)=sum(ToolPos(1,[2 4]));
FramePos(3,4)=sum(ButtonPos(6,[2 4]))-FramePos(3,2)+Offset;
FigHeight=sum(FramePos(3,[2 4]));

[FigHoriz,FigVert]=gnrlfun('GetFigPos',FigHeight,Data);
FigPos=[FigHoriz FigVert FigWidth FigHeight]; % -30 for menu
  
StatusPos(3)=FigWidth-2*Offset;

%%% Other Info
AllInfo.HandleVisibility='off';
AllInfo.Interruptible='off';
AllInfo.BusyAction='queue';

FontSize=get(0,'FactoryUIControlFontSize');

StatusInfo=AllInfo;
StatusInfo.Style='text';
StatusInfo.BackGroundColor=White;
StatusInfo.Units='points';
StatusInfo.FontSize=FontSize;
StatusInfo.FontUnits='points';
StatusInfo.ForeGroundColor=Black;
StatusInfo.HorizontalAlignment='center';

StatusTag='Status'; 
StatusString=''; 
StatusTip='';

FrameInfo=AllInfo;
FrameInfo.Style='frame';
FrameInfo.BackgroundColor=FigColor;
FrameInfo.Units='points';

FrameTags={'New Object Palette Frame';'Figure List Frame';'Guide Tools Frame'};
FrameTips={'';'';''};

ListInfo=StatusInfo;
ListInfo.Style='listbox';
ListInfo.HorizontalAlignment='left';
ListInfo.Max=2;
ListInfo.Value=[];
ListInfo.FontName='FixedWidth';
ListInfo.FontSize=FontSize;
ListInfo.UserData={[],[]};
     
ListTag='Figure List';
ListTip='';
ListString=' ';
ListCall='ctlpanel ListboxFigCtrl';

ButtonInfo=StatusInfo;
ButtonInfo.BackgroundColor=FigColor;
ButtonStyle={'text'
             'pushbutton';'pushbutton';'pushbutton';'text'
             'text'
            };
ButtonAlign={'left'
             'center';'center';'center';'left'
             'left'
            };             
ButtonTags={'New Object Palette'
            'Refresh List';'Add Figure';'Apply';'Figure List'
            'Guide Tools'            
           };
ButtonTips={'';'';'';'';'';''};

ButtonStrings=ButtonTags;
ButtonCall={''
            'ctlpanel RefreshList';'ctlpanel AddFigure';'ctlpanel Apply';''
            ''};

ToolTags={'Property Editor';'Callback Editor';'Alignment Tool';'Menu Editor'};
ToolTips={'';'';'';''};

ToolCall(1:4,1)={'ctlpanel ToolsMenuCall'};

ToolInfo=ButtonInfo;
ToolInfo.Style='togglebutton';

ObjTags={'pointer'
         'axes'      ;'text';'listbox'  ;'checkbox'   ;'slider'
         'pushbutton';'edit';'popupmenu';'radiobutton';'frame'
        };
ObjTips={'Select mode'
         'Add axes'
         'Add text uicontrol'
         'Add listbox uicontrol'
         'Add checkbox uicontrol'
         'Add slider uicontrol'
         'Add pushbutton uicontrol'
         'Add edit uicontrol'
         'Add popupmenu uicontrol'
         'Add radiobutton uicontrol'
         'Add frame uicontrol'
         };

ObjCall(1:11,1)={'ctlpanel SelectObject'};

ObjInfo=ToolInfo;

MenuInfo=AllInfo;

%%% Create the menu options
Call(1:14,1)={'ctlpanel MenuCall'};
Blank={''};
MenuFileLabels={'File'               
               '>Close Control Panel';'>Close All Tools'
               };
MenuFileTags={'MenuFile'
              'MenuFileCloseTool';'MenuFileCloseAllTools'
             };
             
MenuFileCalls=[Blank;Call(1:2,1)];

MenuOptionsLabels={'Options';
                   '>Save Figures when Activating';'>--'
                   '>Show Guide Tools'            ;'>Show Figure List'
                  };
MenuOptionsTags={'MenuOptions'       
                 'MenuOptionsSave'           ;''
                 'MenuOptionsShowToolPalette';'MenuOptionsFigList'};
MenuOptionsCalls=[Blank;Call(1:4,1)];
                 
MenuCustomLabels={'Customization' 
                  '>Save Customization'   ;'>Save Customization As...'
                  '>Load Customization...';
                  '>Use Customized Lists' ;'>Customize...'
                 };
MenuCustomTags={'MenuCustom'
                'MenuCustomSave';'MenuCustomSaveAs'
                'MenuCustomLoad';
                'MenuCustomUse' ;'MenuCustomEdit'   
               };
MenuCustomCalls(1:6,1)=Blank;

[MenuToolsLabels,MenuToolsCalls,MenuToolsTags]= ...
    gnrlfun('AddToolsMenu','Control Panel');

[MenuHelpLabels,MenuHelpCalls,MenuHelpTags]= ...
    gnrlfun('AddHelpMenu','Control Panel');

MenuInfoLabels=[MenuFileLabels ;MenuOptionsLabels;
                MenuToolsLabels;MenuHelpLabels
               ];
MenuInfoTags=[MenuFileTags ;MenuOptionsTags;
              MenuToolsTags;MenuHelpTags
             ];
MenuInfoCalls=[MenuFileCalls ;MenuOptionsCalls;
               MenuToolsCalls;MenuHelpCalls
              ];
             
MenuInfoLabels=char(MenuInfoLabels);
MenuInfoTags=char(MenuInfoTags);
MenuInfoCalls=char(MenuInfoCalls);

NumClr=size(Map,1);
Index=ismember(Map,FigColor,'rows');
if ~any(Index),
  NumClr=NumClr+1;
  Map=[Map;FigColor];
  Index=size(Map,1);  
end  
DisableMap=linspace(.6,.4,NumClr)';
DisableMap=DisableMap(:,ones(1,3));
DisableMap(Index,:)=FigColor;

Map=[Map;DisableMap];

% set up tool
drawnow
ToolFig=figure(AllInfo             , ...
              'Color'              ,FigColor                  , ...
              'CreateFcn'          ,''                        , ...
              'IntegerHandle'      ,'off'                     , ...
              'CloseRequestFcn'    ,'ctlpanel Close'          , ...
              'MenuBar'            ,'none'                    , ...
              'Name'               ,'Guide Control Panel'     , ...
              'Tag'                ,'Guide Control Panel'     , ...
              'NextPlot'           ,'add'                     , ...
              'NumberTitle'        ,'off'                     , ...
              'Units'              ,'points'                  , ...
              'Position'           ,FigPos                    , ...
              'Resize'             ,'on'                      , ...
              'UserData'           ,[]                        , ...
              'Colormap'           ,Map                       , ...
              'Visible'            ,'off'                       ...
              );

MenuHandles=makemenu(ToolFig,MenuInfoLabels,MenuInfoCalls,MenuInfoTags);
set(MenuHandles,MenuInfo);
set(MenuHandles(5:7),'Checked','on'); % Menu Options
set(MenuHandles(9),'Enable','off'); % Control Panel Tool

for FLp=1:size(FrameTags,1),
  FrameHandle(FLp)=uicontrol(FrameInfo       , ...
                        'Parent'        ,ToolFig        , ...
                        'Position'      ,FramePos(FLp,:), ...
                        'Tag'           ,FrameTags{FLp}   ...
                        );
end % FLP
                     
for BtnLp=1:size(ObjTags,1),  
  ImageData=gnrlfun('Ind2RGB',uicData(BtnLp).data,Map);
  ObjHandles(BtnLp)=uicontrol(ObjInfo  , ...
                             'Parent'  ,ToolFig          , ...
                             'CData'   ,ImageData        , ...
                             'Position',ObjPos(BtnLp,:)  , ...
                             'Tag'     ,ObjTags{BtnLp,1} , ...
                             'TooltipString',ObjTips{BtnLp,1}, ...
                             'UserData',uicData(BtnLp).data, ...
                             'Callback',ObjCall{BtnLp,1}   ...
                                );
end

set(ObjHandles(1),'Value',1);

for BtnLp=1:size(ToolTags,1),
  ImageData=gnrlfun('Ind2RGB',toolData(BtnLp).data,Map);
  ToolHandles(BtnLp)=uicontrol(ToolInfo , ...
                             'Parent'  ,ToolFig          , ...
                             'CData'   ,ImageData        , ...
                             'Position',ToolPos(BtnLp,:)  , ...
                             'TooltipString',ToolTips{BtnLp,1}, ...
                             'Tag'     ,ToolTags{BtnLp,1} , ...
                             'UserData',toolData(BtnLp).data, ...
                             'Callback',ToolCall{BtnLp,1}   ...
                                );
end


StatusHandle=uicontrol(StatusInfo     ,  ...
                      'Parent'        ,ToolFig         , ...
                      'Position'      ,StatusPos       , ...                  
                      'Tag'           ,StatusTag       , ...
                      'TooltipString' ,StatusTip       , ...
                      'String'        ,StatusString      ...
                      );

ListHandle=uicontrol(ListInfo     , ...
                    'Parent'      ,ToolFig       , ...
                    'Position'    ,ListPos       , ...                  
                    'Tag'         ,ListTag       , ...
                    'TooltipString',ListTip       , ...
                    'Callback'    ,ListCall      , ...
                    'String'      ,ListString      ...
                    );

for MLp=1:length(ButtonTags),                
  ButtonHandles(MLp)=uicontrol(ButtonInfo           , ...
                               'Style'              ,ButtonStyle{MLp}   , ...
                               'Parent'             ,ToolFig            , ...
                               'Position'           ,ButtonPos(MLp,:)   , ...
                               'Tag'                ,ButtonTags{MLp}    , ...
                               'TooltipString'      ,ButtonTips{MLp}    , ...
                               'HorizontalAlignment',ButtonAlign{MLp}   , ...
                               'Callback'           ,ButtonCall{MLp}    , ...
                               'String'             ,ButtonStrings{MLp}   ...
                              );
end % MLp

% Common UserData Settings
set([ToolHandles ObjHandles StatusHandle FrameHandle ...
     ListHandle ButtonHandles], ...
    'Units','normalized');

if isempty(Data.All.DataHandle),
  Data.All.DataHandle=ToolFig;
end  

Data.All.CustomFlag=CustomFlag;
Data.All.CustomList=CustomList;


Data.All.ControlledFigList=LocalGetControlledFigList(Data.All.HandleList);
if ~isempty(Data.All.ControlledFigList),  
  Data.All.GuideFlag=logical(1);  
else,
  Data.All.GuideFlag=logical(0);  
end    

Property={'CloseRequestFcn'      ,'ResizeFcn', ...
          'WindowButtonDownFcn'  ,'Pointer', ...
          'PointerShapeCData'    ,'PointerShapeHotSpot', ...
          'MenuBar'              ,'KeyPressFcn', ...
          'WindowButtonMotionFcn','WindowButtonUpFcn', ...
          'WindowStyle'};    
MiscProperty={'XYLoc','AxisHandle','MenuHandles'};

Data.All.ControlInfo.Figures.Properties=Property;
Data.All.ControlInfo.Figures.MiscProperties=MiscProperty;
Data.All.ControlInfo.Figures.Handle=ones(0,1);
Data.All.ControlInfo.Figures.Property= ...
    cell2struct(cell(0,length(Property)),Property,2);              
Data.All.ControlInfo.Figures.Misc = ...
    cell2struct(cell(0,length(MiscProperty)),MiscProperty,2);

Property={'ButtonDownFcn','HandleVisibility', ...
          'BusyAction'   ,'Interruptible'  , ...
          'UIContextMenu'};
Data.All.ControlInfo.AllObjects.Properties=Property;
Data.All.ControlInfo.AllObjects.Handle=ones(0,1);
Data.All.ControlInfo.AllObjects.Property= ...
    cell2struct(cell(0,length(Property)),Property,2);  

Property={'Enable'};
Data.All.ControlInfo.UIControls.Properties=Property;
Data.All.ControlInfo.UIControls.Handle=ones(0,1);
Data.All.ControlInfo.UIControls.Property= ...
    cell2struct(cell(0,length(Property)),Property,2);  

Property={'Visible'};
Data.All.ControlInfo.UIMenus.Properties=Property;      
Data.All.ControlInfo.UIMenus.Handle=ones(0,1);
Data.All.ControlInfo.UIMenus.Property= ...
    cell2struct(cell(0,length(Property)),Property,2);  

Data.ToolFig.ApplyHandle=ButtonHandles(4);
Data.ToolFig.ButtonHandles=ButtonHandles;
Data.ToolFig.FrameHandle=FrameHandle;
Data.ToolFig.ListHandle=ListHandle;
Data.ToolFig.NewObjectType='pointer';
Data.ToolFig.ObjHandles=ObjHandles;
Data.ToolFig.ToolHandles=ToolHandles;
Data.ToolFig.OldFigPos=FigPos;
Data.ToolFig.OrigPos=[ObjWidth    ObjHeight 
                      ButtonWidth ButtonHeight 
                      FigWidth    FigHeight
                      PtrHeight  PtrWidth
                      ToolHeight  ToolWidth
                      ];
Data.ToolFig.State='out';
Data.ToolFig.StatusHandle=StatusHandle;

Data=guide('ToolUpdate',Data,ToolFig,'add');

if Data.All.DataHandle~=ToolFig,
  DataFig.All.DataHandle=Data.All.DataHandle;
  set(ToolFig,'UserData',DataFig);
end

set(ToolFig,'Visible','on');

Data=guide('Update',Data);
drawnow
set(ToolFig,'ResizeFcn','ctlpanel Resize');


if ~Data.All.GuideFlag,
  statmsg(ToolFig,'To build a GUI, click on the "Add Figure" button');
end        
