function pan6globals(varargin)

% ========================================================================
% ====================== Panel for the globals ===========================
% ========================================================================
% This is the GUI m-file to show that the panel relative to the global
% variables set by the user.
%
%  $Id: pan6globals.m,v 1.6 2008/08/30 12:32:25 nicola Exp $

global gl currSys
currPanel    = varargin{1};
panelDimens  = get(currPanel, 'Position');
backColor    = get(currPanel, 'BackgroundColor');
selBlocks   = 0;
enlargedFont = 0;
currSys = '';

alltimers = timerfindall;
stop(alltimers(1));
set(alltimers(1),'TimerFcn',@ContinuousParamCheck,'Period',0.3);
start(alltimers(1));

 %----------------------------------------------------------------------
 function buildGlobalPanel(varargin)
 %----------------------------------------------------------------------
 
  globBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','globals');
  if isempty(globBlock) || (~isempty(varargin) && isnumeric(varargin{3}) && varargin{3}==-1)
      gl = struct();
      updateGlobalBlock()
  else
      gl = get_param(globBlock{1},'UserData');
  end

%   if isempty(gl) || (~isempty(varargin) && isnumeric(varargin{3}) && varargin{3}==-1), gl=struct(); end
  
  panelDimens = get(currPanel, 'Position');
  delete(findobj(gcf,'Parent',currPanel))
  varnames = fieldnames(gl);
  y        = numel(varnames);

% 'List of global variables' text:
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','Position',[20 panelDimens(4)-40 panelDimens(3)-40 20],'String','List of global variables:','HorizontalAlignment','center','FontSize',enlargedFont+10,'FontWeight','bold','Visible','on','Style','text');
% 'Global names' text:
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','Position',[panelDimens(3)/2-150-20 panelDimens(4)-70 150 20],'String','Names:','HorizontalAlignment','right','FontSize',enlargedFont+9,'Visible','on','Style','text');
% 'Global values' text:
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','Position',[panelDimens(3)/2+20 panelDimens(4)-70 150 20],'String','Values:','HorizontalAlignment','left','FontSize',enlargedFont+9,'Visible','on','Style','text');

  for i=1:y
%     % 'gl.' text:
%       uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','Position',[panelDimens(3)/2-200-20-15 panelDimens(4)-20-24*(i+2)-5 12 20],'String','gl.','FontSize',enlargedFont+8,'Visible','on','Enable','off','Style','text');
    % Variable name edit field:
      uicontrol('Parent',currPanel,'Units','pixels','Position',[panelDimens(3)/2-200-20 panelDimens(4)-20-24*(i+2) 200 20],'String',['gl.',varnames{i}],'FontSize',enlargedFont+8,'Visible','on','Enable','on','UserData',i,'Callback',@globalName,'Style','edit');
    % Variable value edit field:
      currVal = gl.(varnames{i});
      if iscell(currVal), currVal = cell2str(currVal);
      else currVal = mat2str(currVal);
      end
      uicontrol('Parent',currPanel,'Units','pixels','Position',[panelDimens(3)/2+20 panelDimens(4)-20-24*(i+2) 200 20],'String',currVal,'FontSize',enlargedFont+8,'Visible','on','Enable','on','UserData',i,'Callback',@globalValue,'Style','edit');
    % Remove input button
      uicontrol('Parent',currPanel,'Units','pixels','Position',[700 panelDimens(4)-20-24*(i+2) 20 20],'String','-','Visible','on','Enable','on','Callback', @RemoveGlobal,'UserData',i,'Style','pushbutton');
  end
  
% Add input button
  uicontrol('Parent',currPanel,'Units','pixels','Position',[panelDimens(3)/2-10 panelDimens(4)-50-24*(y+2) 20 20],'String','+','TooltipString','Add a global variable','Visible','on','Enable','on','Callback', @AddGlobal,'Style','pushbutton');

% Clear all button:
  uicontrol('Parent',currPanel,'Units','pixels','HorizontalAlignment','center','Position',[panelDimens(3)-100 10 80 16],'FontAngle','italic','FontSize',enlargedFont+8,'String','Clear all','TooltipString','Clear all the global variables','Visible','on','Callback',{@buildGlobalPanel,-1},'Style','pushbutton');

  
 end
 %----------------------------------------------------------------------

%%
    %----------------------------------------------------------------------
    function ContinuousParamCheck(varargin)
  % This is the function to execute a continuous check on the status
  % of the current selection (system and block).
  
       % Clear if nothing's selected
         if isempty(bdroot) || strcmp(get_param(bdroot,'BlockDiagramType'),'library') || isempty(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'))
             delete(findobj(gcf,'Parent',currPanel))
             currSys = gcs;
             gl = struct();
             return
         else
             if ~strcmp(gcs,currSys)
                 % The selection changed.
                 currSys = gcs;
                 buildGlobalPanel();
             end
         end

%          if ~isempty(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'))
%              % It's selected a ltpda simulink analysis diagram.
%              if ~strcmp(gcs,currSys)
%                  % The selection changed.
%                  currSys = gcs;
%                  buildGlobalPanel();
%              end
%          end
         
    end
    %----------------------------------------------------------------------

%%
    %----------------------------------------------------------------------
    function AddGlobal(varargin)
     
        newGlob  = 'global';
        ii = 1;
        while isfield(gl,[newGlob,num2str(ii)]), ii = ii+1;  end
        newGlob = [newGlob,num2str(ii)];
        gl.(newGlob) = [];
        updateGlobalBlock()
        buildGlobalPanel()
    
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function RemoveGlobal(hObject,varargin)
     
        currGlob = get(hObject,'Userdata');
        varnames = fieldnames(gl);
        gl = rmfield(gl,varnames{currGlob});
        updateGlobalBlock()
        buildGlobalPanel()
    
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function globalName(hObject,varargin)
     
        currGlob = get(hObject,'Userdata');
        varnames = fieldnames(gl);
        newGlobName = get(hObject,'String');
        if numel(newGlobName)<4 || ~strcmp(newGlobName(1:3),'gl.'), newGlobName = ['gl.',strrep(newGlobName,'.','')]; end
           
        newGlobName = ['gl.',genvarname(newGlobName(4:end))];
        if isempty(get(hObject,'String')) || isfield(gl,newGlobName(4:end)), set(hObject,'String',['gl.',varnames{currGlob}]); return; end
        
        set(hObject,'String',newGlobName);
        gl = utils.prog.rnfield(gl,varnames{currGlob},newGlobName(4:end));
        updateGlobalBlock()
        buildGlobalPanel()
    
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function globalValue(hObject,varargin)
     
        currGlob = get(hObject,'Userdata');
        newValue = get(hObject,'String');
        varnames = fieldnames(gl);
        try newValue = eval(newValue); catch end
        gl.(varnames{currGlob}) = newValue;
        updateGlobalBlock()
        buildGlobalPanel()
    
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function updateGlobalBlock(varargin)
     
        varNames = fieldnames(gl);

        if numel(varNames)==0
            % Remove the block if no globals are left:
            globBlock = find_system(bdroot,'BlockType','SubSystem','Tag','globals');
            if ~isempty(globBlock)
                delete_block(globBlock)
                return;
            end
        else
            globBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','globals');
            try globBlock = globBlock{1}; catch end
            % Check if the globals block exists:
            if isempty(globBlock)
                globBlock = add_block('ltpda_library/Commonly Used Blocks/Globals',[bdroot '/Globals']);
                annotation = find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model');
                position = get_param(annotation,'Position');
                set_param(globBlock,'Position',[position(1)+20  position(2)-25 position(1)+150  position(2)-10 ])
                set_param(globBlock,'DropShadow','on')
            end

            % Update the globals block:
            set_param(globBlock,'UserData',gl)
            set_param(globBlock,'UserDataPersistent','on')
        end

    
    end
    %----------------------------------------------------------------------

%%
end