function ltpdagui(varargin)

% =========================================================================
%                               LTPDA GUI
% =========================================================================
% 
%  Open the main LTPDA GUI.
%
%  $Id: ltpdagui.m,v 1.27 2009/01/23 12:40:51 nicola Exp $

warning off all
global LTPDAinvar LTPDAoutvar active labels scaleX

tabbedFigName = 'Family GUI';
   screenSize = get(0,'screensize');
   scaleX     = screenSize(3)/1280;
   if scaleX<1, scaleX = 1; end
   setappdata(0, 'ltpda_gui_scalefactor',scaleX);
   guiSize = [1 1 600*scaleX 550*scaleX];
guiSize = round([(screenSize(3)-guiSize(3))/2 , (screenSize(4)-guiSize(4))/2 , guiSize(3) , guiSize(4)]);

if ~isempty(findobj('Tag','LTPDAGUI')) && nargin==0, return; end

if isempty(LTPDAinvar),  LTPDAinvar  = {}; end
if isempty(LTPDAoutvar), LTPDAoutvar = {}; end

userID = getappdata(0,'ltpda_repo_user');
  if isempty(userID), userID = ''; end
passwd = getappdata(0,'ltpda_repo_pass');
  if isempty(passwd), passwd = ''; end
  
if nargin==0, setappdata(0,'startup',1); [userID passwd] = utils.mysql.logindlg(userID,'',1,tabbedFigName,guiSize); try cd(getappdata(0,'DefaultDataDirectory')); catch, end; end
  if isempty(userID), userID = 'JohnDoe'; passwd=''; end

setappdata(0,'ltpda_repo_user',userID)
setappdata(0,'ltpda_repo_pass',passwd)

if nargin==0
    clc
    disp('Please wait: starting LTPDA GUI...')
    disp('Loading Simulink...')
    drawnow
    load_system('simulink')
    load_system('ltpda_library')
end

try stop(timerfindall); delete(timerfindall); catch end
t1 = timer('TimerFcn',@CheckTimerAlive,'ExecutionMode','fixedRate','Period',0.3);
t2 = timer('TimerFcn',@CheckTimerAlive,'ExecutionMode','fixedRate','Period',1);
start(t1)
start(t2)

%%

tag = '';
units = 'normalized';
position = [0,0,1,1];

% text color in the label:
  foregroundcolor = [0.2,0.2,0.2];
% color in the background, behind tabs:
  backgroundcolor = [0.7,0.7,1];
% background color, inside every tab:
  panelbackgroundcolor = [0.98,0.98,0.98];
% color of the small highlight line, above the selected tab
  titlehighlightcolor = [1,0.3,0];

horizontalalignment = 'center';

active = 0;
string = {'Main LTPDA panel','Parameters','Output','';'Repository','Partial execution','Nested loops','Globals'};
   nrows = size(string,1);
   if nrows>1
       for nn=1:nrows, labels{nn} = string(nn,:); end
       string = string(1,:);
   end
   ntab = numel(string);
   for jj=ntab:-1:1, ntab = ntab - strcmp(string(jj),''); end
     
% Cycle to retrieve parameters from the user:
  for mm=1:2:nargin
      property = lower(varargin{mm});
      value = varargin{mm+1};
      switch property
          case {'title','string'}
              string = value;
              nrows = size(string,1);
              if nrows>1
                  for nn=1:nrows, labels{nn} = string(nn,:);end
                  string = string(1,:);
              end
              ntab = numel(string);
              for jj=ntab:-1:1, ntab = ntab - strcmp(string(jj),''); end
          case {'frameposition','position'}
              position = value;
          case {'framebackgroundcolor','backgroundcolor'}
              backgroundcolor = value;
          case {'framebordertype','bordertype'}
              bordertype = value;
          case {'titleforegroundcolor','foregroundcolor'}
              foregroundcolor = value;
          case {'selecteditem','active'}
              active = value;
          case 'redraw'
              if value == 1 % main panel
                  TopBottomTabCbk([],[],1,1)
                  active = 1;
                  return
              end
              if value == 1.1 % the user clicked the Start button
                  TopBottomTabCbk([],[],1,1)
                  active = 1;
                  runSim = 1;
              end
              if value == 2 % Parameters panel
                  TopBottomTabCbk([],[],2,1)
                  active = 1;
                  return
              end
              if value == 6 % globals panel
                  TopBottomTabCbk([],[],4,2)
                  active = 1;
                  return
              end
              if value == 8 % nested loops
                  TopBottomTabCbk([],[],3,2)
                  active = 1;
                  return
              end
              
          case 'callback'
              if value==1 && strcmp(bdroot,'ltpda_library')
                  HelpCallback();
                  return;
              end
              if value==1 && isempty(findobj('Name',tabbedFigName))
                  return;
              end
          otherwise
              eval([property '= ' value ';']);
      end
  end

parent   = findobj('Tag','LTPDAGUI');
if ~isempty(parent), clf(parent); set(parent,'Resize','on','ResizeFcn',{@GUIResize,guiSize});
else parent = figure('Position',guiSize,'Name',tabbedFigName,'Resize','on','ResizeFcn',{@GUIResize,guiSize},'NumberTitle','off','Toolbar','none','Menubar','none');
end

set(parent,'Tag','LTPDAGUI','NextPlot','new');

if ~exist('margins','var'), margins = {1,'pixels'}; end
if ~iscell(margins), margins = {margins,units}; end
if ~exist('bordertype','var'), bordertype = 'none'; end
if ~exist('titlebackgroundcolor','var'), titlebackgroundcolor = 0.95*panelbackgroundcolor; end
if ~active, active = 1; end

clear htab
htab = uipanel( ...
  'Parent',parent, ...
  'Units',units, ...
  'Position',position, ...
  'BackgroundColor',backgroundcolor, ...
  'BorderType',bordertype, ...
  'Visible','on', ...
  'Tag',tag);

  set(htab,'Units','pixels');
  tabpos = get(htab,'Position');
  

status = uicontainer( ...
  'Parent',htab, ...
  'BackgroundColor',backgroundcolor, ...
  'Units',margins{2}, ...
  'Position',[1,1,1,1], ...
  'Visible','off');

  set(status,'Units','pixels');
  charsz = get(status,'Position');

margins = [charsz(1:2),charsz(1:2)].*margins{1};
set(status,'Units','characters');
set(status,'Position',[1,1,1,1]);
set(status,'Units','pixels');
charsz = get(status,'Position');
titleheight = 2.4*charsz(4);
titleheight = titleheight*scaleX;

margins(3:4) = -(margins(1:2)+margins(3:4));
[loop,sign] = deal(1:ntab,[1,ntab,1,0]);

addtitle = 2*[sign(3:4),-1,-1];
ttextpos = [0.05,0.08,0.9,0.76];
    
  for kk=1:ntab
    title(kk) = uipanel( ...
      'Parent',htab, ...
      'Units','pixels', ...
      'BackgroundColor',titlebackgroundcolor, ...
      'BorderType','beveledout', ...
      'ButtonDownFcn',{@TopBottomTabCbk,kk,1}, ...
      'Visible','on');

    ttext(kk) = uicontrol( ...
      'Parent',title(kk), ...
      'Units','normalized', ...
      'Position',ttextpos, ...
      'ForegroundColor',foregroundcolor, ...
      'BackgroundColor',titlebackgroundcolor, ...
      'HorizontalAlignment',horizontalalignment, ...
      'Style','text', ...
      'String',string{kk}, ...
      'FontSize',11*scaleX,...
      'Enable','inactive', ...
      'HitTest','off',...
      'Visible','on');

  end

  set(htab,'Units','pixels');
  dimension = get(htab,'Position');
  dimension(4) = dimension(4)-nrows*titleheight+5;
  panel = uipanel('Parent',htab,'Tag','mainPanel','Units','pixels','Position',dimension,'BackgroundColor',panelbackgroundcolor,'BorderType','beveledout','Visible','on');
  
  dimension = get(htab,'Position');
  logosize = [52,52];
  dimension = [dimension(3)-logosize(1)-3 , dimension(4)-logosize(2) , logosize];
  logo = axes('Parent',htab,'Units','pixels','Position',dimension,'Tag','Logo');
  image(imread('iconltp.jpg'),'Parent',logo,'AlphaData',imread('iconltpalpha.gif'),'ButtonDownFcn','try open_system(gcs); catch, end;');
  axis(logo,'off'); axis(logo,'square');
  set(logo,'HandleVisibility','callback');

  dimension = get(htab,'Position');
  logosize = [40 40];
  dimension = [dimension(3)-logosize(1)-70 , dimension(4)-logosize(2)-9 , logosize];
  start2 = axes('Parent',htab,'Units','pixels','Position',dimension,'Tag','Start2');
  image(imread('startgreen.jpg'),'Parent',start2,'AlphaData',imread('startalpha.gif'),'ButtonDownFcn','ltpdagui(''redraw'',1.1);','Tag','StartButton');
  axis(start2,'off');
  set(start2,'HandleVisibility','callback');
  
  if active>ntab, active=ntab; end
  
  inset(1) = uicontrol( ...
    'Parent',htab, ...
    'Units','pixels', ...
    'BackgroundColor',panelbackgroundcolor, ...
    'Style','text', ...
    'Visible','on');
  if ~isnan(titlehighlightcolor)
    inset(2) = uicontrol( ...
      'Parent',htab, ...
      'Units','pixels', ...
      'BackgroundColor',titlehighlightcolor, ...
      'Style','text', ...
      'Visible','on');
    inset(3) = uicontrol( ...
      'Parent',htab, ...
      'Units','pixels', ...
      'BackgroundColor',0.85*titlehighlightcolor, ...
      'Style','text', ...
      'Visible','on');
  end
 
% =======================================================================
%                             OTHER BUTTONS
  for xx=2:nrows
      localString = labels{xx};
      ntab = numel(localString);
      for tt=1:ntab
        titles(xx,tt) = uipanel( ...
          'Parent',htab, ...
          'Units','pixels', ...
          'BackgroundColor',titlebackgroundcolor, ...
          'BorderType','beveledout', ...
          'ButtonDownFcn',{@TopBottomTabCbk,tt,xx}, ...
          'Visible','on');

        uicontrol( ...
          'Parent',titles(xx,tt), ...
          'Units','normalized', ...
          'Position',ttextpos, ...
          'ForegroundColor',foregroundcolor, ...
          'BackgroundColor',titlebackgroundcolor, ...
          'HorizontalAlignment',horizontalalignment, ...
          'Style','text', ...
          'String',localString{tt}, ...
          'Enable','inactive', ...
          'FontSize',11*scaleX,...
          'HitTest','off',...
          'Visible','on');
       
     end
  end
% =======================================================================

  TopBottomTabResizeCbk();

panelTitle = get(ttext(active),'string');
setappdata(0, 'ltpda_currPanel', panel);

% =======================================================================
% =======================================================================
% =======================================================================
CheckTimerAlive()

   switch panelTitle
      case 'Main LTPDA panel'
         if exist('runSim','var') && runSim==1
            runSim = 0; %#ok<NASGU>
            pan1main(panel,1)
         else pan1main(panel)
         end
      case 'Parameters'
         pan2param(panel)
      case 'Repository'
         pan3repo(panel)
      case 'Import from workspace'
         pan4import(panel)
      case 'Output'
         pan5output(panel)
      case 'Globals'
         pan6globals(panel)
      case 'Partial execution'
         pan7partial(panel)
      case 'Nested loops'
       % panXyettocome(panel)
         pan8nested(panel)

   end

% =======================================================================
% =======================================================================
% =======================================================================


%%
    %--------------------------------------------------------------------------
    function TopBottomTabCbk(hobj,evdt,indx,numbrow) %#ok<INUSL>
    % Executed when the user clicks on a another tab or resize.
    
    if numbrow>1 % the user clicked on another row
        for pp=ntab:-1:1, ntab = ntab - strcmp(string(pp),''); end
        if ntab==1, active=1; end

      % Swop rows:  
        temp = labels(1);
        labels(1) = labels(numbrow);
        labels(numbrow) = temp;
        clear temp
      % Rebuild the proper list:
        for ii=1:nrows
            temp(ii,1:numel(labels{ii}))=labels{ii};
        end
    else
        active = indx;
        for ii=1:nrows
            temp(ii,1:numel(labels{ii}))=labels{ii};
        end
    end
    
  % ======================================
    ltpdagui('title',temp,'active',indx);
  % ======================================

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

    %--------------------------------------------------------------------------
    function TopBottomTabResizeCbk(varargin)
    % Properly draws the panels.

    units = get(htab,'Units');
    set(htab,'Units','pixels');
    tabpos = get(htab,'Position');
    tabpos(3) = tabpos(3)-120;
    set(htab,'Units',units);
    ntab = numel(string);
    for oo=ntab:-1:1, ntab = ntab - strcmp(string(oo),''); end

    titlepos = [0,0,0,titleheight];
    panelpos = [0,0,tabpos(3),tabpos(4)-titleheight]+margins;
    titlepos(2) = panelpos(2)+panelpos(4);
    panelpos(2) = panelpos(2)-titleheight*(nrows-1)+6;
    
    n = sum(cellfun('length',string))+2*ntab;
    titlepos(1) = panelpos(1)+(1-sign(3))*panelpos(3);
    upperpos = titlepos(2);
    for k=loop
        titlepos(3) = panelpos(3)*(length(string{k})+2)/n;
        addtopos = addtitle.*[k==1,1,k==1|k==ntab,1];
        titlepos(1) = titlepos(1)-(1-sign(3))*titlepos(3);
        titlepos(2) = upperpos - titlepos(4)*(nrows-1)+3+1;
        set(title(k),'Position',titlepos+addtopos);
        titlepos(1) = titlepos(1)+sign(3)*titlepos(3);
    end
    
  % =======================================================================  

    if nrows>1
        for xxx=2:nrows
            localString = labels{xxx};
            ntab = numel(localString);
            for i=ntab:-1:1, ntab = ntab - strcmp(localString(i),''); end
            n = sum(cellfun('length',localString))+2*ntab;
            titlepos(1) = panelpos(1)+(1-sign(3))*panelpos(3);
            titlepos(2) = titlepos(2) + titlepos(4)-2;
            for k=1:ntab
                titlepos(3) = panelpos(3)*(length(localString{k})+2)/n;
                addtopos = addtitle.*[k==1,1,k==1|k==ntab,1];
                titlepos(1) = titlepos(1)-(1-sign(3))*titlepos(3);
                if ntab==1, titlepos(3)=titlepos(3)-2; end
                set(titles(xxx,k),'Position',titlepos+addtopos);
                titlepos(1) = titlepos(1)+sign(3)*titlepos(3);
            end
            if ntab<numel(localString)
                for qq=ntab+1:numel(localString)
                    nullpos=[0,0,1,1];
                    set(titles(xxx,qq),'Position',nullpos);
                end
            end
        end
    end
  
  % =======================================================================  

    titlepos = get(title(active),'Position');
    titlepos = titlepos-addtitle.*[active==sign(1),1,active==sign(1),1];
    titlepos(3) = titlepos(3)-addtitle(3)*(active==sign(2));
    ntab = numel(string);
    for i=ntab:-1:1, ntab = ntab - strcmp(string(i),''); end
    if ntab==1, titlepos(3) = titlepos(3)-4; end
    
    set(title(active),'Position',titlepos,'BackgroundColor',panelbackgroundcolor);
    set(ttext(active),'FontWeight','bold','BackgroundColor',panelbackgroundcolor);

    insetpos = [titlepos(1)+1,titlepos(2)+sign(4)*titlepos(4)-2,titlepos(3)-1,3];
    set(inset(1),'Position',insetpos);
    try
      insetpos = insetpos+[0,(1-2*sign(4))*titleheight+2*sign(4),0,-2];
      set(inset(2),'Position',insetpos);
      set(inset(3),'Position',insetpos+[2,1-2*sign(4),-4,0]);
    catch
    end
     end
    %--------------------------------------------------------------------------

    %--------------------------------------------------------------------------
    function GUIResize(varargin)
    % Called whenever the user resize the GUI window.
    
        guiSize = varargin{3};
        newSize = get(findobj('Tag','LTPDAGUI'),'Position');
        
      % To avoid a width lower than the fixed minimum: 
        if newSize(3)<guiSize(3), newSize(3)=guiSize(3); end
      % To avoid an height lower than the fixed minimum: 
        if newSize(4)<guiSize(4), newSize(4)=guiSize(4); end
      % To avoid a window moved outside the screen border:
        screenSize = get(0,'screensize');
        if newSize(2)+newSize(4)+30>screenSize(4), newSize(2)=screenSize(4)-newSize(4)-40; end
        if newSize(1)+newSize(3)>screenSize(3), newSize(1)=screenSize(3)-newSize(3)-5; end
       
        set(findobj('Tag','LTPDAGUI'),'Position',newSize);
        
      % Redraw the GUI on the current panel:
      % pause(0.1)
        if ~getappdata(0,'startup'), TopBottomTabCbk([],[],active,1)
        else setappdata(0,'startup',0);
        end
                
    end
    %--------------------------------------------------------------------------

%%
    %----------------------------------------------------------------------
    function CheckTimerAlive(varargin)   
        % This is the function to execute a continuous timer check
        
        % Keep alive the first timer:
          alltimers = timerfindall;
          if strcmp(get(alltimers(1),'Running'),'off'), start(alltimers(1)); end
    end
    %----------------------------------------------------------------------
    
    %----------------------------------------------------------------------
    function HelpCallback(varargin)
    % Whenever the user doubleclick a block in the library window (ie, the
    % OpenFcn callback is executed from the library).
       
       openSys = find_system('SearchDepth',0);
       for ii=1:numel(openSys)
          if ~isempty(find_system(openSys{ii},'FindAll','on','Type','Annotation','Tag','ltpda model'))
             add_block(gcb,[openSys{ii},'/',get_param(gcb,'Name')],'MakeNameUnique','on')
             return;
          end
       end
       try
          childpath = find_system(gcbh,'LookUnderMasks','all','BlockType','M-S-Function');
          functionname = get_param(childpath,'Tag');
          
          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
          
          [func,classes] = strtok(get(gcbh,'Tag'));
          if strcmp(func,'method')
             helptext = help([strtrim(classes),'/',functionname]);
          else
             helptext = help(functionname);
          end
          
          helpFigure    =   figure('MenuBar','none','Toolbar','none','Name',strcat(functionname,' help'),'NumberTitle','off','Units','pixels','Position',[200,200,500,300],'Resize','on','ResizeFcn','refresh(gcf)','Tag','helpwindow','Color', get(0, 'defaultuicontrolbackgroundcolor'));
          % Help text:
          uicontrol('Parent',helpFigure,'Units','normalized','HorizontalAlignment','left','Position',[0 0 1 1],'FontSize',8,'String',helptext,'Visible','on','max',100,'Style','edit');
       catch
       end
    end
    %----------------------------------------------------------------------

end