function varargout=gnrlfun(FunctionToCall,varargin)
%GNRLFUN General functions for Guide

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


switch FunctionToCall,
  case 'AddHelpMenu',
    [varargout{1:3}]=LocalAddHelpMenu(varargin{1});  
    
  case 'AddToolsMenu',
    [varargout{1:3}]=LocalAddToolsMenu(varargin{1});  
    
  case 'CatchErrors',
    varargout{1}=LocalCatchErrors(varargin{1});  

  case 'ChopString',
    varargout{1}=LocalChopString(varargin{1:2});  

  case 'DeblankAll',
    varargout{1}=LocalDeblankAll(varargin{1});  

  case 'FlipMenus',
    varargout{1}=LocalFlipMenus(varargin{1:2});  

  case 'GetFigPos',
    [varargout{1:2}]=LocalGetFigPos(varargin{1:2});

  case 'GetFigString',
    [varargout{1}]=LocalGetFigString(varargin{1:2});

  case 'GetGoodObjString',
    [varargout{1}]=LocalGetGoodObjString(varargin{1:2});

  case 'GetGuideFigHandles',
    varargout{1}=LocalGetGuideFigHandles;

  case 'GetSameValFlag',
    varargout{1}=LocalGetSameValFlag(varargin{1});  

  case 'GetSafeVal',
    varargout{1}=LocalGetSafeVal(varargin{1:3});  

  case 'GetUserData',
    varargout{1}=LocalGetUserData(varargin{1});

  case 'Ind2RGB',
    varargout{1}=LocalInd2RGB(varargin{1:2});
    
  case 'InitializeHandleList',
    varargout{1}=LocalInitializeHandleList(varargin{1});

  case 'InitializeHandles',
    [varargout{1:2}]=LocalInitializeHandles(varargin{1:2});

  case 'MakeTrue',
    varargout{1}=LocalMakeTrue(varargin{1:2});  

  case 'RemoveSpecialHandles',
    varargout{1}=LocalRemoveSpecialHandles(varargin{1});  

  case 'RemoveToolbarHandles',
    varargout{1}=LocalRemoveToolbarHandles(varargin{1});
    
  case 'RelinquishGeneralControl',
    varargout{1}=LocalRelinquishGeneralControl(varargin{1});  

  case 'SafeSet',
    [varargout{1:2}]=LocalSafeSet(varargin{1:6});  

  case 'TakeGeneralControl',
    varargout{1}=LocalTakeGeneralControl(varargin{1});  

  case 'ToolsMenuCall',
    varargout{1}=LocalToolsMenuCall(varargin{1});    
    
end % switch

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalAddHelpMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Labels,Calls,Tags]=LocalAddHelpMenu(ToolName)
% Return info for Help Menus

switch ToolName,
  case 'Control Panel'    ,ToolNo=2 ;Name='ctlpanel';
  case 'Property Editor'  ,ToolNo=3 ;Name='propedit';
  case 'Callback Editor'  ,ToolNo=4 ;Name='cbedit'  ;
  case 'Alignment Tool'   ,ToolNo=5 ;Name='align';  
  case 'Menu Editor'      ,ToolNo=6 ;Name='menuedit';
  case 'Controlled Figure',ToolNo=[];Name='ctlpanel';  
end  
Call(1:14,1)={[Name ' MenuCall']};
Blank={''};

Labels={'Help'
        '>Control Panel'      
        '>Property Editor'  ;'>Callback Editor'
        '>Alignment Tool'   ;'>Menu Editor'
        '>Controlled Figure';'>Object Browser'
        '>--'               ;'>HG Object HTML Doc'
        };
Tags={'MenuHelp'
      'MenuHelpCtlpanel' 
      'MenuHelpPropEdit'    ;'MenuHelpCbEdit'
      'MenuHelpAligner'     ;
      'MenuHelpMenuEdit'    ;'MenuHelpControlFig';
      'MenuHelpMenuObjBrwse';              
      ''                    ;'MenuHelpObject'
      };
      
Calls=[Blank;Call(1:9,1)];
              

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalAddToolsMenu %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Labels,Calls,Tags]=LocalAddToolsMenu(ToolName)
% Return info for Tools Menus
switch ToolName,
  case 'Control Panel'    ,ToolNo=2 ;Name='ctlpanel';
  case 'Property Editor'  ,ToolNo=3 ;Name='propedit';
  case 'Callback Editor'  ,ToolNo=4 ;Name='cbedit'  ;
  case 'Alignment Tool'   ,ToolNo=5 ;Name='align';  
  case 'Menu Editor'      ,ToolNo=6 ;Name='menuedit';
  case 'Controlled Figure',ToolNo=[];Name='ctlpanel';  
end  
           
Call(1:14,1)={[Name ' ToolsMenuCall']};
Blank={''};

Labels={'Tools'           ;'>Control Panel'
        '>Property Editor';'>Callback Editor'
        '>Alignment Tool' ;'>Menu Editor'
        '>--'             ;'>Refresh Tools^r'
       };
                
Tags={'MenuTools'        ;'MenuToolsControlPanel'
      'MenuToolsPropEdit';'MenuToolsCbEdit'  
      'MenuToolsAligner' ;'MenuToolsMenuEdit'
      ''                 ;'MenuOptionsUpdate'                 
     };
Calls=[Blank;Call(1:5,1);Blank;Call(1,1)];

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalCatchErrors %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalCatchErrors(Data)
  disp('catching errors')
  disp(Data.All.ErrorFlag);
  Data.All.ErrorFlag=Data.All.ErrorFlag+1;
  set(Data.All.DataHandle,'UserData',Data);
  if Data.All.ErrorFlag<2,
    Data=guide('Update',Data);
  else
    error(lasterr)
  end
  disp('done catching errors')
  
%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalChopString %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
function OutString=LocalChopString(InString,StrLength)

StrSize=size(InString);    
OutString=InString;
if StrSize(2)>StrLength+2,
  OutString=[InString(1,1:StrLength) '..'];
elseif StrSize(2)>0,      
  OutString=InString(1,:);
end        


%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalDeblankAll %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
function String=LocalDeblankAll(String)
if ~isempty(String),
  [r,c]=find(String~=' ' & String~=0);
  String=String(:,min(c):max(c));
end   
 
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalFlipMenus %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
function Val=LocalFlipMenus(Val,StringInfo)
  % This takes care of the fact that menus are flipped
  % wrt child order and how they appear in the object browser
  % This now accounts for uicontextmenus
  TempFigLoc=find(StringInfo(Val,6)==abs('F') | StringInfo(Val,6)==abs('U'));
  if ~isempty(TempFigLoc),
    NewMenuLoc=[];
    NumFig=length(TempFigLoc);
    for pLp=1:NumFig,
      if pLp==NumFig,
        % Get indices for 1 past current figure to end of stringinfo
        TempMenuLoc=TempFigLoc(pLp)+1:length(StringInfo(Val,1));
      else,
        % Get indices for 1 past current figure to 1 before next figure
        TempMenuLoc=TempFigLoc(pLp)+1:TempFigLoc(pLp+1)-1;
      end

      if ~isempty(TempMenuLoc),
        FlippedMenus= ...
            flipmenus(StringInfo(Val(TempFigLoc(pLp)),1), ...
            StringInfo(Val(TempMenuLoc,1)) ...
            );
        if ~isempty(FlippedMenus),
          %FlippedMenuLoc=find(ismember( ...
          %    StringInfo(Val(TempMenuLoc),1),FlippedMenus));
          FlippedMenuLoc=findindices( ...
              StringInfo(Val(TempMenuLoc),1),FlippedMenus,1);
          Val(sort(TempMenuLoc(FlippedMenuLoc))) = ...
              Val(TempMenuLoc(FlippedMenuLoc));
        end % if ~isempty
      end % if ~isempty
    end % for pLp
  end % if ~isempty
      
 
%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetFigPos %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%
function [Horiz,Vert]=LocalGetFigPos(Height,Data)
% Get Initial Figure Position
Temp=get(0,'Units');
set(0,'Units','points');
ScreenSize=get(0,'ScreenSize');
set(0,'Units',Temp);

NumOpenFigs=length(Data.All.Figs.Handles);
Horiz=10+NumOpenFigs*30;
Vert=ScreenSize(4)-60-Height-NumOpenFigs*30;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetFigString %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function String=LocalGetFigString(Handle,StrLength)
    if strcmp(get(Handle,'IntegerHandle'),'on'),
      Number = sprintf('%d',Handle);
    else,
      Number = sprintf('%.4f',Handle);
    end % IntegerHandle
    String=['#',Number];
    Name=get(Handle,'Name');
    if ~isempty(Name),
      Name=LocalChopString(Name,StrLength);
      String=[String ': ' Name];      
    end    

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetGoodObjString %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function String=LocalGetGoodObjString(ObjType,Handle)

switch ObjType,    
  case 'figure',
    String=LocalGetFigString(Handle,7);  
    String=['( ' String ' ) '];
    
  case 'uimenu',
    MenuLabel=get(Handle,'Label');
    String=['(' MenuLabel ') '];    
      
  case 'uicontrol',
    UIStyleString=get(Handle,{'Style','String'});
    if iscell(UIStyleString{2}),
      if isempty(UIStyleString{2}),
        UIStyleString(2)={''};
      else,        
        UIStyleString(2)=UIStyleString{2}(1);
      end        
    end
    UIStyleString{2}=gnrlfun('ChopString',UIStyleString{2},7);
    String=['(' UIStyleString{1} ' ' UIStyleString{2} ') '];    
      
  case 'text',
    CurParent=get(Handle,'Parent');

    if Handle==get(CurParent,'XLabel'),
      String='(xlabel) ';
    elseif Handle==get(CurParent,'YLabel'),
      String='(ylabel) ';     
    elseif Handle==get(CurParent,'ZLabel'),
      String='(zlabel) ';
    elseif Handle==get(CurParent,'Title'),
      String='(title) ';
    else,
      TextString=get(Handle,'String');
      if iscell(TextString),
        TextString=TextString{1};
      end
      TextString=gnrlfun('ChopString',TextString,7);
      String=['(' TextString ') '];    
      
    end % if    

  otherwise,
    String='';
    
end % switch Type
    
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetGuideFigHandles %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Handles=LocalGetGuideFigHandles
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');
HiddenFig=findobj(Figures,'flat','Tag','Guide Hidden Figure');

Handles=[ToolFig;PropFig;CBFig;AlignFig;MenuFig;HiddenFig];


%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetSafeVal %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Info=LocalGetSafeVal(Data,PropertyList,Tool)
if isempty(Data.All.HandleList),
  Info={};
end

if ~isempty(Data.All.HandleList),
  Info=cell(length(PropertyList),length(Data.All.HandleList));

  Handle=Data.All.HandleList;

  for MainLp=1:length(PropertyList),
    %% Note Property is a cell array
    Property=PropertyList(MainLp);  
    if Data.All.GuideFlag,
      switch Property{:},
        case {'BusyAction','ButtonDownFcn','HandleVisibility', ...
              'Interruptible','UIContextMenu'},
          AllHandles=Data.All.ControlInfo.AllObjects.Handle;    
          Loc=find(ismember(AllHandles,Handle));
          evalstr=['CurrentVal={Data.All.ControlInfo.AllObjects.' ...
                   'Property(Loc).' Property{:} '};'];
          eval(evalstr,'error(lasterr)');
        case {'CloseRequestFcn'      ,'KeyPressFcn'        , ...
              'MenuBar'              ,'Pointer'            , ...
              'PointerShapeCData'    ,'PointerShapeHotSpot', ...
              'ResizeFcn'            ,'WindowButtonDownFcn', ...
              'WindowButtonMotionFcn','WindowButtonUpFcn'  , ...
              'WindowStyle'},
          FigHandles=Data.All.ControlInfo.Figures.Handle;    
          Loc=find(ismember(FigHandles,Handle));
          evalstr=['CurrentVal={Data.All.ControlInfo.Figures.' ...
                   'Property(Loc).' Property{:} '};'];
          eval(evalstr,'error(lasterr)');
      
        case 'SelectionHighlight',
          AllHandles=Data.All.GenControlInfo.AllObjects.Handle;    
          Loc=find(ismember(AllHandles,Handle));
          evalstr=['CurrentVal={Data.All.GenControlInfo.AllObjects.' ...
                   'Property(Loc).' Property{:} '};'];
          eval(evalstr,'error(lasterr)');
          
        case 'Children',
          CurrentVal=get(Handle,Property);

          for HLp=1:length(Handle),              
            if strcmp(get(Handle(HLp),'Type'),'figure'),
                  AxisHandle = ...
                      Data.All.ControlInfo.Figures.Misc(Handle(HLp)== ...
                        Data.All.ControlInfo.Figures.Handle).AxisHandle;
                  TempVal=CurrentVal{HLp,1};
                  TempVal(TempVal==AxisHandle)=[];
                  CurrentVal{HLp,1}=TempVal;                  
                 
            end % if
          end % switch  
          
        case 'Enable'
          CurrentVal=get(Handle,Property);          
             
          % Find the UIControls
          TypeList=get(Handle,{'Type'});
          UICHandleLoc=strmatch('uicontrol',TypeList);
          if ~isempty(UICHandleLoc),              
            UIHandles=Data.All.ControlInfo.UIControls.Handle;    
            Loc=find(ismember(UIHandles,Handle(UICHandleLoc)));
            CurrentVal(UICHandleLoc)= ...
              {Data.All.ControlInfo.UIControls.Property(Loc).Enable};
          end                
            
        case 'Visible'
          CurrentVal=get(Handle,Property);          
          
          % Find the UIMenus
          TypeList=get(Handle,{'Type'});
          UIMHandleLoc=strmatch('uimenu',TypeList);
          if ~isempty(UIMHandleLoc),              
            UIHandles=Data.All.ControlInfo.UIMenus.Handle;    
            Loc=find(ismember(UIHandles,Handle(UIMHandleLoc)));
            CurrentVal(UIMHandleLoc) = ...
                {Data.All.ControlInfo.UIMenus.Property(Loc).Visible};
          end                
            
        otherwise,
          CurrentVal=get(Handle,Property);
        
      end % switch  
  
    else,
      CurrentVal=get(Handle,Property);
      
      switch Property{:},

        case 'Children',
          LPFlag=0;        
          for HLp=1:length(Handle),              

            if strcmp(get(Handle(HLp),'Type'),'root'),              
              if ~LPFlag,              
                GuideFigs=LocalGetGuideFigHandles;
                LPFlag=1;                
              end                

              %% V5 LPD This can be sped up
              for GLp=1:length(GuideFigs),
                TempVal=CurrentVal{HLp};                
                TempVal(TempVal==GuideFigs(GLp))=[];
                CurrentVal{HLp}=TempVal;                
              end
            end % if strcmp 
          
         end % for HLp            
         
        case 'SelectionHighlight',
          if ~Data.All.GuideFlag,        
            AllHandles=Data.All.GenControlInfo.AllObjects.Handle;    
            Loc=find(ismember(AllHandles,Handle));
            CurrentVal = ...
                {Data.All.GenControlInfo.AllObjects.Property( ...
                 Loc).SelectionHighlight};
          end % if          
      end % switch      
    end % if
  
    Info(MainLp,:)=CurrentVal;
  end % for MainLp
end % if ~isempty  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetSameValFlag %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function ValFlag=LocalGetSameValFlag(CurVal)

ValFlag=1;ct=2;
while ValFlag & ct<=length(CurVal),  
  ValFlag=isequal(CurVal{1},CurVal{ct});
  ct=ct+1;    
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalGetUserData %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalGetUserData(Action)

Handles=LocalGetGuideFigHandles;
if isempty(Handles), % A tool is not open yet
  Data.All.DataHandle=[];  
  Data.All.WatchFlag=0;  
  Data.All.ErrorFlag=0;
  Data.All.GuideFlag=logical(0);
  Data.All.HandleList=[];
  Data.All.ControlInfo=[];  
  Data.All.GenControlInfo.Root={};  
  Property={'SelectionHighlight'};
  Data.All.GenControlInfo.AllObjects.Properties=Property;
  Data.All.GenControlInfo.AllObjects.Handle=ones(0,1);
  Data.All.GenControlInfo.AllObjects.Property= ...
      cell2struct(cell(0,length(Property)),Property,2);  
  Data.All.CopyBuffer={[] []};
  Data.All.UndoBuffer={};
  Data.All.CurrentHandles=[];
  Data.All.UndoHandle=[];  
  Data.All.CutHandle=[];
  Data.All.CopyHandle=[];
  Data.All.PasteHandle=[];
  Data.All.DeleteHandle=[];
  Data.All.BtFStBHandles=[];
  Data.All.Mapping=[];
  Data.All.ControlledFigList=[];
  Data.All.Browser.Handles=[];                         
  Data.All.Browser.Complete=[];                         
  Data.All.Browser.Square=[];                         
  Data.All.Browser.Menu=[];                         
  Data.All.CustomFlag=[];
  Data.All.CustomList={};
  Data.All.StringInfo=[];
  Data.All.ObjTypeTag=[];
  Data.All.Figs.Handles=[];

  if strcmp(Action,'Init'),  
    HiddenFigure=figure('Visible'         ,'off'                , ...
                        'CreateFcn'       ,''                   , ...
                        'HandleVisibility','off'                , ...
                        'IntegerHandle'   ,'off'                , ...
                        'Tag'             ,'Guide Hidden Figure', ...        
                        'Colormap'        ,[]                   , ...
                        'MenuBar'         ,'none'                 ...
                       );

    HiddenAxes=axes('Parent'          ,HiddenFigure        , ...
                    'HandleVisibility','off'               , ...
                    'Tag'             ,'Guide Hidden Axes'   ...
                   );         
  else,
    HiddenFigure=[];HiddenAxes=[];
  end
  
  Data.All.HiddenFigure=[HiddenFigure HiddenAxes];
  
else, % A Tool is already open
  Data=get(Handles(1),'UserData');
  Data=get(Data.All.DataHandle,'UserData');
end 

%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalInd2RGB %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
function rout = LocalInd2RGB(a,cm)
% Make sure A is in the range from 1 to size(cm,1)
if isa(a, 'uint8')
    a = double(a);    % Switch to one based indexing
end
a = max(1,min(a,size(cm,1)));
 
% Extract r,g,b components
r = zeros(size(a)); r(:) = cm(a,1);
g = zeros(size(a)); g(:) = cm(a,2);
b = zeros(size(a)); b(:) = cm(a,3);
 
rout = zeros([size(r),3]);
rout(:,:,1) = r;
rout(:,:,2) = g;
rout(:,:,3) = b;

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalInitializeHandleList %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function HandleList=LocalInitializeHandleList(Data)
% Initialize HandleList

if strcmp(studio, 'on'),
  HandleList = [];
else,
  if isempty(Data),
    HandleList=findobj(children(0),'Selected','on');
    if isempty(HandleList),HandleList=gcf;end        
  else,      
    HandleList=Data.All.HandleList;
  end
end



%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalInitializeHandles %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [HandleFlag,Data]=LocalInitializeHandles(FigHandle,HandleList)
% Initialize Handles

if ~isempty(FigHandle),
  if strcmp(get(FigHandle,'Visible'),'off'),
    Data=LocalGetUserData('Init');
    Data=guide('ToolUpdate',Data,FigHandle,'delete');
    FigHandle=[];    
  end      
end

HandleList=reshape(HandleList,prod(size(HandleList)),1);
HandleList=HandleList(ishandle(HandleList));
HandleList=LocalRemoveSpecialHandles(HandleList);
HandleFlag=0;
Data=LocalGetUserData('Init');

if ~isempty(Data.All.DataHandle), % Another Tool is open
  HandleFlag=1;      
  set(Data.All.HandleList(ishandle(Data.All.HandleList)),'Selected','off');  
  Data.All.HandleList=HandleList;
      
  set(Data.All.HandleList,'Selected','on');    
  
  if ~isempty(FigHandle),
    figure(FigHandle);    
    HandleFlag=2;    
    return
  end % if ~isempty    
  
else,
  HandleFlag=1;
  if strcmp(studio, 'on'),
    HandleList = [];
  else,
    if isempty(HandleList),
      HandleList = gcf;
    end
  end
  Data.All.HandleList=HandleList;
  set(Data.All.HandleList,'Selected','on');    
  
end % if ~isempty

%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalMakeTrue %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%
function true = LocalMakeTrue(x,map)

true = cat(3,reshape(map(x,1),size(x)), ...
             reshape(map(x,2),size(x)), ...
             reshape(map(x,3),size(x)));

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalParsePosition %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function UpdateType=LocalParsePosition(Data,Property,Value,EditHandle)

Loc=findstr(Value,'?');
if isempty(Loc),
  UpdateType=LocalSafeSetHelper(Data,Data.All.HandleList, ...
                                Property,Value,EditHandle);
else,
  CurPos=get(Data.All.HandleList,{'Position'});
  CurPos=cat(1,CurPos{:});
  Value=fliplr(deblank(fliplr(deblank(Value))));
  if Value(1)=='[',Value(1)=[];end
  if Value(end)==']',Value(end)=[];end
  Loc=findstr(Value,'?');
  if Loc(end)~=length(Value),Loc=[Loc length(Value)+1];end

  Start=1;  
  QLocB=1;  
  UpdateType='Property';        
  set(EditHandle,'ForegroundColor',[0 0 0]);
  for qlp=1:length(Loc),
    TempStrVal=Value(Start:Loc(qlp)-1);
    eval(['TempVal=[' TempStrVal '];EFlag=0;'],'EFlag=1;');
    if EFlag,        
      eval('TempVal=evalin(''base'',[''['' TempStrVal '']'']);EFlag=0;', ...
           'EFlag=1;');
      if EFlag,
        set(EditHandle,'ForegroundColor',[1 0 0]);
        UpdateType='None';
        return        
      end      
    end
    
    QLocT=QLocB+length(TempVal);    
    if ~isempty(TempVal),    
      CurPos(:,QLocB:QLocT-1)=TempVal(ones(size(CurPos,1),1),:);
    end      
    Start=Loc(qlp)+1;    
    QLocB=QLocT+1;    
  end         
  CurPos=num2cell(CurPos,2);
  set(Data.All.HandleList,{'Position'},CurPos);
  
end          

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalRelinquishGeneralControl %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalRelinquishGeneralControl(Data)
% Relinquish general control of everything

% Replace everything that was done when taking control

if ~isempty(Data.All.GenControlInfo.AllObjects.Handle),
  Handles=Data.All.GenControlInfo.AllObjects.Handle;
  BadLoc=~ishandle(Handles);
  Data.All.GenControlInfo.AllObjects.Handle(BadLoc)=[];
  Data.All.GenControlInfo.AllObjects.Property(BadLoc)=[];
  Handles(BadLoc)=[];
  set(Handles,Data.All.GenControlInfo.AllObjects.Property);
end

Data.All.GenControlInfo.Root={};

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalRemoveSpecialHandles %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function NewList=LocalRemoveSpecialHandles(CurrentList)
% Function to remove special handles such as Stateflow figures from
% the knowledge of Guide.
NewList=CurrentList;
BadHandles=[findobj(CurrentList,'flat','Tag','SFCHART')
            findobj(CurrentList,'flat','Tag','DEFAULT_SFCHART')
            findobj(CurrentList,'flat','Tag','SF_SAFEHOUSE')
            findobj(CurrentList,'flat','Tag','SFEXPLR')
            findobj(CurrentList,'flat','Tag','SF_DEBUGGER')
            findobj(CurrentList,'flat','Tag','SF_STYLER')
            ];
if ~isempty(BadHandles),
  NewList=setdiff(CurrentList,BadHandles);
end

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalRemoveToolbarHandles %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function NewList=LocalRemoveToolbarHandles(CurrentList)
% Remove the toolbar and its children from the list
NewList=CurrentList;

tbIndices = find(ismember(CurrentList, ...
    findall(CurrentList,'flat','type','uitoolbar')));

ptIndices = find(ismember(CurrentList, ...
    findall(CurrentList,'flat','type','uipushtool')));

tgIndices = find(ismember(CurrentList, ...
    findall(CurrentList,'flat','type','uitoggletool')));

NewList(unique([tbIndices;ptIndices;tgIndices]))=[];

figs=findobj(CurrentList,'flat','Type','figure');

scribeHandles=[];
for lp=1:length(figs),
  scribeHandles=[scribeHandles;plotedit(figs(lp),'gethandles')];
end

if ~isempty(scribeHandles),
  scIndices = find(ismember(NewList,scribeHandles));
  NewList(unique(scIndices))=[];
end
  



%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalSafeSet %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%
function [UpdateType,Data]=LocalSafeSet(Data,Property,Value,SetType, ...
                                        EditHandle,Tool)

% UpdateType can be Property, Handle, None
UpdateType='Property';

if Data.All.GuideFlag,  
  for DLp=1:length(Data.All.HandleList),
    Handle=Data.All.HandleList(DLp);    
    switch Property,
      case {'BusyAction','ButtonDownFcn','HandleVisibility', ...
            'Interruptible','UIContextMenu'},
        AllHandles=Data.All.ControlInfo.AllObjects.Handle;    
        Loc=find(AllHandles==Handle);
        evalstr=['Data.All.ControlInfo.AllObjects.Property(Loc).' ...
                  Property '=Value;'];
        eval(evalstr,'error(lasterr)');
       
      case 'SelectionHighlight',
        AllHandles=Data.All.GenControlInfo.AllObjects.Handle;
        Loc=find(AllHandles==Handle);
        evalstr=['Data.All.GenControlInfo.AllObjects.Property(Loc).' ...
                  Property '=Value;'];
        eval(evalstr,'error(lasterr)');
      
      case {'CloseRequestFcn'      ,'KeyPressFcn'        , ...
            'ResizeFcn'            ,'WindowButtonDownFcn', ...
            'WindowButtonMotionFcn','WindowButtonUpFcn'  },
        FigHandles=Data.All.ControlInfo.Figures.Handle;
        Loc=FigHandles==Handle;
        if strcmp(Tool,'Prop'),
          Value=quoting('DeQuotify',Value);
        end
        evalstr=['Data.All.ControlInfo.Figures.Property(Loc).' ... 
                 Property '=Value;'];
        eval(evalstr,'error(lasterr)');
      
      case {'MenuBar'          ,  'Pointer'            , ...
            'PointerShapeCData' , 'PointerShapeHotSpot', ...
            'WindowStyle'},
        FigHandles=Data.All.ControlInfo.Figures.Handle;    
        Loc=FigHandles==Handle;
        evalstr=['Data.All.ControlInfo.Figures.Property(Loc).' ... 
                Property '=Value;'];
        eval(evalstr,'error(lasterr)');
      
      case 'Enable',
        if ~isempty(Data.All.ControlInfo.UIControls.Handle),
          UIHandles=Data.All.ControlInfo.UIControls.Handle;    
          UIHandleLoc=find(ismember(UIHandles,Data.All.HandleList));
          if any(UIHandleLoc),        
            Data.All.ControlInfo.UIControls.Property(UIHandleLoc).Enable=...
                Value;
          end
        else,
          UIHandleLoc=[];          
        end          
        
        if ~isempty(Data.All.ControlInfo.UIMenus.Handle),        
          UIMHandles=Data.All.ControlInfo.UIMenus.Handle;    
          UIMHandleLoc=find(ismember(UIMHandles,Data.All.HandleList));
          if any(UIMHandleLoc),
            set(Data.All.ControlInfo.UIMenus.Handle(UIMHandleLoc), ...
                 Property,Value);
          end       
        else,
          UIMHandleLoc=[];          
        end          
        Loc=[UIHandleLoc;UIMHandleLoc];
        if isempty(Loc),UpdateType='None';end
        
        break; % get out of for DLp
         
      case 'Visible',
        if ~isempty(Data.All.ControlInfo.UIMenus.Handle),      
          UIMHandles=Data.All.ControlInfo.UIMenus.Handle;    
          UIMHandleLoc=find(ismember(UIMHandles,Data.All.HandleList));
          if any(UIMHandleLoc),        
            Data.All.ControlInfo.UIMenus.Property(UIMHandleLoc).Visible = ...
                Value;
          end
        else,
          UIMHandleLoc=[];          
        end
        
        OtherHandles=Data.All.HandleList;
        if ~isempty(UIMHandleLoc),
          OtherHandles=Data.All.HandleList(~UIMHandleLoc);
        end
       
        set(OtherHandles,Property,Value);
        break; % get out of for DLp
         
      case 'IntegerHandle',    
      
	CurrentFigList=Data.All.ControlInfo.Figures.Handle;
	CurrentObjList=Data.All.ControlInfo.AllObjects.Handle;
	CurrentGenObjList=Data.All.GenControlInfo.AllObjects.Handle;
	CtrlFigList=Data.All.ControlledFigList;
	StringList=Data.All.StringInfo(:,1);
  
        CurrentFigLoc=CurrentFigList==Handle;
        CurrentObjLoc=CurrentObjList==Handle;
        CurrentGenObjLoc=CurrentGenObjList==Handle;
        CtrlFigLoc=CtrlFigList==Handle;          
        StringLoc=StringList==Handle;          
        ChildLoc=allchild(0)==Handle;
        
        set(Data.All.HandleList(DLp),Property,Value);
        RootChild=allchild(0);      
        NewFigHandle=RootChild(ChildLoc);
          
        Data.All.HandleList(DLp)=NewFigHandle;          
        Data.All.ControlInfo.Figures.Handle(CurrentFigLoc) = ...
            NewFigHandle;
        Data.All.ControlInfo.AllObjects.Handle(CurrentObjLoc) = ...
            NewFigHandle;
        Data.All.GenControlInfo.AllObjects.Handle(CurrentGenObjLoc)= ...
            NewFigHandle;
        Data.All.ControlledFigList(CtrlFigLoc)=NewFigHandle;
        Data.All.StringInfo(StringLoc,1)=NewFigHandle;
          
      case 'Position',
        UpdateType=LocalParsePosition(Data,Property,Value,EditHandle);      
        break; % Get out of for lp
          
      case 'Style',
        % This keeps me from throwing a warning      
        if strcmp(Value,'popupmenu')|strcmp(Value,'listbox'),
          Strings=get(Data.All.HandleList,{'String'});
          for lp=1:length(Strings),
            if isempty(Strings{lp}),
              Strings{lp}=' ';
            end % if
          end % for              
          set(Data.All.HandleList,{'String'},Strings,'Style',Value);      
        else,
          set(Data.All.HandleList,'Style',Value);          
        end % if
        
      otherwise,
        if strcmp(SetType,'edit'),      
          UpdateType=LocalSafeSetHelper(Data,Data.All.HandleList, ...
                                        Property,Value,EditHandle);
          break; % get out of for DLp
          
        elseif strcmp(SetType,'cbedit'), % It was set by the callback editor
          set(Data.All.HandleList,Property,Value);
        
        else, % it was set by a popupmenu          
          set(Data.All.HandleList,Property,Value);
          break; %get out of for DLp
          
        end % if strcmp      
        
    end % switch  
    
  end % for DLp    
  
else,

  SetFlag=0;  
  switch Property,
    case 'IntegerHandle',
      for DLp=1:length(Data.All.HandleList),      
        ChildLoc=allchild(0)==Data.All.HandleList(DLp);
        set(Data.All.HandleList(DLp),Property,Value);
        RootChild=allchild(0);      
        NewFigHandle=RootChild(ChildLoc);
            
        Data.All.HandleList(DLp)=NewFigHandle;          
      end % for DLp
        
      UpdateType='Handle';
        
    case 'Position',
      UpdateType=LocalParsePosition(Data,Property,Value,EditHandle);      
          
    case 'SelectionHighlight',
      if ~Data.All.GuideFlag,        
        Handles=Data.All.GenControlInfo.AllObjects.Handle;    
        Loc=find(ismember(Handles,Data.All.HandleList));
        Data.All.GenControlInfo.AllObjects.Property(Loc).SelectionHighlight...
            = Value;
      else,
        SetFlag=1;        
      end %if
      
    case 'Style',
      % This keeps me from throwing a warning      
      if strcmp(Value,'popupmenu')|strcmp(Value,'listbox'),
        Strings=get(Data.All.HandleList,{'String'});
        for lp=1:length(Strings),
          if isempty(Strings{lp}),
            Strings{lp}=' ';
          end % if
        end % for              
        set(Data.All.HandleList,{'String'},Strings,'Style',Value);      
      else,
        set(Data.All.HandleList,'Style',Value);          
      end % if
      
    otherwise,    
      SetFlag=1;
             
  end % switch  
  
  if SetFlag,
    if strcmp(SetType,'edit'),      
      UpdateType=LocalSafeSetHelper(Data,Data.All.HandleList, ...
                                      Property,Value,EditHandle);
          
    elseif strcmp(SetType,'cbedit'), % It was set by the callback editor
      eval('set(Data.All.HandleList,Property,Value);SetFlag=1;','SetFlag=0;');
      if ~SetFlag,UpdateType='None';end
        
    else, % it was set by a popupmenu          
      if iscell(Value),
        disp('If you can reproduce this message after quitting MATLAB')
        disp('and restarting, please report it.')
        Value=Value{:};
      end
      
      eval('set(Data.All.HandleList,Property,Value);SetFlag=1;','SetFlag=0;');
      if ~SetFlag,UpdateType='None';end
        
    end % if strcmp      
  end %if SetFlag    
end % if

% Force the Object Browser To Update 
if (strcmp(Property,'String') | strcmp(Property,'Label')| ...
   strcmp(Property,'Style'))  & ~isequal(UpdateType,'none'),
  UpdateType='Browser';
end  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalSafeSetHelper %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function UpdateType=LocalSafeSetHelper(Data,Handles,Property,Value,EditHandle)

UpdateType='Property';

% Check the first word in the string.  If it is a variable in the
% base workspace then eval it.  If it isn't then take the literal
% string.  If it doesn't eval in the base workspace then take the
% literal string.

if ~isempty(Value) & size(Value,1)==1,
  alphaNumericLoc=find( (Value >= 65 & Value <= 90) |  ...
                        (Value == 95) | ...
                        (Value >= 97 & Value <= 122) | ...
                        (Value >= 48 & Value <= 57 ) );
  badLoc = 1:length(Value);
  badLoc(alphaNumericLoc)=[];
  Word=Value;
  Word(badLoc)=' ';
  Word=fliplr(deblank(fliplr(Word)));
  if ~isempty(Word),
    blankLoc=find(Word==' ');
    if isempty(blankLoc),
      blankLoc=length(Word)+1;
    end
    Word=Word(1:blankLoc(1)-1);
  end
else,
  Word='';
end

baseWorkspaceVars=evalin('base','whos');
baseWorkspaceVars={baseWorkspaceVars.name};

% check to see if the first word matches a variable.
if ~isempty(baseWorkspaceVars),
  if ~isempty(find(strcmp(Word,baseWorkspaceVars))),
    WarningLevel=warning;
    warning('off');
    try
      eval(['set(Handles,Property,evalin(''base'',Value)', ...
            ');EditFlag1=0;'],'EditFlag1=1;');
    catch
      warning(WarningLevel)
    end
    warning(WarningLevel);
  else,
    EditFlag1=1;
  end
  
% Take the literal string
else,
  Value=Value;
  EditFlag1=1;
end

if EditFlag1,
    
  eval('set(Handles,Property,Value);EditFlag2=0;', ...
       'EditFlag2=1;');
  if EditFlag2, % it can't
    EditFlag3=0;
    eval(['set(Handles,Property,',Value,');EditFlag3=0;'], ...
          'EditFlag3=1;');
    if EditFlag3,
      set(EditHandle,'ForegroundColor',[1 0 0]);    
      UpdateType='None';
    else,
      set(EditHandle,'ForegroundColor',[0 0 0]);
    end
  else, % EditFlag2
    set(EditHandle,'ForegroundColor',[0 0 0]);        
    
  end % if EditFlag2          
      
else,% EditFlag
  set(EditHandle,'ForegroundColor',[0 0 0]);
    
end    

if ~isequal(UpdateType,'None') & isequal(Property,'Tag'),
  UpdateType='Handle';
end  

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalTakeGeneralControl %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalTakeGeneralControl(Data)
% Take control of a minor set of properties whenever any Guide tool is open

% AllObjects={Handle SelectionHighlight}

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

Figures=allchild(0);         
Figures(find(ismember(Figures,Data.All.Figs.Handles)))=[];  
Figures=LocalRemoveSpecialHandles(Figures);
AllHandles=findall(Figures);AllHandles=[0;AllHandles];

ExistingLoc=find(ismember(AllHandles,ControlledHandles));
NewLoc=1:length(AllHandles);
NewLoc(ExistingLoc)=[]; 
NewHandles=AllHandles(NewLoc);
  
if ~isempty(NewHandles),
  Property=Data.All.GenControlInfo.AllObjects.Properties;
  TempProperty= cell2struct(get(NewHandles,Property),Property,2);
  
  AllObjInfo.Properties=Property;
  AllObjInfo.Handle(ExistingLoc) = ...
      Data.All.GenControlInfo.AllObjects.Handle;
  AllObjInfo.Property(ExistingLoc) = ...
      Data.All.GenControlInfo.AllObjects.Property;
  
  AllObjInfo.Handle(NewLoc)=NewHandles;    
  AllObjInfo.Property(NewLoc)=TempProperty;    
  
  Data.All.GenControlInfo.AllObjects=AllObjInfo;
  set(NewHandles,'Selected','off','SelectionHighlight' ,'on');  
  
end % if ~isempty(NewHandles)

set(Data.All.HandleList,'Selected','on');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%% LocalToolsMenuCall %%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
function Data=LocalToolsMenuCall(Data)
% Take care of actions underneath the Tools menu and the Tool Buttons

CurrentMenu=gcbo;

if strcmp(get(CurrentMenu,'Type'),'uimenu'),
  Tool=get(CurrentMenu,'Label');
else,
  Tool=get(CurrentMenu,'Tag');
end

set(Data.All.DataHandle,'UserData',Data);
UpdateType='none';
switch Tool,
  case 'Control Panel'  , 
    if ~Data.All.GuideFlag,  
      Figures=allchild(0);      
      Handles=LocalGetGuideFigHandles;
      Figures(find(ismember(Figures,Handles)))=[];
      if ~isempty(Figures),
        Data.All.HandleList=Figures(1);
      else,
        Data.All.HandleList=figure;
      end        
    end % if Data.All.GuideFlag      
    ctlpanel(Data.All.HandleList);
    
  case 'Property Editor', propedit(Data.All.HandleList);
  case 'Callback Editor',   cbedit(Data.All.HandleList);
  case 'Alignment Tool' ,    align(Data.All.HandleList);
  case 'Menu Editor'    , menuedit(Data.All.HandleList);
  case 'Refresh Tools'  , UpdateType='Update';
end % switch  
Data=gnrlfun('GetUserData','Init');

if strcmp(UpdateType,'Update'),
  Data=guide('Update',Data);
end % switch
set(Data.All.DataHandle,'UserData',Data);
