function pan2param(varargin)
% This is the GUI m-file able to read the list of parameters to be set for
% the function/block currently selected and to build the window with the
% parameters panel accordingly.
%
%  $Id: pan2param.m,v 1.64 2009/02/01 17:20:04 nicola Exp $

global oldparams params paramEnabled oldparamEnabled paramSets currPanel
global LTPDAinvar selBlocks objName noParamsReq functionName guiFontSize %#ok<NUSED>

%%

currPanel   = varargin{1};
panelDimens = get(currPanel, 'Position');
backColor   = get(currPanel, 'BackgroundColor');
selBlocks   = 0;
set(gcf,'NextPlot','new');
  GUIprefs = getappdata(0, 'GUIpreferences');
  if ~isfield(GUIprefs,'CAD'), GUIprefs.CAD = 0; end
  if ~isfield(GUIprefs,'Copied'), GUIprefs.Copied = 0; end
  if ~isfield(GUIprefs,'Detach'), GUIprefs.Detach = 0; end 
  setappdata(0, 'GUIpreferences',GUIprefs);

guiFontSize = getappdata(0, 'ltpda_gui_fontsize');
if isempty(guiFontSize), guiFontSize = 10; setappdata(0, 'ltpda_gui_fontsize',10); end
set(gcf,'NextPlot','new')
alltimers = timerfindall;
  stop(alltimers(1));
  set(alltimers(1),'TimerFcn',@g_ContinuousParamCheck,'Period',0.3);
  start(alltimers(1));
  

%%
    %----------------------------------------------------------------------
    function buildplistFigureParam(varargin)
    %----------------------------------------------------------------------
    panelDimens = get(currPanel, 'Position');
    lineSpacing = 25 * guiFontSize/10;
    setappdata(0,'ltpda_gui_LineSpacing',lineSpacing);
    if ~isempty(findobj(gcf,'Tag','apply'))
       notredrawn = 0; undoStatus = get(findobj(gcf,'Tag','undo'),'enable');
     % deletes only the dynamical part of the panel:
       for i = 1:numel(objName), try delete(objName{i}); catch, end; end
       delete(findobj('Parent',currPanel,'TooltipString','Remove this parameter'))
    else
       notredrawn = 1; undoStatus = 'off'; 
     % deletes all, to redraw the entire panel:
       delete(findobj(gcf,'Parent',currPanel));
    end
    objName = [];
    close(findobj('Tag','expandedEditField'))
if notredrawn % Executes the STATIC part too only if it's not just an update of the panel

% =========================================================================
% =========================================================================
% ========================== Build STATIC panel ===========================
% =========================================================================
% =========================================================================

% -------------------------------------------------------------------------
% Retrieve the parameters:
% -------------------------------------------------------------------------
  if isempty(oldparams) && isempty(params) % the user has just selected another block
     paramcommand = get_param(gcbh,'Description');
     noParamsReq=0;
     if isempty(paramcommand)
        paramcommand = g_RetrievePlist();
        selBlocks = utils.prog.gcbsh;
        for kk=1:length(selBlocks)
           set_param(selBlocks(kk),'Description',paramcommand);
        end
     end
     eval(paramcommand)
     if ~isempty(oldparams), params = oldparams; end
     oldparamEnabled = paramEnabled;
  end
  
  if ~exist('paramEnabled','var') && isempty(find(params,'Sets')) && noParamsReq==0
     paramEnabled = zeros(1,nparams(params));
     oldparamEnabled = paramEnabled;
  end
  childpath = find_system(gcbh,'LookUnderMasks','all','BlockType','M-S-Function');
  setappdata(0,'ltpda_currFunctionName',get_param(childpath,'Tag'));
    
  y = nparams(params);

  if y==0 && ~exist('paramSets','var') && noParamsReq==0
      paramcommand=[paramcommand,'noParamsReq=1;'];
      selBlocks = utils.prog.gcbsh;
      for kk=1:length(selBlocks), set_param(selBlocks(kk),'Description',paramcommand); end
      buildplistFigureParam([],[],get(findobj('Tag','paramsPage'),'UserData'))
  end
  
% -------------------------------------------------------------------------
% Fixed buttons:
% -------------------------------------------------------------------------
% Help Button
  uicontrol('Parent',currPanel,'Units','pixels','HorizontalAlignment','center','Position',[20 10 45 guiFontSize*16/10],'FontAngle','italic','FontSize',guiFontSize,'String','?','TooltipString','Open the Help associated to this function','Visible','on','Callback',@g_HelpButtonCallback,'Style','pushbutton');
% Reset Parameters Button
  uicontrol('Parent',currPanel,'Units','pixels','HorizontalAlignment','center','Position',[75 10 75 guiFontSize*16/10],'FontAngle','italic','FontSize',guiFontSize,'String','Reset','TooltipString','Reset the parameters for this block','Visible','on','Callback',@g_ResetButtonCallback,'Style','pushbutton');
% 'Set name' checkbox:
  setName = get(gcbh,'UserData');
  if isempty(setName), setName = 0; end
  uicontrol('Parent',currPanel,'Units','pixels','BackgroundColor',backColor,'HorizontalAlignment','left','Position',[170 10 140 guiFontSize*16/10],'FontAngle','italic','FontSize',guiFontSize-2,'String','Set name','TooltipString','Set the signal name equal to the block name','Visible','on','Callback',@g_SetNameCallback,'Value',setName,'Style','checkbox');
% Keep local result
  probe = get_param(gcbh,'MaskHelp');
  if ~isempty(probe) && isa(probe,'char') && strcmp(probe,'probe'), keepRes = 1; else keepRes = 0; end
  uicontrol('Parent',currPanel,'Units','pixels','BackgroundColor',backColor,'HorizontalAlignment','left','Position',[250 10 220 guiFontSize*16/10],'FontAngle','italic','FontSize',guiFontSize-2,'String','Keep local result','TooltipString','Do not delete the result of this block at the end of the analysis calculation','Visible','on','Callback',@g_KeepResultCallback,'Value',keepRes,'Style','checkbox');
% Number of data inputs:
  uicontrol('Parent',currPanel,'TooltipString','Set the number of input expected by this block','BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','right','Position',[370 5 70 guiFontSize*20/10],'String','Inputs: ','FontAngle','italic','FontSize',guiFontSize-2,'Visible','on','Style','text');
  paramFromSimulink = 0;
  for ii=1:y
     paramkeys{ii} = params.params(ii).key;
     paramvals{ii} = params.params(ii).val;
     if isa(paramvals{ii},'char') && numel(paramvals{ii})>2 && strcmp(paramvals{ii},'-->'), paramFromSimulink = paramFromSimulink + 1; end
  end
  inports = find_system(gcb,'SearchDepth',1,'LookUnderMasks','all','BlockType','Inport');
  uicontrol('Parent',currPanel,'TooltipString','Set the number of input expected by this block','BackgroundColor',backColor,'Units','pixels','Position',[450 8 40 guiFontSize*20/10],'String',num2str(numel(inports)-paramFromSimulink),'FontSize',guiFontSize,'Visible','on','Enable','on','UserData',numel(inports)-paramFromSimulink,'Callback',@g_numberDataInput,'Tag','numbDataInputs','Style','edit');

% The function has different sets of parameters:
  if exist('paramSets','var') && ~isempty(paramSets)
      sets = find(paramSets,'sets');
      currSet = find(paramSets,'currSet');
    % Sets popup menu:
      uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[40 panelDimens(4)-30 250 20],'String',sets,'Value',currSet,'Visible','on','UserData',sets,'Callback',@g_SetsUpdate,'Style','popup');
      panelDimens(4) = panelDimens(4)-20;
  end
  
% -------------------------------------------------------------------------
% Button to add user-defined params:
% -------------------------------------------------------------------------
  paramTypes  = {'double/char','specwin','pzmodel','-->'};
  for kk=1:y, paramTypes(strmatch(class(params.params(kk).val),paramTypes,'exact'))=[]; end
  paramTypes  = [paramTypes(1:end-1),{'pz','unit'},paramTypes(end)];
% ParamType popup
  hparamType = uicontrol('Parent',currPanel,'Tag','addparamspopup','TooltipString','Add a user-defined parameter','BackgroundColor',backColor,'Units','pixels','Position',[20 40 100 20],'String',paramTypes,'Value',1,'Visible','on','Enable','on','Style','popupmenu');
% Add params button
  uicontrol('Parent',currPanel,'TooltipString','Add a user-defined parameter','Units','pixels','Position',[130 40 20 20],'String','+','Visible','on','Enable','on','Callback', @g_AddParamCallback,'UserData',hparamType,'Style','pushbutton');

% -------------------------------------------------------------------------
% Buttons to apply or undo:
% -------------------------------------------------------------------------
% Apply button
  uicontrol('Parent',currPanel,'Units','pixels','Position',[panelDimens(3)-70 40 60 guiFontSize*20/10],'HorizontalAlignment','right','FontSize',guiFontSize,'String','Apply','Visible','on','Enable','off','Callback', @g_ApplyButtonCallback,'DeleteFcn',{@g_ApplyButtonCallback,0},'UserData',hparamType,'Tag','apply','Style','pushbutton');
% Undo button
  uicontrol('Parent',currPanel,'Units','pixels','Position',[panelDimens(3)-70 10 60 guiFontSize*20/10],'HorizontalAlignment','right','FontSize',guiFontSize,'String','Undo','Visible','on','Enable',undoStatus,'Callback', @g_UndoButtonCallback,'UserData',hparamType,'Tag','undo','Style','pushbutton');

  
  paramPagePosition = panelDimens + [3 65+guiFontSize*16/10 -6 -(80+guiFontSize*16/10)];
  
else % The part above was executed only if it's not an update of the panel
  y = nparams(params);
  for pp=1:y
     paramkeys{pp} = params.params(pp).key;
     paramvals{pp} = params.params(pp).val;
  end
  if exist('paramSets','var') && ~isempty(paramSets), panelDimens(4) = panelDimens(4)-20; end
  paramPagePosition = panelDimens + [3 65+guiFontSize*16/10 -6 -(80+guiFontSize*16/10)];
end

  
if nargin>2 && isa(varargin{3},'cell'), varargin{3} = varargin{3}{1}; end
if nargin<3, currPage = 1; else currPage = varargin{3}; if isa(currPage,'cell'), currPage = currPage{1}; end; end
uipanel('Parent',currPanel,'BackgroundColor',backColor,'FontSize',7,'Units','pixels','Position',paramPagePosition,'Tag','paramsPage','UserData',currPage);

  GUIprefs = getappdata(0, 'GUIpreferences');
% Check if the parameters panel has to be drawn detached:
  if GUIprefs.Detach
     drawn = g_drawParPanel();
     if drawn, return; end;
  end



% =========================================================================
% =========================================================================
% ========================= Build DYNAMIC panel ===========================
% =========================================================================
% =========================================================================

  totalGaps = 0;
  paramThisPage = 0;
  lastParamGap = 0;
  paramPages = [];
  for ii=1:y
      paramThisPage = paramThisPage+1;
% -------------------------------------------------------------------------
% Cycle to verify whether gaps (= extra lines for complex params, such as
% pzmodels) are necessary or not:
      switch class(paramvals{ii})
         case 'pzmodel'
            if numel(paramvals{ii}.poles)>1 || numel(paramvals{ii}.zeros)>1
               totalGaps = totalGaps+1;
               lastParamGap = 1;
            end
         case 'pz'
            if numel(paramvals{ii})>1
               totalGaps = totalGaps+1;
               lastParamGap = 1;
            end
      end
% -------------------------------------------------------------------------
% Check if it's necessary to draw multiple parameters pages:
      if (paramThisPage+totalGaps)*lineSpacing > paramPagePosition(4)-20
         paramPages = [paramPages , paramThisPage-1];
         if ii==y, paramPages = [paramPages,1]; end
         paramThisPage = 1;
         totalGaps = lastParamGap;
         lastParamGap = 0;
      elseif ii==y
         paramPages = [paramPages , paramThisPage];
      end
  end
  
  currGap = 0;
% The vector 'paramPages' contains how many params are contained into every page.
  if numel(paramPages) > 1
     set(findobj('Tag','paramsPage'),'Title',['Page number ', num2str(currPage)] );
     uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Tag','gotoparamspage','HorizontalAlignment','left','Position',[200 39 100 20],'String','Go to page: ','FontName','Times New Roman','FontSize',guiFontSize+2,'FontWeight','bold','Visible','on','Style','text');
     for ii = 0:numel(paramPages)-1
        uicontrol('Parent',currPanel,'Tag','gotoparamspage','Units','pixels','Position',[300+ii*(30) 40 20 20],'String',num2str(ii+1),'Visible','on','Enable','on','Callback', {@buildplistFigureParam,ii+1},'Style','pushbutton');
     end
  elseif numel(paramPages) == 1
     delete(findobj('Tag','gotoparamspage'))
  elseif isempty(paramPages)
     paramPages = 0;
  end
  firstParam = 1;
  if nargin>1
     if varargin{3}>numel(paramPages), varargin{3} = numel(paramPages); end
     for ii = 1:varargin{3}-1
        firstParam = firstParam + paramPages(ii);
     end
     lastParam = firstParam + paramPages(varargin{3})-1;
  else
     lastParam = paramPages(1);
  end
  currParam = 0;
  
for ii = firstParam:lastParam
    currParam = currParam + 1;
    addedPar = 0;
  % Checkbox to enable input setting:
    objName{ii,1}   =   uicontrol('Parent',currPanel,'Units','pixels','Position',[10,panelDimens(4)-lineSpacing*(currParam+1+currGap),14,14],'Value',paramEnabled(ii),'Visible','on','Enable','on','Callback', @g_EnableCallback,'Tag',paramkeys{ii},'UserData',ii,'Style','checkbox');
  % Remove Param Button:
    try %#ok<ALIGN>
    if strcmpi(paramkeys{ii}(1:7),'addPar_')
        uicontrol('Parent',currPanel,'Units','pixels','Position',[panelDimens(3)-30 panelDimens(4)-lineSpacing*(currParam+1+currGap) 20 20],'String','-','TooltipString','Remove this parameter','Visible','on','Enable','on','UserData',ii,'Callback', @g_RemParamCallback,'Style','pushbutton');
        addedPar = 1;
        paramkeys{ii}(1:7) = [];
    end
    catch, end

    switch class(paramvals{ii})

      % ==========================================================================     
        case {'double'}
      % ==========================================================================
          % Key value:
            objName{ii,2} =  uicontrol('Parent',currPanel,'TooltipString','Key (name of the parameter)','Units','pixels','Position',[50 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 guiFontSize*20/10],'String',paramkeys{ii},'FontSize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_editNameCallback,'Style','edit');
            if ~noParamsReq && ~addedPar
                set(objName{ii,2},'Style','text','BackgroundColor',backColor,'Position',[50 panelDimens(4)-(4+lineSpacing*(currParam+1+currGap)) 120 20]);
            end
          % Val value:
            data = mat2str(paramvals{ii});
            objName{ii,3} = uicontrol('Parent',currPanel,'TooltipString','Val (value of the parameter)','Units','pixels','Position',[200 panelDimens(4)-lineSpacing*(currParam+1+currGap) 200 guiFontSize*20/10],'String',data,'Fontsize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_editValueCallback,'Style','edit');
            objName{ii,4} = uicontrol('UserData',objName{ii,3},'TooltipString','Expand the edit field','Parent',currPanel,'BackgroundColor',[0.7 0.7 0.7],'HorizontalAlignment','left','Position',[405 panelDimens(4)+3-lineSpacing*(currParam+1+currGap) 13 13],'Visible','on','Callback',@g_ExpandEdit,'Style','pushbutton');
          % Enable parameters from Simulink:
            objName{ii,10} = uicontrol('TooltipString','Retrieve from Simulink','String','From Simulink','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[450 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 20],'Max',1,'Min',0,'Value',0,'Visible','on','Tag',num2str(ii),'UserData',[],'Callback',@g_fromSimulinkCallback,'Style','checkbox');
            if strcmp(paramvals{ii},'-->')
                set(objName{ii,3},'Visible','off');
                set(objName{ii,4},'Visible','off');
                set(objName{ii,10},'Value',1);
            end

      % ==========================================================================     
        case {'char'}
      % ==========================================================================
          % Key value:
            objName{ii,2} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[120 panelDimens(4)-lineSpacing*(currParam+1+currGap) 60 20],'String',paramkeys{ii},'FontSize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_editNameCallback,'Style','edit');
            if ~noParamsReq && ~addedPar
                set(objName{ii,2},'Style','text','BackgroundColor',backColor,'Position',[50 panelDimens(4)-(4+lineSpacing*(currParam+1+currGap)) 120 20]);
            end
            if strcmpi(paramkeys{ii},'filename')
              % Browse button:
                currFilename = paramvals{ii};
                if isempty(currFilename), currFilename = 'Browse'; end
                if numel(currFilename)>30, currFilename = ['...',currFilename(end-29:end)]; end
                objName{ii,3} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[200 panelDimens(4)-lineSpacing*(currParam+1+currGap) 300 20],'String',currFilename,'Visible','on','Enable','off','Callback',@g_browseCallback,'Style','pushbutton');
            else
             % Val value:
               objName{ii,3} = uicontrol('Parent',currPanel,'Units','pixels','Position',[200 panelDimens(4)-lineSpacing*(currParam+1+currGap) 200 20],'String',['''',strrep(paramvals{ii},'''',''''''),''''],'Fontsize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_editValueCallback,'Style','edit');
               objName{ii,4} =   uicontrol('UserData',objName{ii,3},'TooltipString','Expand the edit field','Parent',currPanel,'BackgroundColor',[0.7 0.7 0.7],'HorizontalAlignment','left','Position',[405 panelDimens(4)+3-lineSpacing*(currParam+1+currGap) 13 13],'Visible','on','Callback',@g_ExpandEdit,'Style','pushbutton');
            end
            objName{ii,10} = uicontrol('TooltipString','Retrieve from Simulink','String','From Simulink','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[450 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 20],'Max',1,'Min',0,'Value',0,'Visible','on','Tag',num2str(ii),'UserData',[],'Callback',@fromSimulinkCallback,'Style','checkbox');
            if strcmp(paramvals{ii},'-->')
               set(objName{ii,3},'Visible','off');
               set(objName{ii,4},'Visible','off');
               set(objName{ii,10},'Value',1);
            else
               set(objName{ii,10},'Visible','off');
            end
               
      % ==========================================================================     
        case {'unit'}
      % ==========================================================================
          % Key value:
            objName{ii,2} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[120 panelDimens(4)-lineSpacing*(currParam+1+currGap) 60 20],'String',paramkeys{ii},'FontSize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_editNameCallback,'Style','edit');
            if ~noParamsReq && ~addedPar
                set(objName{ii,2},'Style','text','BackgroundColor',backColor,'Position',[50 panelDimens(4)-(4+lineSpacing*(currParam+1+currGap)) 120 20]);
            end
          % Val value:
            unitVal = paramvals{ii}.strs; if isempty(unitVal), unitVal = {''}; end
            allunits = unit.supportedUnits;
            unitsTooltip = 'Supported units: ';
            for kk=1:numel(allunits), unitsTooltip = [unitsTooltip,allunits{kk},',']; end
            unitsTooltip(end)=[];
            objName{ii,3} = uicontrol('Parent',currPanel,'TooltipString',unitsTooltip,'Units','pixels','Position',[200 panelDimens(4)-lineSpacing*(currParam+1+currGap) 200 20],'String',['''',unitVal{1},''''],'Fontsize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_unitValCallback,'Style','edit');
            
      % ==========================================================================     
        case {'logical'}
      % ==========================================================================
          % Key value:
            objName{ii,2} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[120 panelDimens(4)-lineSpacing*(currParam+1+currGap) 60 20],'String',paramkeys{ii},'FontSize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_editNameCallback,'Style','edit');
            if ~noParamsReq && ~addedPar
                set(objName{ii,2},'Style','text','BackgroundColor',backColor,'Position',[50 panelDimens(4)-(4+lineSpacing*(currParam+1+currGap)) 120 20]);
            end
          % Val value:
            objName{ii,3} = uicontrol('Parent',currPanel,'Units','pixels','Position',[200 panelDimens(4)-lineSpacing*(currParam+1+currGap) 100 20],'String',{'false','true'},'Value',paramvals{ii}+1,'Fontsize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_logicValCallback,'Style','popupmenu');

      % ==========================================================================     
        case 'specwin'
      % ==========================================================================     
            selectWind      = paramvals{ii}.type;
            listWindows         = ['Kaiser',specwin.getTypes];
            selectWindValue = strmatch(selectWind,listWindows,'exact');
          % Window text:
            objName{ii,2} =   uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[40 panelDimens(4)-lineSpacing*(currParam+1+currGap)-5 60 20],'String','Window:','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Style','text');
          % Window type popup:
            objName{ii,3} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[105 panelDimens(4)-lineSpacing*(currParam+1+currGap)-2 90 20],'String',listWindows,'TooltipString','Window names','Value',selectWindValue,'Visible','on','Enable','off','Tag',paramkeys{ii},'UserData',ii,'Callback', @g_WindListCallback,'Style','popupmenu');
          % Length value:
            currLength = num2str(length(params.params(ii).val.win));
            objName{ii,4} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[200 panelDimens(4)-lineSpacing*(currParam+1+currGap)-2 70 20],'String',num2str(currLength),'TooltipString','Window Length','Visible','on','Enable','off','UserData',ii,'Callback', @g_WindlengthCallback,'Style','edit');
            if strcmp(selectWind,'Kaiser')
             % PSL value if Kaiser:
               currPSL = params.params(ii).val.psll;
               objName{ii,5} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[275 panelDimens(4)-lineSpacing*(currParam+1+currGap)-2 60 20],'String',num2str(currPSL),'TooltipString','Peak Sidelobe','Visible','on','Enable','off','UserData',ii,'Callback',@g_WindPSLCallback,'Style','edit');
            end
          % Simulink checkbox:
            objName{ii,10} = uicontrol('TooltipString','Retrieve from Simulink','String','From Simulink','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[450 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 20],'Max',1,'Min',0,'Value',0,'Visible','on','Tag',num2str(ii),'UserData',paramvals{ii},'Callback',@g_fromSimulinkCallback,'Style','checkbox');

      % ==========================================================================     
        case 'pzmodel'
      % ==========================================================================     
          % Simulink checkbox:
            objName{ii,10} = uicontrol('TooltipString','Retrieve from Simulink','String','From Simulink','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[500 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 20],'Max',1,'Min',0,'Value',0,'Visible','on','Tag',num2str(ii),'UserData',paramvals{ii},'Callback',@g_fromSimulinkCallback,'Style','checkbox');

            clear pzObj currPoles poleFreqs poleQs poleFQs currZeros zeroFreqs zeroQs zeroFQs
            pzObj = params.params(ii).val;
            currPoles = pzObj.poles;
            currZeros = pzObj.zeros;
          % Load button:
            objName{ii,3} =   uicontrol('Parent',currPanel,'HorizontalAlignment','left','Position',[50 panelDimens(4)-(3+lineSpacing*(currParam+1+currGap)) 50 20],'String','Load','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','UserData',ii,'Callback',@g_pzmodelLoad,'enable','off','Style','pushbutton');
          % Gain text:
            objName{ii,4} =   uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[120 panelDimens(4)-lineSpacing*(currParam+1+currGap)-5 40 20*guiFontSize/10],'String','Gain:','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Style','text');
          % Gain value:
            currGain = pzObj.gain;
            objName{ii,5} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[155 panelDimens(4)-(2+lineSpacing*(currParam+1+currGap)) 60 20],'String',num2str(currGain),'FontSize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_pzmodelGainEdit,'Style','edit');
          % Poles text:
            objName{ii,6} =   uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[240 panelDimens(4)-lineSpacing*(currParam+1+currGap)-5 40 20],'String','Poles:','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Style','text');
          % Zeros text:
            objName{ii,7} =   uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[355 panelDimens(4)-lineSpacing*(currParam+1+currGap)-5 40 20],'String','Zeros:','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Style','text');
          % Poles value:
            for kk=1:numel(currPoles)
                poleFreqs(kk,1) = currPoles(kk).f;
                poleQs(kk,1)    = currPoles(kk).q;
                if ~isnan(poleQs(kk,1))
                    poleFQs{kk,1}=strcat(num2str(poleFreqs(kk,1)),',',num2str(poleQs(kk,1)));
                else
                    poleFQs{kk,1}=num2str(poleFreqs(kk,1));
                end
            end
            if numel(currPoles)>1 || numel(currZeros)>1
                currGap=currGap+1;
            end
            if isempty(currPoles)
                poleFQs = '';
            else
                poleFQs=char(poleFQs);
            end
            objName{ii,8} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[280 panelDimens(4)-(2+lineSpacing*(currParam+1+currGap))-(lineSpacing-30)*(max(numel(currPoles),numel(currZeros))>1) 60 (20+(max(numel(currPoles),numel(currZeros))>1)*lineSpacing)*guiFontSize/10],'Max',2,'String',poleFQs,'FontSize',guiFontSize+1,'TooltipString','Insert ''freq'' or ''freq,q'' on multiple lines','Visible','on','Enable','off','UserData',ii,'Callback',{@g_pzmodelPZEdit,1},'Style','edit');
          % Zeros value:
            for kk=1:numel(currZeros)
                zeroFreqs(kk,1) = currZeros(kk).f;
                zeroQs(kk,1)    = currZeros(kk).q;
                if ~isnan(zeroQs(kk,1))
                    zeroFQs{kk,1}=strcat(num2str(zeroFreqs(kk,1)),',',num2str(zeroQs(kk,1)));
                else
                    zeroFQs{kk,1}=num2str(zeroFreqs(kk,1));
                end
            end
            if isempty(currZeros)
                zeroFQs = '';
            else
                zeroFQs = char(zeroFQs);
            end
            objName{ii,9} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[395 panelDimens(4)-(2+lineSpacing*(currParam+1+currGap))-(lineSpacing-30)*(max(numel(currPoles),numel(currZeros))>1) 60 (20+(max(numel(currPoles),numel(currZeros))>1)*lineSpacing)*guiFontSize/10],'Max',2,'String',zeroFQs,'FontSize',guiFontSize+1,'TooltipString','Insert ''freq'' or ''freq,q'' on multiple lines','Visible','on','Enable','off','UserData',ii,'Callback',{@g_pzmodelPZEdit,0},'Style','edit');

      % ==========================================================================
        case 'pz'
      % ==========================================================================
          % Simulink checkbox:
            objName{ii,10} = uicontrol('TooltipString','Retrieve from Simulink','String','From Simulink','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[500 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 20],'Max',1,'Min',0,'Value',0,'Visible','on','Tag',num2str(ii),'UserData',paramvals{ii},'Callback',@g_fromSimulinkCallback,'Style','checkbox');

            currPoles = params.params(ii).val;
            clear poleFreqs poleQs poleFQs
            for kk=1:numel(currPoles)
                poleFreqs(kk,1) = currPoles(kk).f;
                poleQs(kk,1)    = currPoles(kk).q;
                if isnan(poleQs(kk,1))
                   poleFQs{kk,1}=num2str(poleFreqs(kk,1));
                else
                   poleFQs{kk,1}=strcat(num2str(poleFreqs(kk,1)),',',num2str(poleQs(kk,1)));
                end
                
            end
            poleFQs=char(poleFQs);
          % Poles text:
            objName{ii,2} =   uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','center','Position',[50 panelDimens(4)-(4+lineSpacing*(currParam+1+currGap)) 120 20],'String','PZ','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Enable','off','Style','text');
            if numel(currPoles)>1, currGap=currGap+1; end
          % Poles value:
            objName{ii,3} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[250 panelDimens(4)-(2+lineSpacing*(currParam+1+currGap))-(lineSpacing-30)*(numel(currPoles)>1) 100 (20+(numel(currPoles)>1)*lineSpacing)*guiFontSize/10],'String',poleFQs,'Max',2,'FontSize',guiFontSize,'TooltipString','Insert ''freq'' or ''freq,q''','Visible','on','Enable','on','UserData',ii,'Callback',@g_poleEdit,'Style','edit');               
      
      % ==========================================================================     
        case 'cell'
      % ==========================================================================     
            if isa(paramvals{ii}{1},'char') && strcmp(paramvals{ii}{1},'-->')
              % Key value:
                objName{ii,2} =  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','Position',[50 panelDimens(4)-5-lineSpacing*(currParam+1+currGap) 120 20],'String',paramkeys{ii},'Visible','on','Enable','on','UserData',ii,'Callback',@g_editNameCallback,'Style','text');
              % Text: from Simulink environment:
                objName{ii,3} = uicontrol('TooltipString','Retrieve from Simulink','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[230 panelDimens(4)-6-lineSpacing*(currParam+1+currGap) 200 20],'String','From Simulink environment','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Style','text');
                fromSimulink = 1;
            else
              % Key value:
                objName{ii,2} =  uicontrol('Parent',currPanel,'Units','pixels','Position',[120 panelDimens(4)-lineSpacing*(currParam+1+currGap) 60 20],'String',paramkeys{ii},'Visible','on','Enable','off','UserData',ii,'Callback',@g_editNameCallback,'Style','edit');
                if ~noParamsReq && ~addedPar
                    set(objName{ii,2},'Style','text','BackgroundColor',backColor,'Position',[50 panelDimens(4)-5-lineSpacing*(currParam+1+currGap) 120 20]);
                end
              % Val value:
                data = utils.prog.cell2str(paramvals{ii});
                objName{ii,3} = uicontrol('Parent',currPanel,'Units','pixels','Position',[250 panelDimens(4)-lineSpacing*(currParam+1+currGap) 130 20],'String',data,'Visible','on','Enable','on','UserData',ii,'Callback',@g_editValueCallback,'Style','edit');
                fromSimulink = 0;
            end
                
          % Simulink checkbox:
            objName{ii,10} = uicontrol('TooltipString','Retrieve from Simulink','String','From Simulink','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[500 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 20],'Max',1,'Min',0,'Value',fromSimulink,'Visible','on','Tag',num2str(ii),'UserData',paramvals{ii},'Callback',@g_fromSimulinkCallback,'Style','checkbox');
            

      % ==========================================================================
        otherwise % Other types of param?
      % ==========================================================================
          % Key value:
            objName{ii,3} =  uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','Position',[50 panelDimens(4)-5-lineSpacing*(currParam+1+currGap) 120 20],'String',paramkeys{ii},'FontSize',guiFontSize+1,'Visible','on','Enable','off','UserData',ii,'Callback',@g_editNameCallback,'Style','text');
          % Text: input not supported. Please construct by proper block.
            objName{ii,4} = uicontrol('Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[250 panelDimens(4)-4-lineSpacing*(currParam+1+currGap) 200 20],'String','Unsupported yet','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Visible','on','Style','text');
            fromSimulink = 0;
            
          % Simulink checkbox:
            objName{ii,10} = uicontrol('TooltipString','Retrieve from Simulink','String','From Simulink','FontName','Times New Roman','FontSize',guiFontSize+1,'FontWeight','normal','Parent',currPanel,'BackgroundColor',backColor,'HorizontalAlignment','left','Position',[450 panelDimens(4)-lineSpacing*(currParam+1+currGap) 120 20],'Max',1,'Min',0,'Value',fromSimulink,'Visible','on','Tag',num2str(ii),'UserData',paramvals{ii},'Callback',@g_fromSimulinkCallback,'Style','checkbox');
            
  % ==============================================================================
    end % of SWITCH the param type
  % Cycle to activate enabled params:
    if paramEnabled(ii) || noParamsReq==1
        [xx,yy]       = size(objName);
        jj=2;
        while jj<=yy && ~isempty(objName{ii,jj})
            try set(objName{ii,jj},'Enable','on'); set(objName{ii,jj},'ForegroundColor',[0 0 0]); catch, end
            jj=jj+1;
        end
    end
    
end % of cycle among params

    end % of buildplistFigureParam function
    %----------------------------------------------------------------------

%% ========================= Selection Check ==============================
% =========================================================================
    %----------------------------------------------------------------------
    function g_ContinuousParamCheck(varargin)
  % This is the function to execute a continuous check on the status
  % of the current selection (system and block).
  
         currSelection = utils.prog.gcbsh;
       % set(findobj('Tag','LTPDAGUI'),'Name',[strtok(get(findobj('Tag','LTPDAGUI'),'Name'),' - '),' - ',bdroot]);
         if isnan(selBlocks), buildplistFigureParam([],[],get(findobj('Tag','paramsPage'),'UserData')); end
         
       % Clear the figure if nothing is and was selected OR nothing is and  something was selected  OR is selected a library
         if (isempty(selBlocks) && isempty(currSelection)) || (~isempty(selBlocks) && isempty(currSelection)) || strcmp(get_param(bdroot,'BlockDiagramType'),'library')
             delete(findobj(gcf,'Parent',currPanel))
             try close(findobj('Tag','parampanelFigure')); catch, end;
             selBlocks = [];
             uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[0 (panelDimens(4)+30)/2 panelDimens(3) 30],'String','Nothing currently selected','Visible','on','Style','text');   
             return
         end

       % Check that it's selected a ltpda simulink analysis diagram:
         if ~isempty(bdroot) && ~isempty(find_system(bdroot,'FindAll','on','Type','Annotation','Tag','ltpda model'))

         if ((numel(selBlocks)==1 && selBlocks~=gcbh) || length(selBlocks)~=length(currSelection)) || selBlocks(1)~=currSelection(1)  && ~isempty(currSelection)
             delete(findobj(gcf,'Parent',currPanel))
             try close(findobj('Tag','parampanelFigure')); catch, end;
            GUIprefs = getappdata(0, 'GUIpreferences');
            if GUIprefs.CAD
               if GUIprefs.Copied
                  if length(currSelection)<1, return; end
                  currSelection = g_copyfcnCallback(selBlocks,currSelection);
                  GUIprefs.Copied = 0;
                  setappdata(0, 'GUIpreferences',GUIprefs)
               end
            end
            for i=1:length(currSelection)
               set_param(currSelection(i),'LinkStatus','inactive');
               currentTags{i}=get_param(currSelection(i),'Tag');
            end
            
            if strcmp(currentTags{1},'')
               delete(findobj(gcf,'Parent',currPanel))
               selBlocks = currSelection;
               uicontrol('Parent',currPanel,'BackgroundColor',backColor,'Units','pixels','HorizontalAlignment','center','Position',[0 (panelDimens(4)+30)/2 panelDimens(3) 30],'String','Not a valid LTPDA block','Visible','on','Style','text');
               return
            end
            
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            if numel(currSelection)>1 % then the user has selected multiple blocks
             % Check for consistency: all methods? same class?
               for i=1:numel(currentTags)
                  if ~strcmp(currentTags{i},currentTags{1})
                     g_ErrorSelectionInconsistent(currPanel);
                     selBlocks = currSelection;
                     return;
                  end
               end
             % Check for consistency: same method?:
               for i=1:numel(currSelection)
                  childpath = find_system(currSelection(i),'LookUnderMasks','all','BlockType','M-S-Function');
                  functionname{i}=get_param(childpath,'Tag');
                  if ~strcmp(functionname{i},functionname{1}) % different functions, inconsistent selection
                     g_ErrorSelectionInconsistent(currPanel);
                     selBlocks = currSelection;
                     return;
                  end
               end
            end
            %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
            
            delete(findobj(gcf,'Parent',currPanel))
            selBlocks = currSelection;
            oldparams = []; params = []; paramEnabled = []; oldparamEnabled = []; functionName = ''; paramSets = [];
            
          % Get the new functionName:
            childpath    = find_system(gcbh,'LookUnderMasks','all','BlockType','M-S-Function');
            functionName = get_param(childpath,'Tag');
            if isempty(functionName)
               description = get_param(gcbh,'Description');
               funcname = findstr('functionName=',description);
               if funcname
                  i = funcname+14;
                  while ~strcmp(description(i),';'), i=i+1; end
                  functionName = description(funcname+14:i-2);
               end
            end
            funcType = strtok(get(gcbh,'Tag'));
            if isempty(functionName) && strcmp(funcType,'method')
               functionName = g_setmethod();
            end
            
            switch funcType
               % =========================================================
               case {'function','freepl','method'}
                  buildplistFigureParam()
                % =========================================================
               case 'arithmetic'
                  g_arithmetic(currPanel);
                % =========================================================
               case 'input'
                  g_LoadInputParamCallback(currPanel);
                % =========================================================
               case {'mux','demux'}
                  g_LoadMuxParamCallback();
                % =========================================================
               case 'from'
                  g_LoadFromBlockCallback(currPanel);
                % =========================================================
            end % of switch
            
         end % end of blocks selection
         end   % end of system selection check
         
    end
    %----------------------------------------------------------------------

end