function pan8nested(varargin)

% ========================================================================
% =================== Panel to organize nested loops =====================
% ========================================================================
%
%  $Id: pan8nested.m,v 1.3 2008/11/07 17:59:42 nicola Exp $

scaleX = getappdata(0, 'ltpda_gui_scalefactor');
guiFontSize = round(10*scaleX);
currPanel   = varargin{1};
panelDimens = get(currPanel, 'Position');
backColor   = get(currPanel, 'BackgroundColor');

global paramLoop currSys enabledNestedParams
currSys = '';
   
alltimers = timerfindall;
stop(alltimers(2));
set(alltimers(2),'TimerFcn',@ContinuousCheck,'Period',1);
start(alltimers(2));

%%
 %----------------------------------------------------------------------
 function buildNestedPanel(varargin)
 %----------------------------------------------------------------------

   delete(findobj(gcf,'Parent',currPanel))
   
 % Check if nested loops execution is enabled or not:
   nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
   if isempty(nestBlock)
      nestedStatus = 0;
      nestBlock = {''};
   elseif isempty(get_param(nestBlock{1},'Description'))
      set_param(nestBlock{1},'Description','0');
      nestedStatus = 0;
   else
      nestedStatus = str2double(get_param(nestBlock{1},'Description'));
   end
   

  % Enable nested loops:
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'TooltipString','Enable or disable the execution of nested loops: when disabled the variables won''t be cleared','Units','normalized','Position',[0.2 0.92 0.2 0.040],'String',' Enable nested loops','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Value',nestedStatus,'Visible','on','Callback',{@enableNested,currPanel,nestBlock{1}},'Style','checkbox');

   % Current system:
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Units','normalized','Position',[0.5 0.92 0.125 0.040],'String','Current system:','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Style','text');
    currsystem = bdroot;
    if isempty(currsystem) || isempty(find_system(currsystem,'FindAll','on','Type','Annotation','Tag','ltpda model')), currsystem = 'None'; end
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Units','normalized','Position',[0.65 0.92 0.25 0.040],'String',currsystem,'FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','UserData','currsystem','Style','text');
   
   if isempty(nestBlock{1})
      paramLoop = {};
      paramnumb = 0;
      enabledNestedParams = [];
   else
      paramLoop = get_param(nestBlock{1},'UserData');
      paramnumb = size(paramLoop,1);
      enabledNestedParams = get_param(nestBlock{1},'MaskDescription');
      if ~isempty(enabledNestedParams)
         eval(enabledNestedParams);
      else
         enabledNestedParams = ones(1,paramnumb);
         set_param(nestBlock{1},'MaskDescription',['enabledNestedParams = ',mat2str(enabledNestedParams),';'])
      end
   end
   
   for i=1:paramnumb %ie, for every row
    % Set the proper number to each row:
      paramLoop{i,1}=i;
    % Check that every parameter has a valid order value:
      if isempty(paramLoop{i,2}), paramLoop{i,2}=1; end
    % Check that every parameter has a name (not empty):
      if isempty(paramLoop{i,3})
         ii=1;
         while ~isempty(findstr(['loop.var',num2str(ii)],[paramLoop{:,3}])), ii=ii+1; end
         paramLoop{i,3}=['loop.var',num2str(ii)];
      end
    % Check that every parameter has a values array (even empty):
      if isempty(paramLoop{i,6}), paramLoop{i,6}={}; end
   end
   
% % %  % Defining the array with the names/handles of all the elements in the GUI:
% % %    global AllNames

 % Dimensions of all the objects which can be created inside the Loop Panel:
   AddButtDimension      = [20 20];   RemButtDimension      = [20 20];
   LeftArrDimension      = [20 20];   RightArrDimension     = [20 20];
   UpArrDimension        = [20 15];   DownArrDimension      = [20 15];
   Param2ChangeDimension = [150 20];  IterValDimension      = [60 20];

 % Legend (static part of the window):
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[40 panelDimens(4)-80 50 30],'String',{'Add /','Remove'},'FontName','Times New Roman','FontSize',guiFontSize,'Visible','on','Style','text');
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[110 panelDimens(4)-85 45 30],'String','Position','FontName','Times New Roman','FontSize',guiFontSize,'Visible','on','Style','text');
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[195 panelDimens(4)-85 110 30],'String','Parameter name','FontName','Times New Roman','FontSize',guiFontSize,'Visible','on','Style','text');
  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[360 panelDimens(4)-85 70 30],'String','Iterations','FontName','Times New Roman','FontSize',guiFontSize,'Visible','on','Style','text');

% =========================================================================
% This part build the dynamic part of the window:
% =========================================================================
  if 40*(paramnumb+3)+20 < panelDimens(4), possible2add = 'on';
  else possible2add = 'off';
  end

  for i=1:paramnumb
     AddButtPosition      = [45 panelDimens(4)-40*(i+2)];
     RemButtPosition      = [67 panelDimens(4)-40*(i+2)];
     LeftArrPosition      = [105+30*(paramLoop{i,2}-1) panelDimens(4)-40*(i+2)];
     UpArrPosition        = [125+30*(paramLoop{i,2}-1) panelDimens(4)+8-40*(i+2)];
     DownArrPosition      = [125+30*(paramLoop{i,2}-1) panelDimens(4)-8-40*(i+2)];
     RightArrPosition     = [145+30*(paramLoop{i,2}-1) panelDimens(4)-40*(i+2)];
     Param2ChangePosition = [180+30*(paramLoop{i,2}-1) panelDimens(4)-40*(i+2)];
     IterValPosition      = [355+30*(paramLoop{i,2}-1) panelDimens(4)-40*(i+2)];

   % Checkbox to enable this param:
     uicontrol('Parent',currPanel,'Value',enabledNestedParams(i),'TooltipString','Enable or disable this parameter only','Units','pixels','BackGroundColor',[1 1 1],'Position',[15 panelDimens(4)-40*(i+2)+2 15 15],'Visible','on','Enable',possible2add,'UserData',i,'Callback',{@EnableNestedParam,currPanel,nestBlock{1}},'Style','checkbox');     

       uicontrol('Parent',currPanel,'TooltipString','Add another parameter','Units','pixels','Position',[AddButtPosition,AddButtDimension],'String','+','Visible','on','Enable',possible2add,'UserData',i,'Callback', @AddButtCallback,'Style','pushbutton');
       uicontrol('Parent',currPanel,'TooltipString','Remove this parameter','Units','pixels','Position',[RemButtPosition,RemButtDimension],'String','-','Visible','on','Enable','on','UserData',i,'Callback', @RemButtCallback,'Style','pushbutton');
     LeftArrNames{i} = uicontrol('Parent',currPanel,'TooltipString','Move this parameter to the left','Units','pixels','Position',[LeftArrPosition,LeftArrDimension],'String','<','Visible','on','Enable','on','UserData',i,'Callback', @LeftArrCallback,'Style','pushbutton');
     RightArrNames{i} = uicontrol('Parent',currPanel,'TooltipString','Move this parameter to the right','Units','pixels','Position',[RightArrPosition,RightArrDimension],'String','>','Visible','on','Enable','on','UserData',i,'Callback', @RightArrCallback,'Style','pushbutton');
     UpArrNames{i}   = uicontrol('Parent',currPanel,'TooltipString','Move this parameter up','Units','pixels','Position',[UpArrPosition,DownArrDimension],'String','','Visible','on','Enable','on','UserData',i,'Callback', @UpArrCallback,'Style','pushbutton');
     DownArrNames{i} = uicontrol('Parent',currPanel,'TooltipString','Move this parameter down','Units','pixels','Position',[DownArrPosition,UpArrDimension],'String','','Visible','on','Enable','on','UserData',i,'Callback', @DownArrCallback,'Style','pushbutton');
       uicontrol('Parent',currPanel,'Units','pixels','Position',[Param2ChangePosition,Param2ChangeDimension],'String',paramLoop{i,3},'Visible','on','Enable','on','UserData',i,'Callback',@ParamNameChange,'Style','edit');
     IterValNames{i} = uicontrol('Parent',currPanel,'TooltipString','The number of iterations associated to this parameter','Units','pixels','Position',[IterValPosition,IterValDimension],'String','-','Visible','on','Enable','on','UserData',i,'Callback',@SetIterations,'Tag',['iterButton',num2str(i)],'Style','pushbutton');
     if ~isempty(paramLoop{i,4}), set(IterValNames{i},'String',num2str(paramLoop{i,4})); end

     if i==1, set(UpArrNames{i},'Enable','off'); end
     if i==paramnumb, set(DownArrNames{i},'Enable','off'); end

     if paramLoop{i,2}==paramLoop{i,1}, set(RightArrNames{i},'Enable','off');
     else set(RightArrNames{i},'Enable','on');
     end

     if paramLoop{i,2}==1, set(LeftArrNames{i},'Enable','off');
     else set(LeftArrNames{i},'Enable','on');
     end

  end

% Last button to add a parameter:
  paramnumb = paramnumb+1;
  uicontrol('Parent',currPanel,'Units','pixels','Position',[45 panelDimens(4)-40*(paramnumb+2) 20 20],'String','+','Visible','on','Enable',possible2add,'UserData',paramnumb,'Callback', @AddButtCallback,'Tag','lastaddbutton','Style','pushbutton');

  if ~nestedStatus
     set([findobj(currPanel,'Style','pushbutton');findobj(currPanel,'Style','edit')],'Enable','off');
     set(findobj(currPanel,'Style','text'),'ForegroundColor',[.8 .8 .8]);
     set(findobj(currPanel,'Tag','lastaddbutton'),'enable','on')
  end

 end


%%

% ======================================================================
% ======================================================================
% ============================= FUNCTIONS ==============================
% ======================================================================
% ======================================================================

%%
    %----------------------------------------------------------------------
    function ContinuousCheck(varargin)
  % This is the function to execute a continuous check on the status
  % of the current selection, to verify that a valid LTPDA model is
  % selected.
  
       % 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 = '';
            paramLoop = [];
            enabledNestedParams = [];
            return
         else
            if ~strcmp(gcs,currSys)
              % The selection changed: redraw the panel.
                currSys = gcs;
                enabledNestedParams = [];
                buildNestedPanel();
            end
         end
         
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function enableNested(hObject, varargin)   
    % Callback for the 'Enable nested loops' checkbox.
    
         currStatus = get(hObject,'Value');
         currPanel = varargin{2};
         nestBlock = varargin{3};
         allElements = [findobj(currPanel,'Style','pushbutton');findobj(currPanel,'Style','edit');findobj(currPanel,'Style','checkbox')];
         allTexts = findobj(currPanel,'Style','text');
         
         if isempty(nestBlock)
            paramLoop = {1,1,[],[],[],{},[]};
            nestBlock = add_block('ltpda_library/Commonly Used Blocks/Globals',[bdroot '/Nested loops']);
            annotation = find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model');
            position = get_param(annotation,'Position');
            set_param(nestBlock,'LinkStatus','inactive','Showname','off','MaskDisplay','disp(''Nested loops'')','Tag','nestedloops','DropShadow','on','Position',[position(1)+20  position(2)-42 position(1)+150  position(2)-27 ])
            set_param(nestBlock,'UserData',paramLoop,'UserDataPersistent','on')
         end
                  
         switch currStatus
            case 1
               set_param(nestBlock,'Description','1');
               set_param(nestBlock,'UserData',paramLoop);
               buildNestedPanel();
            case 0
               set_param(nestBlock,'Description','0');
               set(allElements,'Enable','off');
               set(hObject,'Enable','on')
               set(findobj(currPanel,'Tag','lastaddbutton'),'enable','on')
               set(allTexts,'ForegroundColor',[.8 .8 .8]);
         end

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

    %----------------------------------------------------------------------
    function EnableNestedParam(hObject, varargin)   
    % Callback for the 'Enable nested param' checkbox, for EVERY PARAM.
    
         currStatus = get(hObject,'Value');
         currPanel = varargin{2};
         nestBlock = varargin{3};
         currParamIndex = get(hObject,'UserData');
         
         enabledNestedParams(currParamIndex) = currStatus;
         set_param(nestBlock,'MaskDescription',['enabledNestedParams = ',mat2str(enabledNestedParams),';'])

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

    %----------------------------------------------------------------------
    function AddButtCallback(hObject, varargin)   
    % Callback function: run when the user click on the Add button: another
    % parameter is added BELOW the row where user has clicked.
    
         % Retrieve the index (row) of the clicked button:
         currParamIndex = get(hObject,'UserData');
         if currParamIndex==1 && isempty(paramLoop)
            paramLoop = {1,1,[],[],[],{},[]};
            nestBlock = add_block('ltpda_library/Commonly Used Blocks/Globals',[bdroot '/Nested loops']);
            annotation = find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model');
            position = get_param(annotation,'Position');
            set_param(nestBlock,'LinkStatus','inactive','Showname','off','MaskDisplay','disp(''Nested loops'')','Tag','nestedloops','DropShadow','on','Position',[position(1)+20  position(2)-42 position(1)+150  position(2)-27 ])
            set_param(nestBlock,'Description','1','UserData',paramLoop,'UserDataPersistent','on')
            enabledNestedParams = 1;
            set_param(nestBlock,'MaskDescription','enabledNestedParams = 1;')
            
         else
            if currParamIndex > size(paramLoop,1), currParamIndex = size(paramLoop,1); end
            paramLoop = [paramLoop(1:currParamIndex,:);cell(1,7);paramLoop(currParamIndex+1:end,:)];
            currParamIndex = currParamIndex+1;
            paramLoop{currParamIndex,1} = currParamIndex;
            paramLoop{currParamIndex,2} = paramLoop{currParamIndex-1,2};
            nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
            set_param(nestBlock{1},'Description','1','UserData',paramLoop);
            enabledNestedParams = [enabledNestedParams , 1];
            set_param(nestBlock{1},'MaskDescription',['enabledNestedParams = ',mat2str(enabledNestedParams),';'])
         end
         
         
         buildNestedPanel()

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

    %----------------------------------------------------------------------
    function RemButtCallback(hObject, varargin)   
    % Callback function: run when the user click on the Remove button
    
         % Retrieve the index of the clicked button:
         currParamIndex = get(hObject,'UserData');
         nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
         
         if currParamIndex==1 && size(paramLoop,1)==1
            clear paramLoop enabledNestedParams
            delete_block(nestBlock{1})
         else
            xx = size(paramLoop,1);
            ii = currParamIndex+1;
            while ii <= xx && paramLoop{ii,2} > paramLoop{currParamIndex,2}
               paramLoop{ii,2} = paramLoop{ii,2}-1;
               ii = ii+1;
            end
            paramLoop = [paramLoop(1:currParamIndex-1,:);paramLoop(currParamIndex+1:end,:)];
            set_param(nestBlock{1},'UserData',paramLoop);
            enabledNestedParams(currParamIndex) = [];
            set_param(nestBlock{1},'MaskDescription',['enabledNestedParams = ',mat2str(enabledNestedParams),';'])
         end
         
         buildNestedPanel()

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

    %----------------------------------------------------------------------
    function LeftArrCallback(hObject, varargin)   
    % Callback function: run when the user click on the Left Arrow button
    
         % Retrieve the number of the modified parameter:
         currParamIndex = get(hObject,'UserData');
         
         xx = size(paramLoop,1);
         ii = currParamIndex+1;
         while ii <= xx && paramLoop{ii,2} > paramLoop{currParamIndex,2}
            paramLoop{ii,2} = paramLoop{ii,2}-1;
            ii = ii+1;
         end
         paramLoop{currParamIndex,2} = paramLoop{currParamIndex,2}-1;
         
         nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
         set_param(nestBlock{1},'UserData',paramLoop);
         buildNestedPanel()

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

    %----------------------------------------------------------------------
    function RightArrCallback(hObject, varargin)   
    % Callback function: run when the user click on the Right Arrow button
    
       % Retrieve the number of the modified parameter:
         currParamIndex = get(hObject,'UserData');
         
       % Move to the right the parents parameters:
         ii=currParamIndex;
         if ii>1 && paramLoop{currParamIndex,2}<paramLoop{currParamIndex,1}
             while paramLoop{ii-1,2}==paramLoop{ii,2}-1
                 % ie, till when the previous parameters are parents:
                 ii=ii-1;
                 if ii==2, break; end
             end
             % ii is the first parent parameter
             if paramLoop{currParamIndex,2}<=paramLoop{currParamIndex,1}
                 for i=ii:currParamIndex,  paramLoop{i,2}=paramLoop{i,2}+1; end
             end
         end
         
         nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
         set_param(nestBlock{1},'UserData',paramLoop);
         buildNestedPanel()

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

    %----------------------------------------------------------------------
    function UpArrCallback(hObject, varargin)
    % Callback function: run when the user click on the Up Arrow button
    
         % Retrieve the number of the modified parameter:
         currParamIndex = get(hObject,'UserData');
         xx = size(paramLoop,1);

         % Move to the left the parameters children:
         ii=currParamIndex;
         if ii<xx
             while paramLoop{ii+1,2}==paramLoop{ii,2}+1
                 % ie, till when the next parameters are children:
                 ii=ii+1;
                 if ii==xx, break; end
             end
         end
         % ii is the last children parameter
         for i=currParamIndex+1:ii, paramLoop{i,2}=paramLoop{i,2}-1; end
         
         % We move up the selected row:
         paramLoop([currParamIndex-1,currParamIndex],:) = paramLoop([currParamIndex,currParamIndex-1],:);
         paramLoop{currParamIndex-1,2} = paramLoop{currParamIndex,2};
         enabledNestedParams([currParamIndex-1,currParamIndex]) = enabledNestedParams([currParamIndex,currParamIndex-1]);

         for i=1:xx, paramLoop{i,1}=i; end
         nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
         set_param(nestBlock{1},'UserData',paramLoop);
         set_param(nestBlock{1},'MaskDescription',['enabledNestedParams = ',mat2str(enabledNestedParams),';'])
         buildNestedPanel()

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

    %----------------------------------------------------------------------
    function DownArrCallback(hObject, varargin)   
    % Callback function: run when the user click on the Down Arrow button
    
         % Retrieve the number of the modified parameter:
         currParamIndex = get(hObject,'UserData');
         xx = size(paramLoop,1);

         % Move to the left the parameters children:
         ii=currParamIndex;
         if ii<xx
             while paramLoop{ii+1,2}==paramLoop{ii,2}+1
                 % ie, till when the next parameters are children:
                 ii=ii+1;
                 if ii==xx, break; end
             end
         end
         for i=currParamIndex+1:ii, paramLoop{i,2}=paramLoop{i,2}-1; end

         % We move down the selected row:
         paramLoop([currParamIndex,currParamIndex+1],:) = paramLoop([currParamIndex+1,currParamIndex],:);
         paramLoop{currParamIndex,2}=paramLoop{currParamIndex+1,2};
         enabledNestedParams([currParamIndex,currParamIndex+1]) = enabledNestedParams([currParamIndex+1,currParamIndex]);

         for i=1:xx, paramLoop{i,1}=i; end
         nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
         set_param(nestBlock{1},'UserData',paramLoop);
         set_param(nestBlock{1},'MaskDescription',['enabledNestedParams = ',mat2str(enabledNestedParams),';'])
         buildNestedPanel()

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

    %----------------------------------------------------------------------
    function ParamNameChange(hObject, varargin)   
    % Callback function: run when the user changes the name of the variable

         % Retrieve the number of the modified parameter:
         currParamIndex = get(hObject,'UserData');

         newName = get(hObject,'String');
         oldName = paramLoop{currParamIndex,3};
         
         if isempty(newName) || ismember(newName,paramLoop(:,3)), set(hObject,'String',oldName), return; end
         if numel(newName)<6 || ~strcmp(newName(1:5),'loop.'), newName = ['loop.',strrep(newName,'.','')]; set(hObject,'String',newName); end
         
         paramLoop{currParamIndex,3} = newName;
         nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
         set_param(nestBlock{1},'UserData',paramLoop);

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

%%
    %----------------------------------------------------------------------
    function SetIterations(hObject,varargin)
       
         existingFig = findobj('Name','Set iterations');
         if ~isempty(existingFig), close(existingFig); end
    
        % Retrieve the number of the modified parameter:
         currParamIndex = get(hObject,'UserData');
         if ~isempty(paramLoop{currParamIndex,5}) % then there are range settings
            range = paramLoop{currParamIndex,5};
            min   = num2str(range(1));  step  = num2str(range(2));  max   = num2str(range(3));
            range = 1;
         else % there are just direct values settings
            min   = '';  step  = '';  max   = '';
            range = 0;
         end

         screenSize = get(0,'ScreenSize');
         backColor   = [1 1 1];
         setIterSize = [570, 280];
         position   = [(screenSize(3)-setIterSize(1))/2 , (screenSize(4)-setIterSize(2))/2 , setIterSize];
         setIterFig = figure('Position',position,'Name','Set iterations','Tag','setiterations','Resize','off','NumberTitle','off','Toolbar','none','Menubar','none');
       % Texts
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[30 position(4)-40 80 20],'String','Default:','FontName','Times New Roman','FontSize',guiFontSize+3,'FontWeight','bold','Visible','on','Style','text');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[30 position(4)-80 80 20],'String','Iterations:','FontName','Times New Roman','FontSize',guiFontSize+3,'FontWeight','bold','Visible','on','Style','text');
       % Radio buttons:
         rangeORvalues = uibuttongroup('Parent',setIterFig,'BackgroundColor',backColor,'visible','on','SelectionChangeFcn',@enableRangeOrValues);
         uicontrol('Parent',rangeORvalues,'BackgroundColor',backColor,'UserData',0,'HorizontalAlignment','center','Position',[150 position(4)-80 100 20],'String','Range:','FontName','Times New Roman','FontSize',guiFontSize+1,'Visible','on','Value',range,'Style','radiobutton');
         uicontrol('Parent',rangeORvalues,'BackgroundColor',backColor,'UserData',1,'HorizontalAlignment','center','Position',[150 position(4)-110 100 20],'String','Values:','FontName','Times New Roman','FontSize',guiFontSize+1,'Visible','on','Value',~range,'Style','radiobutton');
         
       % Default:
         defVal = paramLoop{currParamIndex,7};
         if isempty(defVal), defVal = ''; end
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[140 position(4)-40 100 20],'String',defVal,'TooltipString','This value will be used whenever this variable isn''t looping, or nested loops are disabled','Enable','on','Tag','defaultvalue','Style','edit');

       % GUI elements for range settings:
         inputExamples = {'Insert only';...
                          'scalar';...
                          'numbers:'};
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[270 position(4)-250 80 170],'String',inputExamples,'Visible','on','Tag','range','Style','text');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[350 position(4)-85 50 20],'String','Min:','Visible','off','Enable','on','Tag','range','Style','text');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[400 position(4)-80 50 20],'String',min,'Visible','off','Enable','on','Tag','rangemin','Style','edit');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[350 position(4)-115 50 20],'String','Step:','Visible','off','Enable','on','Tag','range','Style','text');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[400 position(4)-110 50 20],'String',step,'Visible','off','Enable','on','Tag','rangestep','Style','edit');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[350 position(4)-145 50 20],'String','Max:','Visible','off','Enable','on','Tag','range','Style','text');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[400 position(4)-140 50 20],'String',max,'Visible','off','Enable','on','Tag','rangemax','Style','edit');
       % Apply button:
         uicontrol('Parent',setIterFig,'BackgroundColor',[.9 .9 .9],'Units','pixels','Position',[250 15 60 25],'String','Apply >','Visible','off','Enable','on','Callback',@calcIterRange,'UserData',0,'Tag','range','Style','pushbutton');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','left','Position',[325 17 200 20],'String','---','FontSize',guiFontSize+1,'Visible','off','Tag','rangeIter','Style','text');
       
       % GUI elements for direct values settings:
         listInput = paramLoop{currParamIndex,6};
         inputExamples = {'Examples:';...
                          '       1';...
                          '       2';...
                          ' ';...
                          '  or:';...
                          '       ''one''';...
                          '       ''two''';...
                          ' ';...
                          '  or:';...
                          '       [1:5]';...
                          '       [10:10:50]'};
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','left','Position',[270 position(4)-230 140 170],'String',inputExamples,'Visible','on','Tag','values','Style','text');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[360 position(4)-210 150 150],'String',listInput,'Max',10,'FontSize',guiFontSize,'Visible','on','Enable','on','Callback',@valuesListCallback,'Tag','valuesList','UserData',currParamIndex,'Style','edit');
       % Apply button:
         uicontrol('Parent',setIterFig,'BackgroundColor',[.9 .9 .9],'Units','pixels','Position',[250 15 60 25],'String','Apply >','Visible','on','Enable','on','Callback',@calcIterRange,'UserData',1,'Tag','values','Style','pushbutton');
         uicontrol('Parent',setIterFig,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','left','Position',[325 17 200 20],'String','---','FontSize',guiFontSize+1,'Visible','on','Tag','valuesIter','Style','text');

         if ~isempty(paramLoop{currParamIndex,6}) % then there are values
            numbIter = numel(paramLoop{currParamIndex,6});
            set(findobj(gcf,'tag','valuesIter'),'String',[num2str(numbIter),' iterations'])
            set(findobj(gcf,'tag','rangeIter'),'String',[num2str(numbIter),' iterations'])
         end
         
         if range, enableRangeOrValues(-1,0)
         else enableRangeOrValues(-1,1)
         end
         
    end
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function enableRangeOrValues(hObject,varargin)
       
       if hObject==-1, rangeORvalue = varargin{1};
       else rangeORvalue = get(get(hObject,'SelectedObject'),'userdata');
       end
       
       if rangeORvalue % value
          set(findobj(gcf,'-regexp','Tag','^range'),'visible','off')
          set(findobj(gcf,'-regexp','Tag','^values'),'visible','on')
       else            % range
          set(findobj(gcf,'-regexp','Tag','^range'),'visible','on')
          set(findobj(gcf,'-regexp','Tag','^values'),'visible','off')
       end
       
    end  
    %----------------------------------------------------------------------

    %----------------------------------------------------------------------
    function calcIterRange(hObject,varargin)
       
       rangeORvalue = get(hObject,'userdata');
       defaultVal = findobj(gcf,'Tag','defaultvalue');
       if isempty(get(defaultVal,'String'))
          set(findobj(gcf,'tag','valuesIter'),'String','Please insert a default value')
          return
       end
          
       if rangeORvalue % value
          try
             listField      = findobj(gcf,'tag','valuesList');
             valuesList     = get(listField,'String');
             currParamIndex = get(listField,'UserData');
             numbIter = size(valuesList,1);
             paramLoop{currParamIndex,4} = numbIter;
             paramLoop{currParamIndex,5} = [];
             paramLoop{currParamIndex,6} = valuesList;
             nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
             set_param(nestBlock{1},'UserData',paramLoop);
             
             set(findobj(gcf,'tag','rangemin'),'String','')
             set(findobj(gcf,'tag','rangestep'),'String','')
             set(findobj(gcf,'tag','rangemax'),'String','')
             set(findobj(gcf,'tag','valuesIter'),'String',[num2str(numbIter),' iterations'])
             set(findobj('Tag',['iterButton',num2str(currParamIndex)]),'String',num2str(numbIter))
          catch
             set(findobj(gcf,'tag','valuesIter'),'String','Error')
          end
       else            % range
          try
             minVal  = str2double(get(findobj(gcf,'tag','rangemin'),'String'));
             stepVal = str2double(get(findobj(gcf,'tag','rangestep'),'String'));
             maxVal  = str2double(get(findobj(gcf,'tag','rangemax'),'String'));
             valuesList = num2cell([minVal:stepVal:maxVal]'); %#ok<NBRAK>
             if  ~iscell(valuesList) && isnan(valuesList), error(''); end
             listField      = findobj(gcf,'tag','valuesList');
             currParamIndex = get(listField,'UserData');
             numbIter = size(valuesList,1);
             paramLoop{currParamIndex,4} = numbIter;
             paramLoop{currParamIndex,5} = [minVal,stepVal,maxVal];
             paramLoop{currParamIndex,6} = valuesList;
             nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
             set_param(nestBlock{1},'UserData',paramLoop);

             set(findobj(gcf,'tag','valuesList'),'String',valuesList)
             set(findobj(gcf,'tag','rangeIter'),'String',[num2str(numbIter),' iterations'])
             set(findobj('Tag',['iterButton',num2str(currParamIndex)]),'String',num2str(numbIter))
          catch
             set(findobj(gcf,'tag','rangeIter'),'String','Error')
          end
       end
       paramLoop{currParamIndex,7} = get(defaultVal,'String');
       
       nestBlock = find_system(bdroot,'SearchDepth',1,'BlockType','SubSystem','Tag','nestedloops');
       set_param(nestBlock{1},'UserData',paramLoop);
    end  
    %----------------------------------------------------------------------
          
    %----------------------------------------------------------------------
    function valuesListCallback(hObject, varargin)   

       valuesList = get(hObject,'String');
       currParamIndex = get(hObject,'UserData');
       paramLoop{currParamIndex,6} = valuesList;
              
    end  
    %----------------------------------------------------------------------

end
