function PCAplots(method,GNATData,Export_Inf,Classes,Labels)
%   An interactive graphical user interface to plot Chemometric Information of the PCA/PLS-DA/OPLS-DA models
%
%   This is a part of the GNAT
%   Copyright  2024  <Mathias Nilsson>%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License along
%   with this program; if not, write to the Free Software Foundation, Inc.,
%   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
%
%   Dr. Mathias Nilsson
%   School of Chemistry, University of Manchester,
%   Oxford Road, Manchester M13 9PL, UK
%   Telephone: +44 (0) 161 306 4465
%   Fax: +44 (0)161 275 4598
%
%   Hugo da Silva Rocha, PhD Student
%   School of Chemistry, University of Manchester,
%   hugo.rocha@postgrad.manchester.ac.uk
%   Telephone: +44 (0) 7871080481
 
%% ---------Setup the GUI
tic
if nargin==0
   disp(' ')
   disp(' PLOT GUI error ')
   disp(' ')
   disp(' Type <<help PLOT_GUI>> for more info ')
   return
elseif nargin>5
   error('re-evaluate the inputs ')
end
if ~exist('Labels','var')    
    Labels = '';
end

GUIData.version=sprintf('%s plot analysis v 1.0',method);
hPLOTfigure = figure(...
    'Units','normalized',...
    'Name',GUIData.version,... 
    'MenuBar','none',...
    'NumberTitle','Off',...
    'Toolbar','Figure',...
    'OuterPosition',[0.0 0.0 0.55 0.9],...
    'Color','w',...
    'Tag','mainfigure',...
    'Visible','off');
movegui(hPLOTfigure,'center')
GUIData.MessageText={datestr(datetime)};
GUIData.MessageText{end +1}=GUIData.version;

guidata(hPLOTfigure,GUIData);
%% ---------GUI Structure

% File menu
hMenuFile=uimenu(...
    'Parent',hPLOTfigure,...
    'Label','Analysis');
hOpenMenu=uimenu(hMenuFile,'Label','Method',...
    'Enable','On');
uimenu(hOpenMenu,'Label','PCA',...
    'Enable','On',...
    'Callback',{@PCAMethod});
uimenu(hOpenMenu,'Label','PLSDA',...
    'Enable','On',...
    'Callback',{@PLSDAMethod});
uimenu(hOpenMenu,'Label','OPLS',...
    'Enable','On',...
    'Callback',{@OPLSMethod});
uimenu(hOpenMenu,'Label','OPLSDA',...
    'Enable','On',...
    'Callback',{@OPLSDAMethod});
% Clean up the Toolbar, removing things we don't need
    tmp = findall(hPLOTfigure,'ToolTipString','New Figure');
    set(tmp,'Visible','Off')
    tmp = findall(hPLOTfigure,'ToolTipString','Open File');
    set(tmp,'Visible','Off')
    tmp = findall(hPLOTfigure,'ToolTipString','Link Plot');
    set(tmp,'Visible','Off')
    tmp = findall(hPLOTfigure,'ToolTipString','Insert Legend');
    set(tmp,'Visible','off')
    tmp = findall(hPLOTfigure,'ToolTipString','Rotate 3D');
    set(tmp,'Visible','Off')
    tmp = findall(hPLOTfigure,'ToolTipString','Brush/Select Data');
    set(tmp,'Visible','Off')
    tmp = findall(hPLOTfigure,'ToolTipString','Insert Colorbar');
    set(tmp,'Visible','Off')
%---------- Main Tab
hTabGroup=uitabgroup(...
    'Parent',hPLOTfigure,...
    'Units','Normalized',...
    'Position',[0 0 1 1],...
    'visible','on');    
%% ---------PCA
hTabScoreLoadingResidual=uitab(...
    'Parent',hTabGroup,...
    'Title','Score/Loading/Residual Results',...
    'TooltipString','Basic spectral analysis tools for PCA models',...
    'Units','Normalized');

%---------- Plot Panel
AxesSLRPanel=uipanel(...
    'Parent',hTabScoreLoadingResidual,...
    'Units','normalized',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
Axes = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','off',...
    'tag','ax1',...
    'ylim',[-inf inf],...
    'Position',[0.11 0.2 0.85 0.65]);
Axes21 = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','on',...
    'Position',[0.11 0.6 0.85 0.35]);
Axes22 = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','on',...
    'Position',[0.11 0.12 0.85 0.35]);
Axes31 = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','on',...
    'Position',[0.11 0.73 0.85 0.23]);
Axes32 = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','on',...
    'Position',[0.11 0.41 0.85 0.23]);
Axes33 = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','on',...
    'Position',[0.11 0.08 0.85 0.23]);

%---------- Scores Panel

% Options Panel
OptionsSLRPanel=uipanel(...
    'Parent',hTabScoreLoadingResidual,...
    'Units','normalized',...    
    'Position',[0.0 0.0 0.27 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
OptionsAxisSPanel=uipanel(...
    'Parent',OptionsSLRPanel,...
    'Units','normalized',...            
    'Title','Plot Scores Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.74 1 0.26],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%htextScoreXaxis =
uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.80 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','X');    
hpopupPCX=uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',1,...
    'TooltipString','Principal Components ploted in X axis',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'BackgroundColor','w',...    
    'String',[],...
    'Position',[0.14 0.81 0.8 0.10],...
    'CallBack', {@ChangingScore_Callback});
%htextScoreYaxis =
uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.57 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','Y');   
hpopupPCY=uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',2,...
    'TooltipString','Principal Components ploted in Y axis',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.14 0.58 0.8 0.10],...
    'CallBack', {@ChangingScore_Callback});
%hTextScoreZaxis =
uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.34 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','Z');   
hpopupPCZ=uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',2,...
    'TooltipString','Principal Components ploted in Z axis',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.14 0.34 0.8 0.1 ],...
    'Enable','off',...
    'CallBack', {@ChangingScore_Callback});
%hTextUse3dimention=
uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.14 0.12 0.42 0.1],...
    'horizontalalignment','l',...
    'FontWeight','bold',...
    'FontSize',9.3,...
    'BackgroundColor',[1 1 1],...
    'String','Enable Z axis');
hCheckUse3D = uicontrol(...
    'Parent',OptionsAxisSPanel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Principal Components ploted in axes Z',...
    'Position',[0.05 0.12 0.07 0.12],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableZaxis_Callback});

%---------- Loadings Panel
OptionsAxisLPanel=uipanel(...
    'Parent',OptionsSLRPanel,...
    'Units','normalized',...            
    'Title','Plot Loadings Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.533 1 0.207],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%htextLoadingXaxis =
uicontrol(...
    'Parent',OptionsAxisLPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.46 1 0.4],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','X');   
hpopupPCXLoading=uicontrol(...
    'Parent',OptionsAxisLPanel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',1,...
    'TooltipString','Principal Components ploted in axes X',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.14 0.75 0.8 0.1 ],...
    'CallBack', {@ChangingScore_Callback});
%htextLoadingYaxis =
uicontrol(...
    'Parent',OptionsAxisLPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.30 0.07 0.25],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','Y');   
hpopupPCYLoading=uicontrol(...
    'Parent',OptionsAxisLPanel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',2,...
    'TooltipString','Principal Components ploted in axes Y',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.14 0.44 0.8 0.1],...
    'Enable','off',...
    'CallBack', {@ChangingScore_Callback});
%hTextUse2DLoadings=
uicontrol(...
    'Parent',OptionsAxisLPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.14 0.12 0.56 0.123],...
    'horizontalalignment','l',...
    'FontWeight','bold',...
    'FontSize',9.3,...
    'BackgroundColor',[1 1 1],...
    'String','Enable 2D plots');
hCheck2DLoadings = uicontrol(...
    'Parent',OptionsAxisLPanel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    '2D Loadings',...
    'Position',[0.05 0.12 0.07 0.13],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@Enable2DLoading_Callback});

%---------- Processing Panel
OptionsPreprocessing=uipanel(...
    'Parent',OptionsSLRPanel,...
    'Units','normalized',...            
    'Title','Processing',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.42 1 0.11],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethod_Processing=
uicontrol(...
    'Parent',OptionsPreprocessing,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.5 0.42 0.23],...
    'horizontalalignment','l',...
    'FontWeight','bold',...
    'FontSize',9.3,...
    'BackgroundColor',[1 1 1],...
    'String','Pre-processing Samples');
hProcessing_PCA = uicontrol(...
    'Parent',OptionsPreprocessing,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the processing method for PCA',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'mean|auto|pareto',...
    'Position',[0.55 0.60 0.4 0.15],...
    'Enable','on',...
    'CallBack', @ModelPCA);

%---------- Visual Panel
OptionsPlotPanel=uipanel(...
    'Parent',OptionsSLRPanel,...
    'Units','normalized',...            
    'Title','Visual Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.29 1 0.13],... 
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hCheckLabels = uicontrol(...
    'Parent',OptionsPlotPanel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Labels',...
    'FontSize',9.3,...
    'FontWeight','bold',...
    'Position',[0.05 0.52 0.29 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableLabel_Callback});
hCheckLegend = uicontrol(...
    'Parent',OptionsPlotPanel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Legend',...
    'FontSize',9.3,...
    'FontWeight','bold',...    
    'Position',[0.05 0.12 0.29 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableLegend_Callback});
hCheckEllipse = uicontrol(...
    'Parent',OptionsPlotPanel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Class Ellipse',...
    'FontSize',9.3,...
    'FontWeight','bold',...    
    'Position',[0.50 0.52 0.49 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableEllipse_Callback});

%---------- Export Data Panel
OptionsExportPanel=uipanel(...
    'Parent',OptionsSLRPanel,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.17 1 0.12],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

% hExportData = 
uicontrol(...
    'parent',OptionsExportPanel,...
    'style','PushButton',...
    'String','Export PCA Info',...
    'Units','Normalized',...
    'TooltipString','Export info of PCA analysis to a file',...
    'Position',[0.02 0.49 0.47 0.44],...
    'Callback',{ @ExportInfo});    
% hSaveModel = 
uicontrol(...
    'parent',OptionsExportPanel,...
    'style','PushButton',...
    'String','Export PCA Data',...
    'Units','Normalized',...
    'TooltipString','Export data of PCA analysis to a file',...
    'Position',[0.51 0.49 0.47 0.44 ],... 
    'Callback',{@ExportData});  
% hExportFigures = 
uicontrol(...
    'parent',OptionsExportPanel,...
    'style','PushButton',...
    'String','Export PCA Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figure(s)',...
    'Position',[0.02 0.03 0.47 0.44 ],... 
    'Callback',{ @ExportFigure});    
% hSaveModel = 
uicontrol(...
    'parent',OptionsExportPanel,...
    'style','PushButton',...
    'String','Save Model',...
    'Units','Normalized',...
    'TooltipString','Save Model in a .m file',...
    'Position',[ 0.51,0.03,0.47,0.44],... 
    'Callback',{@ExportModel});  


%---------- Info Panel
hMessagesPanel=uipanel(...
    'Parent',OptionsSLRPanel,...
    'Title','Info',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0 1 0.17]);
hTextTest=uicontrol(...
    'Parent',hMessagesPanel,...
    'Style','edit',...
    'String','',...
    'Max',2,...
    'Enable','Off',...
    'Tag','MessageText',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.0 0.02 1 0.97],...
    'horizontalalignment','l');
    set(hTextTest,'String',GUIData.MessageText)

%% ---------PLSDA
%% ----------- Tab Model
hTabModelPLSDA=uitab(...
    'Parent',[],...
    'Title','Model',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupPLSDA=uitabgroup(...
    'Parent',hTabModelPLSDA,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangingScorePLS_Callback,...
    'Position',[0.0 0.0 1 1]);
hTabScorePLSDA=uitab(...
    'Parent',hTabGroupPLSDA,...
    'Title','Score Plots',...
    'TooltipString','Score Plot',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabLoadingPLSDA=uitab(...
    'Parent',hTabGroupPLSDA,...
    'Title','Loading Plots',...
    'TooltipString','Loading Plot',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
%-----VIP organization---------
hTabVIPPLSDA=uitab(...
    'Parent',hTabGroupPLSDA,...
    'Title','VIP Score',...
    'TooltipString','VIP plots',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabGroupPLSDA_VIP=uitabgroup(...
    'Parent',hTabVIPPLSDA,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangeTabCallback,...
    'Position',[0.27 0.0 0.73 1]);
hTabVIPPlot=uitab(...
    'Parent',hTabGroupPLSDA_VIP,...
    'Title','Plot',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabVIPTable=uitab(...
    'Parent',hTabGroupPLSDA_VIP,...
    'Title','Table',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
%------------------------------
hTabPermutPLSDA=uitab(...
    'Parent',hTabGroupPLSDA,...
    'Title','Permutation test',...
    'TooltipString','Show the plots for permutation tests',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabAxesPLSDA=uitab(...
    'Parent',hTabGroupPLSDA,...
    'Title','Discrimination',...
    'TooltipString','Discrimination of classes Plot',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabROCPLSDA=uitab(...
    'Parent',hTabGroupPLSDA,...
    'Title','ROC Curves',...
    'TooltipString','ROC Curves',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabConfMatPLSDA=uitab(...
    'Parent',[],...
    'Title','Confusion Matrix',...
    'TooltipString','Confusion Matrix values for the current model',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');

%% ----------------- Control Panel (left)

%---------- Model Construction Main panel
hModelPLSDA=uipanel(...
    'Parent',hTabModelPLSDA,...
    'Units','normalized',...            
    'Position',[0.0,0.0,0.27,0.96],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');   

%---------- Plot Scores Panel
hRunModel=uipanel(...
    'Parent',hModelPLSDA,...
    'Units','normalized',...            
    'Title','Plot Scores Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.74 1 0.26],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%htextScoreXaxis =
uicontrol(...
    'Parent',hRunModel,...
    'Units','Normalized',...
    'Style','text',...
    'Position',[0.05 0.80 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','X');    
hScore_PLSDA_Model_X=uicontrol(...
    'Parent',hRunModel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',1,...
    'TooltipString','Score ploted in axes X',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'BackgroundColor','w',...    
    'String',[],...
    'Position',[0.14 0.81 0.8 0.10],...
    'CallBack', {@ModelPLSDA});
%htextScoreYaxis =
uicontrol(...
    'Parent',hRunModel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.57 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','Y');   
hScore_PLSDA_Model_Y=uicontrol(...
    'Parent',hRunModel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',2,...
    'TooltipString','Score ploted in axes Y',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.14 0.58 0.8 0.10],...
    'CallBack', {@ModelPLSDA});
%hTextScoreZaxis =
uicontrol(...
    'Parent',hRunModel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.34 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','Z');   
hScore_PLSDA_Model_Z=uicontrol(...
    'Parent',hRunModel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',3,...
    'TooltipString','Score ploted in axes Z',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.14 0.34 0.8 0.1 ],...
    'Enable','off',...
    'CallBack', {@ModelPLSDA});
%hTextUse3dimention=
uicontrol(...
    'Parent',hRunModel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.14 0.12 0.42 0.1],...
    'horizontalalignment','l',...
    'FontWeight','bold',...
    'FontSize',9.3,...
    'BackgroundColor',[1 1 1],...
    'String','Enable Z axis');
hCheckUse3D_PLSDA = uicontrol(...
    'Parent',hRunModel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Principal Components ploted in axes Z',...
    'Position',[0.05 0.12 0.07 0.12],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableZaxis_PLSDA_Callback});

%---------- Processing Panel
hProcModel=uipanel(...
    'Parent',hModelPLSDA,...
    'Units','normalized',...            
    'Title','Processing',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.533 1 0.207],... 
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethod_Processing=
uicontrol(...
    'Parent',hProcModel,...
    'Style','text',...
    'String','Pre-processing Samples',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.73 0.4 0.20]);  
hProcessing_PLSDA_Model_s = uicontrol(...
    'Parent',hProcModel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the processing method for PLS-DA',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'mean|auto|pareto',...
    'Position',[0.55 0.78 0.4 0.15],...
    'Enable','on',...
    'CallBack', @ModelPLSDA);
%hComponents=
uicontrol(...
    'Parent',hProcModel,...
    'Style','text',...
    'String','Components',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.50 0.4 0.15],...
    'CallBack', @ModelPLSDA); 
hEditFactorsModelPLSDA=uicontrol(...
    'Parent',hProcModel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Number of components',...
    'String','4',...
    'Units','Normalized',...
    'Position',[0.55 0.55 0.4 0.15],...
    'CallBack', @ModelPLSDA);
%hConfidence=
uicontrol(...
    'Parent',hProcModel,...
    'Style','text',...
    'String','Confidence value',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.28 0.4 0.15]);  
hEditConfidenceModel=uicontrol(...
    'Parent',hProcModel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String','0.95',...
    'Units','Normalized',...
    'Position',[0.55 0.32 0.4 0.15],...
    'CallBack', @ModelPLSDA); %#ok<*NASGU> 
%hVariable Selec PLSDA=
uicontrol(...
    'Parent',hProcModel,...
    'Style','text',...
    'String','Variable selection',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.07 0.4 0.15]);  
hVariables_PLSDA_Model_s = uicontrol(...
    'Parent',hProcModel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the processing method for PLS-DA',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'none|iPLS|biPLS',...
    'Position',[0.55 0.09 0.4 0.15],...
    'Enable','on',...
    'CallBack', @ModelPLSDA);

%---------- Cal & Val plot "panel"
hCalValGroup_pls=uibuttongroup(...
    'Parent',hModelPLSDA,...
    'Title','Analysis Cal/Val',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'Position',[0.0 0.38 1 0.15]);

hRadioCalPLSDA = uicontrol(...
    'Parent',hCalValGroup_pls,...
    'Style','RadioButton',...
    'BackgroundColor',[1 1 1],...
    'String','Calibration',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.65 0.7 0.3],...
    'CallBack', @ModelPLSDA);
hRadioValPLSDA = uicontrol(...
    'Parent',hCalValGroup_pls,...
    'Style','RadioButton',...
    'BackgroundColor',[1 1 1],...
    'String','Validation',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.35 0.7 0.3],...
    'CallBack', @ModelPLSDA);
hRadioCalValPLSDA = uicontrol(...
    'Parent',hCalValGroup_pls,...
    'Style','RadioButton',...
    'BackgroundColor',[1 1 1],...
    'String','Calibration and Validation',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.05 0.7 0.3],...
    'CallBack', @ModelPLSDA);
%hMethod_Processing=
uicontrol(...
    'Parent',hCalValGroup_pls,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.55 0.70 0.4 0.2],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...
    'String','Classes');   
hRunClasses_PLSDA = uicontrol(...
    'Parent',hCalValGroup_pls,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',1,...
    'TooltipString','Target class for discrimination plot',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.55 0.6 0.4 0.09],...
    'Enable','on',...
    'CallBack', {@ModelPLSDA});

%---------- Visual Panel
OptionsPlotPanel_pls=uipanel(...
    'Parent',hModelPLSDA,...
    'Units','normalized',...            
    'Title','Visual Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.29 1 0.09],...  0,0.292429792429794,1,0.074481074481073
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hCheckLabels_pls = uicontrol(...
    'Parent',OptionsPlotPanel_pls,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Labels',...
    'FontSize',9.3,...
    'FontWeight','bold',...
    'Position',[0.05 0.52 0.29 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableLabel_Callback});
hCheckLegend_pls = uicontrol(...
    'Parent',OptionsPlotPanel_pls,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Legend',...
    'FontSize',9.3,...
    'FontWeight','bold',...    
    'Position',[0.05 0.12 0.40 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableLegend_Callback});
hCheckEllipse_pls = uicontrol(...
    'Parent',OptionsPlotPanel_pls,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Class Ellipse',...
    'FontSize',9.3,...
    'FontWeight','bold',...    
    'Position',[0.50 0.52 0.49 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableEllipse_Callback});

%---------- Export Data Panel
ExportPanel=uipanel(...
    'Parent',hModelPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.17 1 0.12],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

% hExportData = 
uicontrol(...
    'parent',ExportPanel,...
    'style','PushButton',...
    'String','Export PLSDA Info',...
    'Units','Normalized',...
    'TooltipString','Export info of PLSDA analysis to a file',...
    'Position',[0.02 0.49 0.47 0.44],...
    'Callback',{ @ExportInfo});   
% hExportData = 
uicontrol(...
    'parent',ExportPanel,...
    'style','PushButton',...
    'String','Export PLSDA Data',...
    'Units','Normalized',...
    'TooltipString','Export data of PLSDA analysis to a file',...
    'Position',[0.51 0.49 0.47 0.44],...
    'Callback',{ @ExportData});    
% hExportFigures = 
uicontrol(...
    'parent',ExportPanel,...
    'style','PushButton',...
    'String','Export Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.02 0.03 0.47 0.44],...
    'Callback',{ @ExportFigure});    
% hSaveModel = 
uicontrol(...
    'parent',ExportPanel,...
    'style','PushButton',...
    'String','Save Model',...
    'Units','Normalized',...
    'TooltipString','Save Model in a .m file',...
    'Position',[0.51,0.03,0.47,0.44],...
    'Callback',{ @ExportModel});  

%---------- Info Panel
hMessagesPanel_PLSDA=uipanel(...
    'Parent',hModelPLSDA,...
    'Title','Info',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0 1 0.17]);
hTextTest=uicontrol(...
    'Parent',hMessagesPanel_PLSDA,...
    'Style','edit',...
    'String','',...
    'Max',2,...
    'Enable','Off',...
    'Tag','MessageText',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.0 0.15 1 0.85],...
    'horizontalalignment','l');
set(hTextTest,'String',GUIData.MessageText)

%---------- hSaveLogfileButton = 
uicontrol(...
    'Parent',hMessagesPanel_PLSDA,...
    'Style','PushButton',...
    'String','Save logfile',...
    'Units','normalized',...
    'TooltipString','Save the logfile',...
    'Position',[0.3 0.01 0.4 0.13],...
    'Callback', { @SaveLogfile_Callback});

%% ----------------- Score plot Tab
%---------- Model Construction Main panel
hModelPLSDA_Axes=uipanel(...
    'Parent',hTabScorePLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Axis Panel
hAxesScorePLSDA = axes(...
    'Parent',hModelPLSDA_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65

%% ----------------- Loading plot Tab
%---------- Model Construction Main panel
hModelPLSDA_L_Axes=uipanel(...
    'Parent',hTabLoadingPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Axis Panel
hAxesLoadingPLSDA = axes(...
    'Parent',hModelPLSDA_L_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65

%% ----------------- VIP Tab
%---------- Plot Construction Main panel
hVIPPLSDA_Axes=uipanel(...
    'Parent',hTabVIPPlot,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.0 1 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Model Construction Main Axes
hAxesVIPPLSDA = axes(...
    'Parent',hVIPPLSDA_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','axDisc',...
    'title','Discrimination Model',...
    'Position',[0.11 0.2 0.85 0.65]);

%hSpecVIP=
uicontrol(...
    'Parent',hTabVIPPlot,...
    'Style','text',...
    'String','Average Spectra',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.1,0.04,0.2,0.04]); 
hCheckSpecVIP = uicontrol(...
    'Parent',hTabVIPPlot,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'Position',[0.25 0.035 0.1 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@ModelPLSDA});

%LoadingVIP=
uicontrol(...
    'Parent',hTabVIPPlot,...
    'Style','text',...
    'String','Loading',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.4,0.04,0.2,0.04]); 
hCheckLoadingVIP = uicontrol(...
    'Parent',hTabVIPPlot,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'Position',[0.55 0.035 0.1 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@ModelPLSDA});

%---------- Table Construction Main panel
hVIPPLSDA_Table=uipanel(...
    'Parent',hTabVIPTable,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.0 1 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%nConfMatrixTxt=
uicontrol(...
    'Parent',hVIPPLSDA_Table,...
    'Style','text',...
    'String',['VIP results for ' method ' model above the threshold'],...
    'Units','Normalized',...
    'FontSize',12,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01,0.95,0.64,0.045]); 
nVIPTablePpm=uitable(...
    'Parent',hVIPPLSDA_Table,...
    'Units','Normalized',...
    'Data',[],...
    'ColumnWidth',{75},...
    'ColumnName',{'Number','Chemical Shift','VIP Score'},...
    'RowName',{},...
    'Position',[0.01,0.01,0.98,0.94]);

%% ----------------- Permutation Tab
%---------- Model Construction Main panel
hPermutPLSDA_Axes=uipanel(...
    'Parent',hTabPermutPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Model Construction Main Axes
hAxesPermPLSDA = axes(...
    'Parent',hPermutPLSDA_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','axPermut',...
    'title','Discrimination Model',...
    'Position',[0.11 0.1 0.85 0.65]); %0.11 0.2 0.85 0.65

%nPermNumber=
uicontrol(...
    'Parent',hTabPermutPLSDA,...
    'Style','text',...
    'String','Number of permutations',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.36,0.90,0.1,0.04],...
    'CallBack', @permtest); 
hEditPermutModelPLSDA=uicontrol(...
    'Parent',hTabPermutPLSDA,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Number of permutations',...
    'String','100',...
    'Units','Normalized',...
    'Position',[0.47,0.90,0.1,0.04],...
    'CallBack', @permtest);

%nPermNumber=
uicontrol(...
    'Parent',hTabPermutPLSDA,...
    'Style','text',...
    'String','Use Parallel Computing Toolbox',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.65,0.90,0.1,0.04],...
    'CallBack', @permtest); 
hCheckParPerm = uicontrol(...
    'Parent',hTabPermutPLSDA,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',0,...
    'Position',[0.75 0.90 0.1 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on');

%% ----------------- Discrimination Tab
%---------- Model Construction Main panel
hDiscriminationPLSDA_Axes=uipanel(...
    'Parent',hTabAxesPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Model Construction Main Axes
hAxesDiscPLSDA = axes(...
    'Parent',hDiscriminationPLSDA_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','axDisc',...
    'title','Discrimination Model',...
    'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65

%% ----------------- Roc Curves Tab
%---------- Model Construction Main panel
hROCPLSDA=uipanel(...
    'Parent',hTabROCPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
% %---------- Axis Roc Curves Panel
AxesROC_PLSDA = axes(...
    'Parent',hROCPLSDA,...
    'Units','normalized',...
    'Visible','off',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.0 0.11 0.99 0.8]); %0.11 0.2 0.85 0.65

%% ----------------- Confusion Matrix Tab 
%---------- Model Construction Main panel
hMeasurePLSDA=uipanel(...
    'Parent',hTabConfMatPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%nConfMatrixTxt=
uicontrol(...
    'Parent',hMeasurePLSDA,...
    'Style','text',...
    'String',['Model: ' method],...
    'Units','Normalized',...
    'FontSize',12,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01,0.95,0.3,0.045]); 
%nConfMatrixTxt=
uicontrol(...
    'Parent',hMeasurePLSDA,...
    'Style','text',...
    'String','Confusion Matrix:',...
    'Units','Normalized',...
    'FontSize',12,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01,0.90,0.3,0.045]); 

nConfMatrixTxt=uitable(...
    'Parent',hMeasurePLSDA,...
    'Data',[],...
    'ColumnWidth',{75},...
    'ColumnName',{'TPR','FPR','TNR','FNR','Prediction'},...
    'RowName',{},...
    'Position',[7.6,458.2,586.9,135.8]);

%nConfTableTxt=
uicontrol(...
    'Parent',hMeasurePLSDA,...
    'Style','text',...
    'String','Confusion Table:',...
    'FontSize',12,...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01,0.63,0.3,0.045]); 

nConfTableTxt=uitable(...
    'Parent',hMeasurePLSDA,...
    'Data',[],...
    'ColumnWidth',{75},...
    'ColumnName',{'TPR','FPR','TNR','FNR','Acuracy','Prediction'},...
    'RowName',{},...
    'Position',[7.6,275,586.9,135.8]);

%nExplainedVarianceTxt=
uicontrol(...
    'Parent',hMeasurePLSDA,...
    'Style','text',...
    'String','Explained Variance:',...
    'Units','Normalized',...
    'FontSize',12,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01,0.35,0.3,0.045]); 

%---------- Tab explaned variance
hTableEigenvalues = uitable(...
    'parent',hMeasurePLSDA,...
    'units','normalized',...
    'columneditable',[true true true true],...
    'columnname',{' Eigenvalue ','   Explained Variance (%)   ','   Cumulative Variance (%)   '},...
    'columnformat',{'numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.01 0 1 0.35],...
    'Data',zeros(6,4));


%% ----------- Tab Cross-Validation
hTabCrossValidation=uitab(...
    'Parent',[],...
    'Title','Cross-Validation',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupPLSDA_CV=uitabgroup(...
    'Parent',hTabCrossValidation,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangeTabCallback,...
    'Position',[0.27 0.0 0.73 1]);
hTabSplitCV=uitab(...
    'Parent',hTabGroupPLSDA_CV,...
    'Title','Splits',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hResiduals=uitab(...
    'Parent',hTabGroupPLSDA_CV,...
    'Title','Residuals',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hConfusionMatrix=uitab(...
    'Parent',[],...
    'Title','Confusion Matrix',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized'); 

%% ----------------- Options Panel (left)

%---------- Cross Validation Main panel
OptionsCVPanel=uipanel(...
    'Parent',hTabCrossValidation,...
    'Units','normalized',...           
    'Position',[0.0 0.0 0.27 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%---------- Parameters Panel
hCrossVAlPanel=uipanel(...
    'Parent',OptionsCVPanel,...
    'Units','normalized',...            
    'Title','Parameters',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.51 1 0.49],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethodCV=
uicontrol(...
    'Parent',hCrossVAlPanel,...
    'Style','text',...
    'String','Method',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.27 0.93 0.28 0.07]);  
hMethodCV = uicontrol(...
    'Parent',hCrossVAlPanel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8.3,...
    'HorizontalAlignment','center',...
    'String',...
    'K-fold|Leane-One-Out|Contiguous Block|Monte Carlo',...
    'Position',[0.07 0.85 0.58 0.10],...
    'CallBack', {@MethodCheck_CV_Callback});
%hMethodCV_Results=
uicontrol(...
    'Parent',hCrossVAlPanel,...
    'Style','text',...
    'String','Shuffle',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.78 0.86 0.2 0.09]);  
hCheckshuffle = uicontrol(...
    'Parent',hCrossVAlPanel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',0,...
    'Position',[0.7 0.89 0.07 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on');

%--- max LV
hLVsPanelPLS=uipanel(...
    'Parent',hCrossVAlPanel,...
    'Units','normalized',...            
    'Title','Max N° LVs',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.62 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hLeftLV=
uicontrol(...
    'Parent',hLVsPanelPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
%hRightLV=
uicontrol(...
    'Parent',hLVsPanelPLS,...
    'Style','text',...
    'String','20',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditCVLVPLS=uicontrol(...
    'Parent',hLVsPanelPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of groups to use in the Cross-Validation model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditMaxLV_Callback});    
hSliderCVPLS=uicontrol(...
    'Parent',hLVsPanelPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',20, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 10,...
    'SliderStep',[1/19 1/19], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderCVGroup_Callback});

%--- Fold
hFoldPanelPLS=uipanel(...
    'Parent',hCrossVAlPanel,...
    'Units','normalized',...            
    'Title','Fold',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
hLeftFold=uicontrol(...
    'Parent',hFoldPanelPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightFold=uicontrol(...
    'Parent',hFoldPanelPLS,...
    'Style','text',...
    'String',[],...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.86 0.09 0.12 0.28]); 
hEditCVFoldPLS=uicontrol(... 
    'Parent',hFoldPanelPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of folds to use in the CV model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'Enable','on',...
    'CallBack', {@EditFold_Callback});
hSliderFoldCVPLS=uicontrol(...
    'Parent',hFoldPanelPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',5, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 1,...
    'SliderStep',[1/10 1/10], ...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@SliderFold_Callback});

%--- Division
hDivisionPanelPLS=uipanel(...
    'Parent',hCrossVAlPanel,...
    'Units','normalized',...            
    'Title','Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.12 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hLeftDivision=uicontrol(...
    'Parent',hDivisionPanelPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightDivision=uicontrol(...
    'Parent',hDivisionPanelPLS,...
    'Style','text',...
    'String','100',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditDivPLS=uicontrol(...
    'Parent',hDivisionPanelPLS,...
    'Style','edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Percentage of samples to use in the CV model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditPercIn_Callback});
hSliderDivCVPLS=uicontrol(...
    'Parent',hDivisionPanelPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',100, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 70,...
    'SliderStep',[1/99 1/99], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderSliderDiv_Callback});

%----------------------------------------------------
hCVApply = uicontrol(...
    'parent',hCrossVAlPanel,...
    'style','PushButton',...
    'String','Apply',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.022 0.01 0.45 0.10],...
    'Callback',{@CVApply_Callback}); 
hCVRun = uicontrol(...
    'parent',hCrossVAlPanel,...
    'style','PushButton',...
    'String','Run',...
    'Units','Normalized',...
    'TooltipString','Test with curent Cross-Validation parameters',...
    'Enable','off',...
    'Position',[0.52 0.01 0.45 0.10],...
    'Callback',{@CVRun_Callback});

%---------- Visual Panel (Results)
hVisualPanelResults=uipanel(...
    'Parent',OptionsCVPanel,...
    'Units','normalized',...            
    'Title','Visual Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.31 1 0.20],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hMethodCV_Results=
uicontrol(...
    'Parent',hVisualPanelResults,...
    'Style','text',...
    'String','Class',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'FontSize',10,...
    'BackgroundColor',[1 1 1],...
    'Position',[0.06 0.69 0.25 0.2]);  
hMethodCV_Class = uicontrol(...
    'Parent',hVisualPanelResults,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8,...
    'HorizontalAlignment','center',...
    'String',...
    '|',...
    'Position',[0.35 0.85 0.57 0.09],...
    'Enable','off',...
    'CallBack', {@Classes_RMSECV_Callback});

%hTextLabels=
uicontrol(...
    'Parent',hVisualPanelResults,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.19 0.37 0.37 0.21],...
    'FontSize',10,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'String','All Classes');
hCheckLabelsAllClasses = uicontrol(...
    'Parent',hVisualPanelResults,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'Position',[0.06 0.4 0.1 0.2],...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...    
    'Callback',{@Classes_RMSECV_Callback});

%hTextLabels=
uicontrol(...
    'Parent',hVisualPanelResults,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.19 0.07 0.37 0.21],...
    'FontSize',10,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'String','Labels');
hCheckLabelsLabels = uicontrol(...
    'Parent',hVisualPanelResults,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','r',...
    'TooltipString',...
    'Labels for each point',...
    'Value',0,...
    'Position',[0.06 0.1 0.1 0.2],...
    'BackgroundColor',[1 1 1],...
    'Enable','off',...    
    'Callback',{@EnableLabel_Callback});

%---------- Visual Panel (Outlier Detection)
hVisualPanelOutlier=uipanel(...
    'Parent',OptionsCVPanel,...
    'Units','normalized',...            
    'Title','Outlier Detection',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.31 1 0.20],...
    'BackgroundColor',[1 1 1],...
    'Visible','off');
%hMethodCV_Results=
uicontrol(...
    'Parent',hVisualPanelOutlier,...
    'Style','text',...
    'String','PLS Components',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'FontSize',9,...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01 0.43 0.52 0.20]);
hOutliersCV_Results = uicontrol(...
    'Parent',hVisualPanelOutlier,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8,...
    'HorizontalAlignment','center',...
    'String',...
    '|',...
    'Position',[0.57 0.42 0.40 0.25],...
    'Enable','off',...
    'CallBack', {@PLS_Tables_Callback});

%---------- Visual Panel (Confusion Matrix)
hVisualPanelConfusion=uipanel(...
    'Parent',OptionsCVPanel,...
    'Units','normalized',...            
    'Title','N° of PLS Components',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.31 1 0.20],...
    'BackgroundColor',[1 1 1],...
    'Visible','off');
%hMethodCV_Results=
uicontrol(...
    'Parent',hVisualPanelConfusion,...
    'Style','text',...
    'String','PLS Components',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'FontSize',9,...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01 0.43 0.52 0.20]);  
hConfusion_PLS = uicontrol(...
    'Parent',hVisualPanelConfusion,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8,...
    'HorizontalAlignment','center',...
    'String',...
    '|',...
    'Position',[0.57 0.42 0.40 0.25],...
    'Enable','off',...
    'CallBack', {@PLS_Tables_Callback});

%---------- Export Data Panel
OptionsExportPLSDAPanel=uipanel(...
    'Parent',OptionsCVPanel,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.23 1 0.08],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hExportData = uicontrol(...
    'parent',OptionsExportPLSDAPanel,...
    'style','PushButton',...
    'String','Export Table',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.022 0.1 0.45 0.70],...
    'Callback',{ @ExportData});    
hExportFigures = uicontrol(...
    'parent',OptionsExportPLSDAPanel,...
    'style','PushButton',...
    'String','Export CV Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.52 0.1 0.45 0.70],...
    'Callback',{ @ExportFigure});    


%---------- Info Panel
hMessagesPanel=uipanel(...
    'Parent',OptionsCVPanel,...
    'Title','Info',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0 1 0.23]);
hTextTest=uicontrol(...
    'Parent',hMessagesPanel,...
    'Style','edit',...
    'String','',...
    'Max',2,...
    'Enable','Off',...
    'Tag','MessageText',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.0 0.15 1 0.85],...
    'horizontalalignment','l');
set(hTextTest,'String',GUIData.MessageText)

%---------- hSaveLogfileButton = 
uicontrol(...
    'Parent',hMessagesPanel,...
    'Style','PushButton',...
    'String','Save logfile',...
    'Units','normalized',...
    'TooltipString','Save the logfile',...
    'Position',[0.3 0.01 0.4 0.13],...
    'Callback', { @SaveLogfile_Callback});


%% ----------------- Splits Tab
AxesResultTab=uipanel(...
    'Parent',hTabSplitCV,...
    'Units','normalized',...   %'BorderType','none',...
    'Position',[0.0 0.0 1 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
AxesPLSDA = axes(...
    'Parent',AxesResultTab,...
    'Units','normalized',...
    'Visible','off',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.0 0.11 0.99 0.8]); %0.11 0.2 0.85 0.65
% ------Class Table Structure
hClassInfoTable = uitable(...
    'parent',AxesResultTab,...
    'units','normalized',...
    'columneditable',true,...
    'columnname',{'Sample','Class'},...
    'columnformat',{'numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{},...
    'ColumnFormat',{[],[],[],[]}, ...
    'Visible','on',...
    'position',[0.01 0.01 0.985 0.95]);

%% ----------------- Confusion Matrix Tab
%hFigures_of_MeritCV=
uicontrol(...
    'Parent',hConfusionMatrix,...
    'Style','text',...
    'String','Figures of Merit',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'FontSize',14,...
    'FontName','Goudy Old Style',...    
    'Position',[0.024 0.94 0.30 0.04]); 
hFigureMeritTable = uitable(...
    'parent',hConfusionMatrix,...
    'units','normalized',...
    'columneditable',[false true false false true],...
    'columnname',{' Sample ',' Class ','Calibration', 'Traning', 'Used'},...
    'columnformat',{'char','numeric','numeric','numeric','logical'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024 0.50 0.95 0.43],...
    'Data',zeros(1,5));

%hConfusionTable=
uicontrol(...
    'Parent',hConfusionMatrix,...
    'Style','text',...
    'String','Confusion Table',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'FontSize',14,...
    'FontName','Goudy Old Style',...
    'Position',[0.024 0.45 0.30 0.04]); 
hConfusionTable = uitable(...
    'parent',hConfusionMatrix,...
    'units','normalized',...
    'columneditable',[false true false false true],...
    'columnname',{' Sample ',' Class ','Calibration', 'Traning', 'Used'},...
    'columnformat',{'char','numeric','numeric','numeric','logical'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024 0.009 0.95 0.43],...
    'Data',zeros(1,5));

 
%% ----------------- Residuals Tab
AxesRMSECV = axes(...
    'Parent',hResiduals,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'Position',[0.11 0.2 0.85 0.65]);

%% ----------- Tab iPLS
hTab_iPLS_PLSDA=uitab(...
    'Parent',[],...
    'Title','iPLS',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupiPLS_PLSDA=uitabgroup(...
    'Parent',hTab_iPLS_PLSDA,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangeTabCallback,...
    'Position',[0.27 0.0 0.73 1]);
hTabResiduals_Intervals_iPLS=uitab(...
    'Parent',hTabGroupiPLS_PLSDA,...
    'Title','Residuals vs Intervals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabPredMeasure_iPLS=uitab(...
    'Parent',[],...
    'Title','Prediction',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hResiduals_iPLS=uitab(...
    'Parent',hTabGroupiPLS_PLSDA,...
    'Title','Residuals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hModelinfo_iPLS=uitab(...
    'Parent',hTabGroupiPLS_PLSDA,...
    'Title','Model info',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized'); 

%% ----------------- Residual vs Intervals Tab
AxesiPLS_residual = axes(...
    'Parent',hTabResiduals_Intervals_iPLS,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.08,0.09,0.90,0.84]); %0.11 0.2 0.85 0.65

%% ----------------- Residual Tab
AxesiPLS_residual_idx_Tab = axes(...
    'Parent',hResiduals_iPLS,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax1iPLS',...
    'Position',[0.08,0.55,0.90,0.39]); %0.11 0.2 0.85 0.65
AxesiPLS_residual_all_Tab = axes(...
    'Parent',hResiduals_iPLS,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax2iPLS',...
    'Position',[0.08,0.08,0.90,0.38]); %0.11 0.2 0.85 0.65
%% ----------------- Model info Tab
hTable_iPLS_intervals = uitable(...
    'parent',hModelinfo_iPLS,...
    'units','normalized',...
    'columneditable',[false true false false true],...
    'columnname',{'Interval','Start var.','End var.','Start ppm','End ppm','Number of vars.'},...
    'columnformat',{'numeric','numeric','numeric','numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024 0.009 0.937 0.95],...
    'Data',zeros(1,6));
%% ----------------- Options Panel (left)
Options_iPLS_Panel=uipanel(...
    'Parent',hTab_iPLS_PLSDA,...
    'Units','normalized',...            
    'Position',[0.0 0.0 0.27 1],...
    'BackgroundColor',[1 1 1],...
    'BorderType','none',...
    'Visible','on');

%---------- Cross-Validation 
hCrossVal_iPLS_Panel=uipanel(...
    'Parent',Options_iPLS_Panel,...
    'Units','normalized',...            
    'Title','Parameters',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.51 1 0.49],...
    'BackgroundColor',[1 1 1],...
    'BorderType','etchedin',...
    'Visible','on');

%hMethodCViPLS=
uicontrol(...
    'Parent',hCrossVal_iPLS_Panel,...
    'Style','text',...
    'String','Method',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.27 0.93 0.28 0.07]);  
hMethodiPLS = uicontrol(...
    'Parent',hCrossVal_iPLS_Panel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8.3,...
    'HorizontalAlignment','center',...
    'String',...
    'K-fold|Leane-One-Out|Contiguous Block|Monte Carlo',...
    'Position',[0.07 0.85 0.58 0.10],...
    'CallBack', {@MethodCheck_iPLS_Callback});
%hMethodCV_Results=
uicontrol(...
    'Parent',hCrossVal_iPLS_Panel,...
    'Style','text',...
    'String','shuffle',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'FontSize',10,...
    'BackgroundColor',[1 1 1],...
    'Position',[0.78 0.86 0.2 0.09]);  
hCheckshuffleiPLS = uicontrol(...
    'Parent',hCrossVal_iPLS_Panel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',0,...
    'Position',[0.7 0.89 0.07 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on');

%--- max LV
hLVsPanelPLS_iPLS=uipanel(...
    'Parent',hCrossVal_iPLS_Panel,...
    'Units','normalized',...            
    'Title','Max N° LVs',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.62 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hLeftLV=
uicontrol(...
    'Parent',hLVsPanelPLS_iPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
%hRightLV=
uicontrol(...
    'Parent',hLVsPanelPLS_iPLS,...
    'Style','text',...
    'String','20',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditCVGroupiPLS=uicontrol(...
    'Parent',hLVsPanelPLS_iPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of LV to use in the iPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditMaxLV_Callback});    
hSliderLViPLS=uicontrol(...
    'Parent',hLVsPanelPLS_iPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',20, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 10,...
    'SliderStep',[1/19 1/19], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderCVGroup_Callback});

%--- Fold
hFoldPanelPLS_iPLS=uipanel(...
    'Parent',hCrossVal_iPLS_Panel,...
    'Units','normalized',...            
    'Title','Fold',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');   
hLeftFoldPLSiPLS=uicontrol(...
    'Parent',hFoldPanelPLS_iPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightFoldPLSiPLS=uicontrol(...
    'Parent',hFoldPanelPLS_iPLS,...
    'Style','text',...
    'String',[],...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.86 0.09 0.12 0.28]); 
hEditFoldiPLS=uicontrol(...
    'Parent',hFoldPanelPLS_iPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of folds to use in the iPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'Enable','on',...
    'CallBack', {@EditFold_Callback});
hSliderFold=uicontrol(...
    'Parent',hFoldPanelPLS_iPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',5, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 1,...
    'SliderStep',[1/10 1/10], ...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@SliderFold_Callback});

%--- Division
hDivisionPanelPLS_iPLS=uipanel(...
    'Parent',hCrossVal_iPLS_Panel,...
    'Units','normalized',...            
    'Title','Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.12 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hLeftDivisioniPLS=uicontrol(...
    'Parent',hDivisionPanelPLS_iPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightDivisioniPLS=uicontrol(...
    'Parent',hDivisionPanelPLS_iPLS,...
    'Style','text',...
    'String','100',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditDiviPLS=uicontrol(...
    'Parent',hDivisionPanelPLS_iPLS,...
    'Style','edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of samples to use in the iPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditPercIn_Callback});
hSliderDiviPLS=uicontrol(...
    'Parent',hDivisionPanelPLS_iPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',100, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 70,...
    'SliderStep',[1/99 1/99], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderSliderDiv_Callback});

%---------- Spectral Division Panel
hSpecDiv_iPLS_Panel=uipanel(...
    'Parent',Options_iPLS_Panel,...
    'Units','normalized',...            
    'Title','Spectral Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.193],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethodCV_Results=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','text',...
    'String','Pre-processing',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.73 0.4 0.20]);  
hiPLSprocess = uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'mean|auto|msc mean|msc auto',...
    'Position',[0.55 0.78 0.4 0.15],...
    'Enable','on');
%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.51 0.4 0.15],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Intervals:' );
hEditIntervals_iPLS=uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',20,...
    'Units','Normalized',...
    'Position',[0.55 0.55 0.4 0.15]); 
%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.29 0.4 0.15],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Segments:' );
hEditSegments_iPLS=uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',5,...
    'Units','Normalized',...
    'Position',[0.55 0.32 0.4 0.15]); 
%hCheckBinPCA=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','text',...
    'String','External Limits',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.07 0.4 0.15]);  
hBinCheck = uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Import limits directly from the Bin GUI',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String','None|Binning',...
    'Position',[0.55 0.09 0.4 0.15],...
    'Enable','on',...
    'Callback',{@iPLS_Apply_Callback});


% hCheckimportBin_iPLS = uicontrol(...
%     'Parent',hCrossVal_iPLS_Panel,...
%     'Style','Checkbox',...
%     'Units','normalized',...
%     'horizontalalignment','l',...
%     'TooltipString', 'Import limits directly from the Bin GUI',...
%     'Labels for each point',...
%     'Value',0,...
%     'String','Import Bin limits',...
%     'Position',[0.085 0.883 0.067 0.034],...
%     'BackgroundColor',[1 1 1],...
%     'Enable','on',...
%     'Callback',{@iPLS_Run_Callback});

%---------- Run iPLS & Export Data Panel
Export_iPLS_Panel=uipanel(...
    'Parent',Options_iPLS_Panel,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0 0.23 1 0.14],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hExport_iPLSData = uicontrol(...
    'parent',Export_iPLS_Panel,...
    'style','PushButton',...
    'String','Export Table',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.03 0.5 0.45 0.42],...
    'Callback',{@ExportData});    
hExport_iPLSFigures = uicontrol(...
    'parent',Export_iPLS_Panel,...
    'style','PushButton',...
    'String','Export iPLS Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.52 0.5 0.45 0.42],...
    'Callback',{@ExportFigure});    

h_iPLS_Apply = uicontrol(...
    'parent',Export_iPLS_Panel,...
    'style','PushButton',...
    'String','Apply',...
    'Units','Normalized',...
    'TooltipString','',...
    'Position',[0.03 0.07 0.45 0.42],...
    'Callback',{@iPLS_Apply_Callback}); 
h_iPLS_Run = uicontrol(...
    'parent',Export_iPLS_Panel,...
    'style','PushButton',...
    'String','Run',...
    'Units','Normalized',...
    'TooltipString','',...
    'Enable','off',...
    'Position',[0.52 0.07 0.45 0.42],...
    'Callback',{@iPLS_Run_Callback});

%---------- Tips for user
hTipsiPLS=uipanel(...
    'Parent',Options_iPLS_Panel,...
    'Title','Tips',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...    
    'Position',[0.0 0 1 0.23]);
%hTextStart=
uicontrol(...
    'Parent',hTipsiPLS,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.0 0.15 1 0.85],...
    'BackgroundColor',[1 1 1],...    
    'horizontalalignment','left',...
    'String','Note that the iPLS approach differs from the so-called binning method for data reduction. The segmentation step in iPLS is not a reduction of the number of variables; it is merely a technique to obtain an overview of a large number of (possibly diverse) variables' ); 

%% ----------- Tab biPLS
hTab_biPLS_PLSDA=uitab(...
    'Parent',[],...
    'Title','biPLS',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupbiPLS_PLSDA=uitabgroup(...
    'Parent',hTab_biPLS_PLSDA,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangeTab_biPLS_Callback,...
    'Position',[0.27 0.0 0.73 1]);
hModelinfo_biPLS=uitab(...
    'Parent',hTabGroupbiPLS_PLSDA,...
    'Title','Model info',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hResiduals_biPLS=uitab(...
    'Parent',hTabGroupbiPLS_PLSDA,...
    'Title','Residuals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabResiduals_Intervals_biPLS=uitab(...
    'Parent',[],...
    'Title','Residuals vs Intervals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabPredMeasure_biPLS=uitab(...
    'Parent',hTabGroupbiPLS_PLSDA,...
    'Title','Prediction',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');

 

%% ----------------- Residual vs Intervals Tab
Axes_biPLS_residual = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.08,0.09,0.90,0.84]); %0.11 0.2 0.85 0.65

%% ----------------- Prediction Tab
AxesbiPLS_Interval = axes(...
    'Parent',hTabPredMeasure_biPLS,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax1',...
    'Position',[0.08,0.58,0.90,0.37]); %0.11 0.2 0.85 0.65
AxesbiPLS_Predic = axes(...
    'Parent',hTabPredMeasure_biPLS,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax1',...
    'Position',[0.08,0.07,0.90,0.37]); %0.11 0.2 0.85 0.65

%% ----------------- Residual Tab
AxesbiPLS_RMSE = axes(...
    'Parent',hResiduals_biPLS,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','axbiPLSresidual',...
    'Position',[0.08,0.09,0.90,0.84]); %0.11 0.2 0.85 0.65

%% ----------------- Model info Tab
%hinfoInterval_biPLS=
uicontrol(...
    'Parent',hModelinfo_biPLS,...
    'Style','text',...
    'String','Outliers',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'FontSize',14,...
    'FontName','Goudy Old Style',...    
    'Position',[0.024 0.32 0.30 0.04]); 
hinfoInterval_biPLS = uitable(...
    'parent',hModelinfo_biPLS,...
    'units','normalized',...
    'columneditable',[false true false false],...
    'columnname',{' Number ',' Interval ','RMSE', 'Number of Variables'},...
    'columnformat',{'numeric','numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024,0.009,0.937,0.95],...
    'Data',zeros(1,5));
%% ----------------- Options Panel (left)
Options_biPLS_Panel=uipanel(...
    'Parent',hTab_biPLS_PLSDA,...
    'Units','normalized',...           
    'Position',[0.0 0.0 0.27 1],...
    'BackgroundColor',[1 1 1],...
    'BorderType','none',...
    'Visible','on');

%---------- Parameters Panel
hCrossVal_biPLS_Panel=uipanel(...
    'Parent',Options_biPLS_Panel,...
    'Units','normalized',...            
    'Title','Parameters',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.51 1 0.49],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethodCV_biPLS=
uicontrol(...
    'Parent',hCrossVal_biPLS_Panel,...
    'Style','text',...
    'String','Method',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.27 0.93 0.28 0.07]);  
hMethodbiPLS = uicontrol(...
    'Parent',hCrossVal_biPLS_Panel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8.3,...
    'HorizontalAlignment','center',...
    'String',...
    'K-fold|Leane-One-Out|Contiguous Block|Monte Carlo',...
    'Position',[0.07 0.85 0.58 0.10],...
    'CallBack', {@MethodCheck_biPLS_Callback});
%hMethodCV_Results=
uicontrol(...
    'Parent',hCrossVal_biPLS_Panel,...
    'Style','text',...
    'String','shuffle',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.78 0.86 0.2 0.09]);  
hCheckshufflebiPLS = uicontrol(...
    'Parent',hCrossVal_biPLS_Panel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString','',...
    'Value',0,...
    'Position',[0.7 0.89 0.07 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on');

%--- max LV
hLVsPanelPLS_biPLS=uipanel(...
    'Parent',hCrossVal_biPLS_Panel,...
    'Units','normalized',...            
    'Title','Max N° LVs',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.62 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hLeftLV=
uicontrol(...
    'Parent',hLVsPanelPLS_biPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
%hRightLV=
uicontrol(...
    'Parent',hLVsPanelPLS_biPLS,...
    'Style','text',...
    'String','20',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditCVGroupbiPLS=uicontrol(...
    'Parent',hLVsPanelPLS_biPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to use in the biPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditMaxLV_Callback});    
hSliderLVbiPLS=uicontrol(...
    'Parent',hLVsPanelPLS_biPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',20, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 10,...
    'SliderStep',[1/19 1/19], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderCVGroup_Callback});

%--- Fold
hFoldPanelPLS_biPLS=uipanel(...
    'Parent',hCrossVal_biPLS_Panel,...
    'Units','normalized',...            
    'Title','Fold',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');     
hLeftFoldPLSbiPLS=uicontrol(...
    'Parent',hFoldPanelPLS_biPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightFoldPLSbiPLS=uicontrol(...
    'Parent',hFoldPanelPLS_biPLS,...
    'Style','text',...
    'String',[],...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.86 0.09 0.12 0.28]); 
hEditFoldbiPLS=uicontrol(...
    'Parent',hFoldPanelPLS_biPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of folds to use in the CV model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'Enable','on',...
    'CallBack', {@EditFold_Callback});
hSliderFoldbiPLS=uicontrol(...
    'Parent',hFoldPanelPLS_biPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',5, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 1,...
    'SliderStep',[1/10 1/10], ...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@SliderFold_Callback});

%--- Division
hDivisionPanelPLS_biPLS=uipanel(...
    'Parent',hCrossVal_biPLS_Panel,...
    'Units','normalized',...            
    'Title','Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.12 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hLeftDivision=uicontrol(...
    'Parent',hDivisionPanelPLS_biPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightDivision=uicontrol(...
    'Parent',hDivisionPanelPLS_biPLS,...
    'Style','text',...
    'String','100',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditDivbiPLS=uicontrol(...
    'Parent',hDivisionPanelPLS_biPLS,...
    'Style','edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Percentage of samples to use in the CV model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditPercIn_Callback});
hSliderDivbiPLS=uicontrol(...
    'Parent',hDivisionPanelPLS_biPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',100, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 70,...
    'SliderStep',[1/99 1/99], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderSliderDiv_Callback});

%---------- Spectral Division Panel (Residuals vs Intervals)
hSpecDiv_biPLS_Panel=uipanel(...
    'Parent',Options_biPLS_Panel,...
    'Units','normalized',...            
    'Title','Spectral Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.35 1 0.217],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hMethodCV_Results=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','text',...
    'String','Pre-processing',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.69 0.4 0.2]);  
hbiPLSprocess = uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'mean|auto|msc mean|msc auto',...
    'Position',[0.55 0.85 0.4 0.09],...
    'Enable','on');

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.46 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Intervals:' );
hEditIntervals_biPLS=uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',20,...
    'Units','Normalized',...
    'Position',[0.35 0.51 0.3 0.2 ]); 

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.26 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Segments:' );
hEditSegments_biPLS=uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',5,...
    'Units','Normalized',...
    'Position',[0.35 0.30 0.3 0.2 ]); 

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.06 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Variables:' );
hEditVariables_biPLS=uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Use space to separate the desired variables',...
    'String',1,...
    'Units','Normalized',...
    'Enable','off',...
    'Position',[0.35 0.09 0.3 0.2 ]); 

mls = sprintf('%s\n%s','Variable','Selection');
%hTextUseVariables_biPLS=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.71 0.30 0.21 0.24],...
    'horizontalalignment','r',...
    'BackgroundColor',[1 1 1],...
    'String',mls);
hCheckUseVariables_biPLS = uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Enable you select which intervals the biPLS shoud use in its calculations',...
    'Position',[0.77 0.09 0.08 0.17],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableVariables_biPLS_Callback});

%---------- Spectral Division Panel (Prediction)
hSpecDiv_biPLS_Predic=uipanel(...
    'Parent',Options_biPLS_Panel,...
    'Units','normalized',...            
    'Title','Spectral Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.35 1 0.217],...
    'BackgroundColor',[1 1 1],...
    'Visible','off');

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Predic,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.46 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Latent Variables:' );
hEditLV_biPLS=uicontrol(...
    'Parent',hSpecDiv_biPLS_Predic,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','',...
    'String',10,...
    'Units','Normalized',...
    'Position',[0.35 0.51 0.3 0.2 ]); 
% 
% %hTextStart=
% uicontrol(...
%     'Parent',hSpecDiv_biPLS_Predic,...
%     'Style','text',...
%     'Units','Normalized',...
%     'Position',[0.05 0.06 0.3 0.2 ],...
%     'horizontalalignment','left',...
%     'BackgroundColor',[1 1 1],...    
%     'String','Variables:' );
% hEditVariables_biPLS=uicontrol(...
%     'Parent',hSpecDiv_biPLS_Predic,...
%     'Style','edit',...
%     'BackgroundColor','w',...
%     'TooltipString','Use space to separate the desired variables',...
%     'String',1,...
%     'Units','Normalized',...
%     'Enable','off',...
%     'Position',[0.35 0.09 0.3 0.2 ]); 

%---------- Run iPLS & Export Data Panel
Export_biPLS_Panel=uipanel(...
    'Parent',Options_biPLS_Panel,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0 0.207 1 0.14],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hExport_iPLSData = uicontrol(...
    'parent',Export_biPLS_Panel,...
    'style','PushButton',...
    'String','Export Table',...
    'Units','Normalized',...
    'TooltipString','Export data of iPLS analysis to a .txt file',...
    'Position',[0.03 0.5 0.45 0.42],...
    'Callback',{@ExportData});    
hExport_iPLSFigures = uicontrol(...
    'parent',Export_biPLS_Panel,...
    'style','PushButton',...
    'String','Export iPLS Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.52 0.5 0.45 0.42],...
    'Callback',{@ExportFigure});    

h_biPLS_Apply = uicontrol(...
    'parent',Export_biPLS_Panel,...
    'style','PushButton',...
    'String','Apply',...
    'Units','Normalized',...
    'TooltipString','',...
    'Position',[0.03 0.07 0.45 0.42],...
    'Callback',{@biPLS_Apply_Callback}); 
h_biPLS_Run = uicontrol(...
    'parent',Export_biPLS_Panel,...
    'style','PushButton',...
    'String','Run',...
    'Units','Normalized',...
    'TooltipString','',...
    'Enable','off',...
    'Position',[0.52 0.07 0.45 0.42],...
    'Callback',{@biPLS_Run_Callback});

%---------- Tips for user
hTipsbiPLS=uipanel(...
    'Parent',Options_biPLS_Panel,...
    'Title','Tips',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...    
    'Position',[0.0 0 1 0.205]);
%hTextStart=
uicontrol(...
    'Parent',hTipsbiPLS,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.0 0.15 1 0.85],...
    'BackgroundColor',[1 1 1],...    
    'horizontalalignment','left',...
    'String','Sample and/or measurement abnormalities (outliers) as detected by PLS inner relation plots should generally be removed prior to the application of iPLS/biPLS' ); 

%% ---------OPLS

%---------- Tab Construction
hTabModelOPLS=uitab(...
    'Parent',[],...
    'Title','Model',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');

%---------- Model Construction
hModelOPLS=uipanel(...
    'Parent',hTabModelOPLS,...
    'Units','normalized',...            
    'Title','Model',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.0 1 0.30],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');   
hRunModelOPLS=uipanel(...
    'Parent',hModelOPLS,...
    'Units','normalized',...            
    'Title','Process',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.5 0.26 0.50],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hRunButtonOPLS=uicontrol(...
    'Parent',hRunModelOPLS,...
    'Style','PushButton',...
    'String','Run',...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to use in the PCA model',...
    'Units','Normalized',...
    'Position',[0.31 0.37 0.34 0.37],...
    'CallBack', {@ModelOPLS}); 

hPlotModelOPLS=uipanel(...
    'Parent',hModelOPLS,...
    'Units','normalized',...            
    'Title','Model',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.265 0.5 0.26 0.50],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hRadioPlotsOPLS = uicontrol(...
    'Parent',hPlotModelOPLS,...
    'Style','RadioButton',...
    'String','Global',...
    'TooltipString','Control whether Scores or Loadings will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.65 0.5 0.3]);

hFactorsModelOPLS=uipanel(...
    'Parent',hModelOPLS,...
    'Units','normalized',...            
    'Title','Model',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.0 0.26 0.50],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hComponents=
uicontrol(...
    'Parent',hFactorsModelOPLS,...
    'Style','text',...
    'String','PLS components',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'Position',[0.08 0.58 0.31 0.19]);  
hEditFactorsModel=uicontrol(...
    'Parent',hFactorsModelOPLS,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String','4',...
    'Units','Normalized',...
    'Position',[0.46 0.56 0.26 0.27]); 
%hConfidence=
uicontrol(...
    'Parent',hFactorsModelOPLS,...
    'Style','text',...
    'String','Orthogonal components',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'Position',[0.08 0.17 0.31 0.19]);  
hEditOrthogonalModel=uicontrol(...
    'Parent',hFactorsModelOPLS,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','orthogonal components',...
    'String','1',...
    'Units','Normalized',...
    'Position',[0.46 0.17 0.26 0.27]); 

hCalValGroupOPLS=uibuttongroup(...
    'Parent',hModelOPLS,...
    'Title','Split Cal/Val',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.265 0.0 0.26 0.50]);
hRadioCal = uicontrol(...
    'Parent',hCalValGroupOPLS,...
    'Style','RadioButton',...
    'String','Calibration',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.65 0.7 0.3]);
hRadioVal = uicontrol(...
    'Parent',hCalValGroupOPLS,...
    'Style','RadioButton',...
    'String','Validation',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.35 0.7 0.3]);
hRadioCalVal = uicontrol(...
    'Parent',hCalValGroupOPLS,...
    'Style','RadioButton',...
    'String','Calibration and Validation',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.05 0.7 0.3]);

hTableEigenvaluesOPLS = uitable(...
    'parent',hModelOPLS,...
    'units','normalized',...
    'columneditable',[true true true true],...
    'columnname',{' Eigenvalue ','   Explained Variance (%)   ','   Cumulative Variance (%)   ','RMSECV'},...
    'columnformat',{'numeric','numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.53 0.0 0.465 1.0],...
    'Data',zeros(6,4));

%---------- Splits Tab
AxesModelTabOPLS=uipanel(...
    'Parent',hTabModelOPLS,...
    'Units','normalized',...   %'BorderType','none',...
    'Position',[0.0 0.3 1 0.70],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
AxesModelOPLS = axes(...
    'Parent',AxesModelTabOPLS,...
    'Units','normalized',...
    'Visible','off',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.0 0.11 0.99 0.8]); %0.11 0.2 0.85 0.65
%% ---------OPLSDA

%% ----------- Tab Model
hTabModelOPLSDA=uitab(...
    'Parent',[],...
    'Title','Model',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupOPLSDA=uitabgroup(...
    'Parent',hTabModelOPLSDA,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangingScoreOPLS_Callback,...
    'Position',[0.0 0.0 1 1]);
hTabScoreOPLSDA=uitab(...
    'Parent',hTabGroupOPLSDA,...
    'Title','Score Plots',...
    'TooltipString','Score Plot',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized'); 
hTabLoadingOPLSDA=uitab(...
    'Parent',hTabGroupOPLSDA,...
    'Title','Loadings Plots',...
    'TooltipString','Loadings',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized'); 
% hTabPermutOPLSDA=uitab(...
%     'Parent',hTabGroupOPLSDA,...
%     'Title','Score Plots',...
%     'TooltipString','Score Plot',...
%     'BackgroundColor',[1 1 1],...
%     'Units','Normalized'); 
hTabVIPOPLSDA=uitab(...
    'Parent',hTabGroupOPLSDA,...
    'Title','VIP Score',...
    'TooltipString','Discrimination',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabAxesOPLSDA=uitab(...
    'Parent',hTabGroupOPLSDA,...
    'Title','Discrimination',...
    'TooltipString','Discrimination',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabROCOPLSDA=uitab(...
    'Parent',hTabGroupOPLSDA,...
    'Title','ROC Curves',...
    'TooltipString','ROC Curves',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabMeasureOPLSDA=uitab(...
    'Parent',hTabGroupOPLSDA,...
    'Title','Measures Model',...
    'TooltipString','Explained Variance of the model',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');

%% ----------------- Control Panel (left)

%---------- Model Construction Main panel
hModelOPLSDA=uipanel(...
    'Parent',hTabModelOPLSDA,...
    'Units','normalized',...            
    'Position',[0.0,0.0,0.27,0.96],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');   

%---------- Plot Scores Panel
hRunModel_oplsda=uipanel(...
    'Parent',hModelOPLSDA,...
    'Units','normalized',...            
    'Title','Plot Scores Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.74 1 0.26],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%htextScoreXaxis =
uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Units','Normalized',...
    'Style','text',...
    'Position',[0.05 0.80 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','X');    
hScore_OPLSDA_Model_X=uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',1,...
    'TooltipString','Score ploted in axes X',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'BackgroundColor','w',...    
    'String',[],...
    'Position',[0.14 0.81 0.8 0.10],...
    'CallBack', {@ModelOPLSDA});
%htextScoreYaxis =
uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.57 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','Y');   
hScore_OPLSDA_Model_Y=uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',2,...
    'TooltipString','Score ploted in axes Y',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Enable','off',...
    'Position',[0.14 0.58 0.8 0.10],...
    'CallBack', {@ModelOPLSDA});
%hTextScoreZaxis =
uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.34 0.1 0.12],...
    'horizontalalignment','left',...
    'FontSize',13,...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...
    'String','Z');   
hScore_OPLSDA_Model_Z=uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',3,...
    'TooltipString','Score ploted in axes Z',...
    'FontWeight','normal',...
    'FontSize',8.5,...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.14 0.34 0.8 0.1 ],...
    'Enable','off',...
    'CallBack', {@ModelOPLSDA});
%hTextUse3dimention=
uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.14 0.12 0.42 0.1],...
    'horizontalalignment','l',...
    'FontWeight','bold',...
    'FontSize',9.3,...
    'BackgroundColor',[1 1 1],...
    'String','Enable Z axis');
hCheckUse3D_OPLSDA = uicontrol(...
    'Parent',hRunModel_oplsda,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Principal Components ploted in axes Z',...
    'Position',[0.05 0.12 0.07 0.12],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableZaxis_OPLSDA_Callback});

%---------- Processing Panel
hProcModel_oplsda=uipanel(...
    'Parent',hModelOPLSDA,...
    'Units','normalized',...            
    'Title','Processing',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.533 1 0.207],... 
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethod_Processing=
uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','text',...
    'String','Pre-processing Samples',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.73 0.4 0.20]);  
hProcessing_OPLSDA_Model_s = uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the processing method for OPLS-DA',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'mean|auto|pareto',...
    'Position',[0.55 0.78 0.4 0.15],...
    'Enable','on',...
    'CallBack', @ModelOPLSDA);
%hComponents=
uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','text',...
    'String','Components',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.50 0.4 0.15],...
    'CallBack', @ModelOPLSDA); 
hEditFactorsModelOPLSDA=uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Number of components',...
    'String','4',...
    'Units','Normalized',...
    'Position',[0.55 0.55 0.4 0.15],...
    'CallBack', @ModelOPLSDA);
%hConfidence=
uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','text',...
    'String','Confidence value',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.28 0.4 0.15]);  
hEditConfidenceModel_oplsda=uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String','0.95',...
    'Units','Normalized',...
    'Position',[0.55 0.32 0.4 0.15],...
    'CallBack', @ModelOPLSDA); 
% hVariable Selec OPLSDA=
uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','text',...
    'String','Variable selection',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.07 0.4 0.15]);  
hVariables_OPLSDA_Model_s = uicontrol(...
    'Parent',hProcModel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the processing method for OPLS-DA',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'none|iPLS|biPLS',...
    'Position',[0.55 0.09 0.4 0.15],...
    'Enable','on',...
    'CallBack', @ModelOPLSDA);

%---------- Cal & Val plot "panel"
hCalValGroup_oplsda=uibuttongroup(...
    'Parent',hModelOPLSDA,...
    'Title','Analysis Cal/Val',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'BackgroundColor',[1 1 1],...
    'Enable','off',...
    'Position',[0.0 0.38 1 0.15]);

hRadioCalOPLSDA = uicontrol(...
    'Parent',hCalValGroup_oplsda,...
    'Style','RadioButton',...
    'BackgroundColor',[1 1 1],...
    'String','Calibration',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.65 0.7 0.3],...
    'CallBack', @ModelOPLSDA);
hRadioValOPLSDA = uicontrol(...
    'Parent',hCalValGroup_oplsda,...
    'Style','RadioButton',...
    'BackgroundColor',[1 1 1],...
    'String','Validation',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.35 0.7 0.3],...
    'CallBack', @ModelOPLSDA);
hRadioCalValOPLSDA = uicontrol(...
    'Parent',hCalValGroup_oplsda,...
    'Style','RadioButton',...
    'BackgroundColor',[1 1 1],...
    'String','Calibration and Validation',...
    'TooltipString','Control whether Calibration and/or Validation will be shown in the graphs',...
    'Units','normalized',...
    'Position',[0.0 0.05 0.7 0.3],...
    'CallBack', @ModelOPLSDA);
%hMethod_Processing=
uicontrol(...
    'Parent',hCalValGroup_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.55 0.70 0.4 0.2],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...
    'String','Classes');   
hRunClasses_OPLSDA = uicontrol(...
    'Parent',hCalValGroup_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'value',1,...
    'TooltipString','Target class for orthogonal discrimination_plot',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',[],...
    'Position',[0.55 0.6 0.4 0.09],...
    'Enable','on',...
    'CallBack', {@ModelOPLSDA});

%---------- Visual Panel
OptionsPlotPanel_opls=uipanel(...
    'Parent',hModelOPLSDA,...
    'Units','normalized',...            
    'Title','Visual Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.29 1 0.09],... 
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hCheckLabels_opls = uicontrol(...
    'Parent',OptionsPlotPanel_opls,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Labels',...
    'FontSize',9.3,...
    'FontWeight','bold',...
    'Position',[0.05 0.52 0.29 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableLabel_Callback});
hCheckLegend_opls = uicontrol(...
    'Parent',OptionsPlotPanel_opls,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Legend',...
    'FontSize',9.3,...
    'FontWeight','bold',...    
    'Position',[0.05 0.12 0.40 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableLegend_Callback});
hCheckEllipse_opls = uicontrol(...
    'Parent',OptionsPlotPanel_opls,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'String','Class Ellipse',...
    'FontSize',9.3,...
    'FontWeight','bold',...    
    'Position',[0.50 0.52 0.49 0.4],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableEllipse_Callback});

%---------- Export Data Panel
ExportPanel_oplsda=uipanel(...
    'Parent',hModelOPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.17 1 0.12],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

hExportData_oplsda = uicontrol(...
    'parent',ExportPanel_oplsda,...
    'style','PushButton',...
    'String','Export OPLSDA Data',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.02 0.49 0.47 0.44],...
    'Callback',{ @ExportData_oplsda});    
hExportFigures_oplsda = uicontrol(...
    'parent',ExportPanel_oplsda,...
    'style','PushButton',...
    'String','Export OPLSDA Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.51 0.49 0.47 0.44],...
    'Callback',{ @ExportFigure});    
hSaveModel_oplsda = uicontrol(...
    'parent',ExportPanel_oplsda,...
    'style','PushButton',...
    'String','Save Model',...
    'Units','Normalized',...
    'TooltipString','Save Model in a m. file',...
    'Position',[0.02 0.03 0.47 0.44],...
    'Callback',{ @ExportModel_oplsda});  

%---------- Info Panel
hMessagesPanel_OPLSDA=uipanel(...
    'Parent',hModelOPLSDA,...
    'Title','Info',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0 1 0.17]);
hTextTest_oplsda=uicontrol(...
    'Parent',hMessagesPanel_OPLSDA,...
    'Style','edit',...
    'String','',...
    'Max',2,...
    'Enable','Off',...
    'Tag','MessageText',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.0 0.15 1 0.85],...
    'horizontalalignment','l');
set(hTextTest_oplsda,'String',GUIData.MessageText)

%---------- hSaveLogfileButton = 
uicontrol(...
    'Parent',hMessagesPanel_OPLSDA,...
    'Style','PushButton',...
    'String','Save logfile',...
    'Units','normalized',...
    'TooltipString','Save the logfile',...
    'Position',[0.3 0.01 0.4 0.13],...
    'Callback', { @SaveLogfile_Callback});

%% ----------------- Score plot Tab
%---------- Model Construction Main panel
hModelOPLSDA_Axes=uipanel(...
    'Parent',hTabScoreOPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Axis Panel
hAxesScoreOPLSDA = axes(...
    'Parent',hModelOPLSDA_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.11 0.2 0.85 0.65]); 
%% ----------------- Loading plot Tab
%---------- Model Construction Main panel
hModelOPLSDA_L_Axes=uipanel(...
    'Parent',hTabLoadingOPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Axis Panel
hAxesLoadingOPLSDA = axes(...
    'Parent',hModelOPLSDA_L_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65



%% ----------------- VIP Tab
%---------- Model Construction Main panel
hVIPOPLSDA_Axes=uipanel(...
    'Parent',hTabVIPOPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Model Construction Main Axes
hAxesVIPOPLSDA = axes(...
    'Parent',hVIPOPLSDA_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','axDisc',...
    'title','Discrimination Model',...
    'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65 

%% ----------------- Permutation Tab
% %---------- Model Construction Main panel
% hPermutOPLSDA_Axes=uipanel(...
%     'Parent',hTabPermutOPLSDA,...
%     'Units','normalized',...            
%     'Titleposition','centertop',...
%     'FontWeight','bold',...
%     'Position',[0.27 0.0 0.73 1],...
%     'BackgroundColor',[1 1 1],...
%     'Visible','on'); 
% %---------- Model Construction Main Axes
% hAxesPermOPLSDA = axes(...
%     'Parent',hPermutOPLSDA_Axes,...
%     'Units','normalized',...
%     'Visible','on',...
%     'Box','off',...
%     'tag','axPermut',...
%     'title','Discrimination Model',...
%     'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65
% 
% %nPermNumber=
% uicontrol(...
%     'Parent',hTabPermutOPLSDA,...
%     'Style','text',...
%     'String','Number of permutations',...
%     'Units','Normalized',...
%     'horizontalalignment','l',...
%     'BackgroundColor',[1 1 1],...
%     'Position',[0.36,0.90,0.1,0.04],...
%     'CallBack', @permtest); 
% hEditPermutModelOPLSDA=uicontrol(...
%     'Parent',hTabPermutOPLSDA,...
%     'Style','edit',...
%     'BackgroundColor','w',...
%     'TooltipString','Number of permutations',...
%     'String','100',...
%     'Units','Normalized',...
%     'Position',[0.47,0.90,0.1,0.04],...
%     'CallBack', @permtest);
% 
% %nPermNumber=
% uicontrol(...
%     'Parent',hTabPermutOPLSDA,...
%     'Style','text',...
%     'String','Use Parallel Computing Toolbox',...
%     'Units','Normalized',...
%     'horizontalalignment','l',...
%     'BackgroundColor',[1 1 1],...
%     'Position',[0.65,0.90,0.1,0.04],...
%     'CallBack', @permtest); 
% hCheckParPermOPLS = uicontrol(...
%     'Parent',hTabPermutOPLSDA,...
%     'Style','Checkbox',...
%     'Units','normalized',...
%     'horizontalalignment','l',...
%     'TooltipString',...
%     'Labels for each point',...
%     'Value',0,...
%     'Position',[0.75 0.90 0.1 0.07],...
%     'BackgroundColor',[1 1 1],...
%     'Enable','on');


%% ----------------- Discrimination Tab
%---------- Model Construction Main panel
hDiscriminationOPLSDA_Axes=uipanel(...
    'Parent',hTabAxesOPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Model Construction Main Axes
hAxesDiscOPLSDA = axes(...
    'Parent',hDiscriminationOPLSDA_Axes,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','axDisc',...
    'title','Discrimination Model',...
    'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65


%% ----------------- Roc Curves Tab
%---------- Model Construction Main panel
hROCOPLSDA=uipanel(...
    'Parent',hTabROCOPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 

%% ----------------- Classification Measures Tab 
%---------- Model Construction Main panel
hMeasureOPLSDA=uipanel(...
    'Parent',hTabMeasureOPLSDA,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.27 0.0 0.73 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
%---------- Tab explaned variance
hTableEigenvalues_oplsda = uitable(...
    'parent',hMeasureOPLSDA,...
    'units','normalized',...
    'columneditable',[true true true true],...
    'columnname',{' Eigenvalue ','   Explained Variance (%)   ','   Cumulative Variance (%)   ','RMSECV'},...
    'columnformat',{'numeric','numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.0 0 1 0.99],...
    'Data',zeros(6,4));

%% ----------- Tab Cross-Validation
hTabCrossValidation_oplsda=uitab(...
    'Parent',[],...
    'Title','Cross-Validation',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupCVOPLSDA=uitabgroup(...
    'Parent',hTabCrossValidation_oplsda,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangeTabCallback,...
    'Position',[0.27 0.0 0.73 1]);
hTabSplitCV_oplsda=uitab(...
    'Parent',hTabGroupCVOPLSDA,...
    'Title','Splits',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hResiduals_oplsda=uitab(...
    'Parent',hTabGroupCVOPLSDA,...
    'Title','Residuals',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hConfusionMatrix_oplsda=uitab(...
    'Parent',[],...
    'Title','Confusion Matrix',...
    'TooltipString','Cross-Validation analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized'); 

%% ----------------- Options Panel (left)

%---------- Cross Validation Main panel
OptionsCVPanel_oplsda=uipanel(...
    'Parent',hTabCrossValidation_oplsda,...
    'Units','normalized',...           
    'Position',[0.0 0.0 0.27 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%---------- Parameters Panel
hCrossVAlPanelOPLSDA=uipanel(...
    'Parent',OptionsCVPanel_oplsda,...
    'Units','normalized',...            
    'Title','Parameters',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.51 1 0.49],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethodCV=
uicontrol(...
    'Parent',hCrossVAlPanelOPLSDA,...
    'Style','text',...
    'String','Method',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.27 0.93 0.28 0.07]);  
hMethodCVOPLSDA = uicontrol(...
    'Parent',hCrossVAlPanelOPLSDA,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8.3,...
    'HorizontalAlignment','center',...
    'String',...
    'K-fold|Leane-One-Out|Contiguous Block|Monte Carlo',...
    'Position',[0.07 0.85 0.58 0.10],...
    'CallBack', {@MethodCheck_CV_Callback_OPLSDA});
%hMethodCV_Results=
uicontrol(...
    'Parent',hCrossVAlPanelOPLSDA,...
    'Style','text',...
    'String','shuffle',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.78 0.86 0.2 0.09]);  
hCheckshuffleOPLSDA = uicontrol(...
    'Parent',hCrossVAlPanelOPLSDA,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',0,...
    'Position',[0.7 0.89 0.07 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on');

%--- max LV
hLVsPanelOPLSDA=uipanel(...
    'Parent',hCrossVAlPanelOPLSDA,...
    'Units','normalized',...            
    'Title','Max N° LVs',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.62 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hLeftLV=
uicontrol(...
    'Parent',hLVsPanelOPLSDA,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
%hRightLV=
uicontrol(...
    'Parent',hLVsPanelOPLSDA,...
    'Style','text',...
    'String','20',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditCVOPLSDA=uicontrol(...
    'Parent',hLVsPanelOPLSDA,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to use in the PCA model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditMaxLV_OPLSDA_Callback});    
hSliderCVOPLSDA=uicontrol(...
    'Parent',hLVsPanelOPLSDA,...
    'Style','slider',...
    'TooltipString','Correct the baseline offset',...
    'Units','Normalized',...
    'Min' ,1,'Max',20, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 10,...
    'SliderStep',[1/19 1/19], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderCVGroup_OPLSDA_Callback});

%--- Fold
hFoldPanelOPLSDA=uipanel(...
    'Parent',hCrossVAlPanelOPLSDA,...
    'Units','normalized',...            
    'Title','Fold',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on'); 
hLeftFoldCVOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightFoldCVOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA,...
    'Style','text',...
    'String',[],...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.86 0.09 0.12 0.28]); 
hEditFoldOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to use in the CV model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'Enable','on',...
    'CallBack', {@EditFold_OPLSDA_Callback});
hSliderFoldCVOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',5, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 1,...
    'SliderStep',[1/10 1/10], ...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@SliderFold_OPLSDA_Callback});

%--- Division
hDivisionPanelOPLSDA=uipanel(...
    'Parent',hCrossVAlPanelOPLSDA,...
    'Units','normalized',...            
    'Title','Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.12 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hLeftDivisionOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightDivisionOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA,...
    'Style','text',...
    'String','100',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditDivOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA,...
    'Style','edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to use in the PCA model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditPercIn_OPLSDA_Callback});
hSliderDivCVOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA,...
    'Style','slider',...
    'TooltipString','Correct the baseline offset',...
    'Units','Normalized',...
    'Min' ,1,'Max',100, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 70,...
    'SliderStep',[1/99 1/99], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderSliderDiv_OPLSDA_Callback});

%----------------------------------------------------
hCVApplyOPLSDA = uicontrol(...
    'parent',hCrossVAlPanelOPLSDA,...
    'style','PushButton',...
    'String','Apply',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.022 0.01 0.45 0.10],...
    'Callback',{@CVApply_OPLSDA_Callback}); 
hCVRunOPLSDA = uicontrol(...
    'parent',hCrossVAlPanelOPLSDA,...
    'style','PushButton',...
    'String','Run',...
    'Units','Normalized',...
    'TooltipString','Test with curent Cross-Validation parameters',...
    'Enable','off',...
    'Position',[0.52 0.01 0.45 0.10],...
    'Callback',{@CVRun_OPLSDA_Callback});

%---------- Visual Panel (Results)
hVisualPanelResults_oplsda=uipanel(...
    'Parent',OptionsCVPanel_oplsda,...
    'Units','normalized',...            
    'Title','Visual Options',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.31 1 0.20],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hMethodCV_Results=
uicontrol(...
    'Parent',hVisualPanelResults_oplsda,...
    'Style','text',...
    'String','Class',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'FontSize',10,...
    'BackgroundColor',[1 1 1],...
    'Position',[0.06 0.69 0.25 0.2]);  
hMethodCV_Class_oplsda = uicontrol(...
    'Parent',hVisualPanelResults_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8,...
    'HorizontalAlignment','center',...
    'String',...
    '|',...
    'Position',[0.35 0.85 0.57 0.09],...
    'Enable','off',...
    'CallBack', {@Classes_RMSECV_OPLSDA_Callback});

%hTextLabels=
uicontrol(...
    'Parent',hVisualPanelResults_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.19 0.37 0.37 0.21],...
    'FontSize',10,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'String','All Classes');
hCheckLabelsAllClasses_oplsda = uicontrol(...
    'Parent',hVisualPanelResults_oplsda,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',1,...
    'Position',[0.06 0.4 0.1 0.2],...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...    
    'Callback',{@Classes_RMSECV_OPLSDA_Callback});

%hTextLabels=
uicontrol(...
    'Parent',hVisualPanelResults_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.19 0.07 0.37 0.21],...
    'FontSize',10,...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'String','Labels');
hCheckLabelsLabels_oplsda = uicontrol(...
    'Parent',hVisualPanelResults_oplsda,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','r',...
    'TooltipString',...
    'Labels for each point',...
    'Value',0,...
    'Position',[0.06 0.1 0.1 0.2],...
    'BackgroundColor',[1 1 1],...
    'Enable','off',...    
    'Callback',{@EnableLabel_OPLSDA_Callback});

%---------- Visual Panel (Outlier Detection)
hVisualPanelOutlier_oplsda=uipanel(...
    'Parent',OptionsCVPanel_oplsda,...
    'Units','normalized',...            
    'Title','Outlier Detection',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.31 1 0.20],...
    'BackgroundColor',[1 1 1],...
    'Visible','off');
%hMethodCV_Results=
uicontrol(...
    'Parent',hVisualPanelOutlier_oplsda,...
    'Style','text',...
    'String','PLS Components',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'FontSize',9,...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01 0.43 0.52 0.20]);
hOutliersCV_Results_oplsda = uicontrol(...
    'Parent',hVisualPanelOutlier_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8,...
    'HorizontalAlignment','center',...
    'String',...
    '|',...
    'Position',[0.57 0.42 0.40 0.25],...
    'Enable','off',...
    'CallBack', {@PLS_Tables_OPLSDA_Callback});

%---------- Visual Panel (Confusion Matrix)
hVisualPanelConfusion_oplsda=uipanel(...
    'Parent',OptionsCVPanel_oplsda,... 
    'Units','normalized',...            
    'Title','N° of PLS Components',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.31 1 0.20],...
    'BackgroundColor',[1 1 1],...
    'Visible','off');
%hMethodCV_Results=
uicontrol(...
    'Parent',hVisualPanelConfusion_oplsda,...
    'Style','text',...
    'String','PLS Components',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'FontSize',9,...
    'BackgroundColor',[1 1 1],...
    'Position',[0.01 0.43 0.52 0.20]);  
hConfusion_OPLS = uicontrol(...
    'Parent',hVisualPanelConfusion_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8,...
    'HorizontalAlignment','center',...
    'String',...
    '|',...
    'Position',[0.57 0.42 0.40 0.25],...
    'Enable','off',...
    'CallBack', {@PLS_Tables_Callback});

%---------- Export Data Panel
OptionsExportOPLSDAPanel=uipanel(...
    'Parent',OptionsCVPanel_oplsda,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.23 1 0.08],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hExportData_oplsda = uicontrol(...
    'parent',OptionsExportOPLSDAPanel,...
    'style','PushButton',...
    'String','Export Table',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.022 0.1 0.45 0.70],...
    'Callback',{ @ExportData});    
hExportFigures_oplsda = uicontrol(...
    'parent',OptionsExportOPLSDAPanel,...
    'style','PushButton',...
    'String','Export CV Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.52 0.1 0.45 0.70],...
    'Callback',{@ExportFigure});    


%---------- Info Panel
hMessagesPanel_oplsda=uipanel(...
    'Parent',OptionsCVPanel_oplsda,...
    'Title','Info',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0 1 0.23]);
hTextTest_oplsda=uicontrol(...
    'Parent',hMessagesPanel_oplsda,...
    'Style','edit',...
    'String','',...
    'Max',2,...
    'Enable','Off',...
    'Tag','MessageText',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.0 0.15 1 0.85],...
    'horizontalalignment','l');
set(hTextTest_oplsda,'String',GUIData.MessageText)

%---------- hSaveLogfileButton = 
uicontrol(...
    'Parent',hMessagesPanel_oplsda,...
    'Style','PushButton',...
    'String','Save logfile',...
    'Units','normalized',...
    'TooltipString','Save the logfile',...
    'Position',[0.3 0.01 0.4 0.13],...
    'Callback', { @SaveLogfile_Callback});


%% ----------------- Splits Tab
AxesResultTab_oplsda=uipanel(...
    'Parent',hTabSplitCV_oplsda,...
    'Units','normalized',...   %'BorderType','none',...
    'Position',[0.0 0.0 1 1],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
AxesOPLSDA = axes(...
    'Parent',AxesResultTab_oplsda,...
    'Units','normalized',...
    'Visible','off',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.0 0.11 0.99 0.8]); %0.11 0.2 0.85 0.65
% ------Class Table Structure
hClassInfoTableOPLSDA = uitable(...
    'parent',AxesResultTab_oplsda,...
    'units','normalized',...
    'columneditable',true,...
    'columnname',{'Sample','Class'},...
    'columnformat',{'numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{},...
    'ColumnFormat',{[],[],[],[]}, ...
    'Visible','on',...
    'position',[0.01 0.01 0.985 0.95]);

%% ----------------- Confusion Matrix Tab
%hFigures_of_MeritCV=
uicontrol(...
    'Parent',hConfusionMatrix_oplsda,...
    'Style','text',...
    'String','Figures of Merit',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'FontSize',14,...
    'FontName','Goudy Old Style',...    
    'Position',[0.024 0.94 0.30 0.04]); 
hFigureMeritTable_oplsda = uitable(...
    'parent',hConfusionMatrix_oplsda,...
    'units','normalized',...
    'columneditable',[false true false false true],...
    'columnname',{' Sample ',' Class ','Calibration', 'Traning', 'Used'},...
    'columnformat',{'char','numeric','numeric','numeric','logical'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024 0.50 0.95 0.43],...
    'Data',zeros(1,5));

%hConfusionTable=
uicontrol(...
    'Parent',hConfusionMatrix_oplsda,...
    'Style','text',...
    'String','Confusion Table',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'FontSize',14,...
    'FontName','Goudy Old Style',...
    'Position',[0.024 0.45 0.30 0.04]); 
hConfusionTable_oplsda = uitable(...
    'parent',hConfusionMatrix_oplsda,...
    'units','normalized',...
    'columneditable',[false true false false true],...
    'columnname',{' Sample ',' Class ','Calibration', 'Traning', 'Used'},...
    'columnformat',{'char','numeric','numeric','numeric','logical'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024 0.009 0.95 0.43],...
    'Data',zeros(1,5));

 
%% ----------------- Residuals Tab
AxesRMSECVOPLSDA = axes(...
    'Parent',hResiduals_oplsda,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'Position',[0.11 0.2 0.85 0.65]);

%% ----------- Tab iPLS
hTab_iPLS_OPLSDA=uitab(...
    'Parent',[],...
    'Title','iPLS',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupiPLS_OPLSDA=uitabgroup(...
    'Parent',hTab_iPLS_OPLSDA,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangeTabCallback,...
    'Position',[0.27 0.0 0.73 1]);
hTabResiduals_Intervals_iPLS_oplsda=uitab(...
    'Parent',hTabGroupiPLS_OPLSDA,...
    'Title','Residuals vs Intervals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabPredMeasure_iPLS_oplsda=uitab(...
    'Parent',[],...
    'Title','Prediction',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hResiduals_iPLS_oplsda=uitab(...
    'Parent',hTabGroupiPLS_OPLSDA,...
    'Title','Residuals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hModelinfo_iPLS_oplsda=uitab(...
    'Parent',hTabGroupiPLS_OPLSDA,...
    'Title','Model info',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized'); 

%% ----------------- Residual vs Intervals Tab
AxesiPLS_residual_oplsda = axes(...
    'Parent',hTabResiduals_Intervals_iPLS_oplsda,...
    'Units','normalized',...
    'Visible','on',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.08,0.09,0.90,0.84]); %0.11 0.2 0.85 0.65

%% ----------------- Residual Tab
AxesiPLS_residual_idx_Tab_oplsda = axes(...
    'Parent',hResiduals_iPLS_oplsda,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax',...
    'Position',[0.08,0.55,0.90,0.39]); %0.11 0.2 0.85 0.65
AxesiPLS_residual_all_Tab_oplsda = axes(...
    'Parent',hResiduals_iPLS_oplsda,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax2',...
    'Position',[0.08,0.08,0.90,0.38]); %0.11 0.2 0.85 0.65
%% ----------------- Model info Tab
hTable_iPLS_intervals_oplsda = uitable(...
    'parent',hModelinfo_iPLS_oplsda,...
    'units','normalized',...
    'columneditable',[false true false false true],...
    'columnname',{'Interval','Start var.','End var.','Start ppm','End ppm','Number of vars.'},...
    'columnformat',{'numeric','numeric','numeric','numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024 0.009 0.937 0.95],...
    'Data',zeros(1,6));
%% ----------------- Options Panel (left)
Options_iPLS_Panel_oplsda=uipanel(...
    'Parent',hTab_iPLS_OPLSDA,...
    'Units','normalized',...            
    'Position',[0.0 0.0 0.27 1],...
    'BackgroundColor',[1 1 1],...
    'BorderType','none',...
    'Visible','on');

%---------- Cross-Validation 
hCrossVal_iPLS_Panel_oplsda=uipanel(...
    'Parent',Options_iPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Parameters',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.51 1 0.49],...
    'BackgroundColor',[1 1 1],...
    'BorderType','etchedin',...
    'Visible','on');

%hMethodCViPLS=
uicontrol(...
    'Parent',hCrossVal_iPLS_Panel_oplsda,...
    'Style','text',...
    'String','Method',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.27 0.93 0.28 0.07]);  
hMethodiPLSOPLSDA = uicontrol(...
    'Parent',hCrossVal_iPLS_Panel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8.3,...
    'HorizontalAlignment','center',...
    'String',...
    'K-fold|Leane-One-Out|Contiguous Block|Monte Carlo',...
    'Position',[0.07 0.85 0.58 0.10],...
    'CallBack', {@MethodCheck_iPLS_Callback});
%hMethodCV_Results=
uicontrol(...
    'Parent',hCrossVal_iPLS_Panel_oplsda,...
    'Style','text',...
    'String','shuffle',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.78 0.86 0.2 0.09]);  
hCheckshuffleiPLSOPLSDA = uicontrol(...
    'Parent',hCrossVal_iPLS_Panel_oplsda,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Labels for each point',...
    'Value',0,...
    'Position',[0.7 0.89 0.07 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on');

%--- max LV
hLVsPanelOPLSDA_iPLS=uipanel(...
    'Parent',hCrossVal_iPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Max N° LVs',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.62 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hLeftLV=
uicontrol(...
    'Parent',hLVsPanelOPLSDA_iPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
%hRightLV=
uicontrol(...
    'Parent',hLVsPanelOPLSDA_iPLS,...
    'Style','text',...
    'String','20',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditCVGroupiPLSOLPSDA=uicontrol(...
    'Parent',hLVsPanelOPLSDA_iPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of LV to use in the iPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditMaxLV_Callback});    
hSliderLViPLSOLPSDA=uicontrol(...
    'Parent',hLVsPanelOPLSDA_iPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',20, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 10,...
    'SliderStep',[1/19 1/19], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderCVGroup_Callback});

%--- Fold
hFoldPanelOPLSDA_iPLS=uipanel(...
    'Parent',hCrossVal_iPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Fold',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');    
hLeftFoldOPLSDAiPLS=uicontrol(...
    'Parent',hFoldPanelOPLSDA_iPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightFoldOPLSDAiPLS=uicontrol(...
    'Parent',hFoldPanelOPLSDA_iPLS,...
    'Style','text',...
    'String',[],...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.86 0.09 0.12 0.28]); 
hEditFoldiPLSOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA_iPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of folds to use in the iPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'Enable','on',...
    'CallBack', {@EditFold_Callback});
hSliderFoldOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA_iPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',5, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 1,...
    'SliderStep',[1/10 1/10], ...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@SliderFold_Callback});

%--- Division
hDivisionPanelOPLSDA_iPLS=uipanel(...
    'Parent',hCrossVal_iPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.12 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hLeftDivisioniPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_iPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightDivisioniPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_iPLS,...
    'Style','text',...
    'String','100',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditDiviPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_iPLS,...
    'Style','edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of samples to use in the iPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditPercIn_Callback});
hSliderDiviPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_iPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',100, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 70,...
    'SliderStep',[1/99 1/99], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderSliderDiv_Callback});

%---------- Spectral Division Panel
hSpecDiv_iPLS_Panel_oplsda=uipanel(...
    'Parent',Options_iPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Spectral Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.193],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');

%hMethodCV_Results=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','text',...
    'String','Pre-processing',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.73 0.4 0.20]);  
hiPLSprocess_oplsda = uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'mean|auto|msc mean|msc auto',...
    'Position',[0.55 0.78 0.4 0.15],...
    'Enable','on');
%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.51 0.4 0.15],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Intervals:' );
hEditIntervals_iPLS_oplsda=uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',20,...
    'Units','Normalized',...
    'Position',[0.55 0.55 0.4 0.15]); 
%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.29 0.4 0.15],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Segments:' );
hEditSegments_iPLS_oplsda=uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',5,...
    'Units','Normalized',...
    'Position',[0.55 0.32 0.4 0.15]); 
%hCheckBinPCA=
uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','text',...
    'String','External Limits',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.07 0.4 0.15]);  
hBinCheck_oplsda = uicontrol(...
    'Parent',hSpecDiv_iPLS_Panel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Import limits directly from the Bin GUI',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String','None|Binning',...
    'Position',[0.55 0.09 0.4 0.15],...
    'Enable','on',...
    'Callback',{@iPLS_Apply_Callback});


% hCheckimportBin_iPLS = uicontrol(...
%     'Parent',hCrossVal_iPLS_Panel_oplsda,...
%     'Style','Checkbox',...
%     'Units','normalized',...
%     'horizontalalignment','l',...
%     'TooltipString', 'Import limits directly from the Bin GUI',...
%     'Labels for each point',...
%     'Value',0,...
%     'String','Import Bin limits',...
%     'Position',[0.085 0.883 0.067 0.034],...
%     'BackgroundColor',[1 1 1],...
%     'Enable','on',...
%     'Callback',{@iPLS_Run_Callback});

%---------- Run iPLS & Export Data Panel
Export_iPLS_Panel_oplsda=uipanel(...
    'Parent',Options_iPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0 0.23 1 0.14],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hExport_iPLSData_oplsda = uicontrol(...
    'parent',Export_iPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Export Table',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.03 0.5 0.45 0.42],...
    'Callback',{@ExportData});    
hExport_iPLSFigures_oplsda = uicontrol(...
    'parent',Export_iPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Export iPLS Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.52 0.5 0.45 0.42],...
    'Callback',{@ExportFigure});    

h_iPLS_Apply_oplsda = uicontrol(...
    'parent',Export_iPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Apply',...
    'Units','Normalized',...
    'TooltipString','',...
    'Position',[0.03 0.07 0.45 0.42],...
    'Callback',{@iPLS_Apply_Callback}); 
h_iPLS_Run_oplsda = uicontrol(...
    'parent',Export_iPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Run',...
    'Units','Normalized',...
    'TooltipString','',...
    'Enable','off',...
    'Position',[0.52 0.07 0.45 0.42],...
    'Callback',{@iPLS_Run_Callback});

%---------- Tips for user
hTipsiPLS_oplsda=uipanel(...
    'Parent',Options_iPLS_Panel_oplsda,...
    'Title','Tips',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...    
    'Position',[0.0 0 1 0.23]);
%hTextStart=
uicontrol(...
    'Parent',hTipsiPLS_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.0 0.15 1 0.85],...
    'BackgroundColor',[1 1 1],...    
    'horizontalalignment','left',...
    'String','Note that the iPLS approach differs from the so-called binning method for data reduction. The segmentation step in iPLS is not a reduction of the number of variables; it is merely a technique to obtain an overview of a large number of (possibly diverse) variables' ); 

%% ----------- Tab biPLS
hTab_biPLS_OPLSDA=uitab(...
    'Parent',[],...
    'Title','biPLS',...
    'TooltipString','Cross-Validation analysis tools',...
    'Units','Normalized');
hTabGroupbiPLS_OPLSDA=uitabgroup(...
    'Parent',hTab_biPLS_OPLSDA,...
    'Units','Normalized',...
    'SelectionChangedFcn', @ChangeTab_biPLS_Callback,...
    'Position',[0.27 0.0 0.73 1]);
hModelinfo_biPLS_oplsda=uitab(...
    'Parent',hTabGroupbiPLS_OPLSDA,...
    'Title','Model info',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hResiduals_biPLS_oplsda=uitab(...
    'Parent',hTabGroupbiPLS_OPLSDA,...
    'Title','Residuals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabResiduals_Intervals_biPLS_oplsda=uitab(...
    'Parent',[],...
    'Title','Residuals vs Intervals',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');
hTabPredMeasure_biPLS_oplsda=uitab(...
    'Parent',hTabGroupbiPLS_OPLSDA,...
    'Title','Prediction',...
    'TooltipString','iPLS analysis tools',...
    'BackgroundColor',[1 1 1],...
    'Units','Normalized');

%% ----------------- Residual vs Intervals Tab
Axes_biPLS_residual_oplsda = axes(...
    'Parent',[],...
    'Units','normalized',...
    'Visible','off',...
    'Box','off',...
    'tag','ax1',...
    'Position',[0.08,0.09,0.90,0.84]); %0.11 0.2 0.85 0.65

%% ----------------- Prediction Tab
AxesbiPLS_Interval_oplsda = axes(...
    'Parent',hTabPredMeasure_biPLS_oplsda,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax1',...
    'Position',[0.08,0.58,0.90,0.37]); %0.11 0.2 0.85 0.65
AxesbiPLS_Predic_oplsda = axes(...
    'Parent',hTabPredMeasure_biPLS_oplsda,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','ax1',...
    'Position',[0.08,0.07,0.90,0.37]); %0.11 0.2 0.85 0.65

%% ----------------- Residual Tab
AxesbiPLS_RMSE_oplsda = axes(...
    'Parent',hResiduals_biPLS_oplsda,...
    'Units','normalized',...
    'Visible','on',...
    'Box','on',...
    'tag','axbiPLSresidual',...
    'Position',[0.08,0.09,0.90,0.84]); %0.11 0.2 0.85 0.65

%% ----------------- Model info Tab
%hinfoInterval_biPLS_oplsda=
uicontrol(...
    'Parent',hModelinfo_biPLS_oplsda,...
    'Style','text',...
    'String','Outliers',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'FontSize',14,...
    'FontName','Goudy Old Style',...    
    'Position',[0.024 0.32 0.30 0.04]); 
hinfoInterval_biPLS_oplsda = uitable(...
    'parent',hModelinfo_biPLS_oplsda,...
    'units','normalized',...
    'columneditable',[false true false false],...
    'columnname',{' Number ',' Interval ','RMSE', 'Number of Variables'},...
    'columnformat',{'numeric','numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.024,0.009,0.937,0.95],...
    'Data',zeros(1,5));
%% ----------------- Options Panel (left)
Options_biPLS_Panel_oplsda=uipanel(...
    'Parent',hTab_biPLS_OPLSDA,...
    'Units','normalized',...           
    'Position',[0.0 0.0 0.27 1],...
    'BackgroundColor',[1 1 1],...
    'BorderType','none',...
    'Visible','on');

%---------- Parameters Panel
hCrossVal_biPLS_Panel_oplsda=uipanel(...
    'Parent',Options_biPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Parameters',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.51 1 0.49],...
    'BackgroundColor',[1 1 1],...
    'BorderType','etchedin',...
    'Visible','on');

%hMethodCV_biPLS=
uicontrol(...
    'Parent',hCrossVal_biPLS_Panel_oplsda,...
    'Style','text',...
    'String','Method',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.27 0.93 0.28 0.07]);  
hMethodbiPLSOPLSDA = uicontrol(...
    'Parent',hCrossVal_biPLS_Panel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'FontSize',8.3,...
    'HorizontalAlignment','center',...
    'String',...
    'K-fold|Leane-One-Out|Contiguous Block|Monte Carlo',...
    'Position',[0.07 0.85 0.58 0.10],...
    'CallBack', {@MethodCheck_biPLS_Callback});
%hMethodCV_Results=
uicontrol(...
    'Parent',hCrossVal_biPLS_Panel_oplsda,...
    'Style','text',...
    'String','shuffle',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.78 0.86 0.2 0.09]);  
hCheckshufflebiPLS_oplsda = uicontrol(...
    'Parent',hCrossVal_biPLS_Panel_oplsda,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString','',...
    'Value',0,...
    'Position',[0.7 0.89 0.07 0.07],...
    'BackgroundColor',[1 1 1],...
    'Enable','on');

%--- max LV
hLVsPanelOPLSDA_biPLS=uipanel(...
    'Parent',hCrossVal_biPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Max N° LVs',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.62 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hLeftLV=
uicontrol(...
    'Parent',hLVsPanelOPLSDA_biPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
%hRightLV=
uicontrol(...
    'Parent',hLVsPanelOPLSDA_biPLS,...
    'Style','text',...
    'String','20',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditCVGroupbiPLSOPLSDA=uicontrol(...
    'Parent',hLVsPanelOPLSDA_biPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to use in the biPLS model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditMaxLV_Callback});    
hSliderLVbiPLSOPLSDA=uicontrol(...
    'Parent',hLVsPanelOPLSDA_biPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',20, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 10,...
    'SliderStep',[1/19 1/19], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderCVGroup_Callback});

%--- Fold
hFoldPanelOPLSDA_biPLS=uipanel(...
    'Parent',hCrossVal_biPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Fold',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.37 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');  
hLeftFoldOPLSDAbiPLS=uicontrol(...
    'Parent',hFoldPanelOPLSDA_biPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightFoldOPLSDAbiPLS=uicontrol(...
    'Parent',hFoldPanelOPLSDA_biPLS,...
    'Style','text',...
    'String',[],...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.86 0.09 0.12 0.28]); 
hEditFoldbiPLSOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA_biPLS,...
    'Style','edit',...
    'String',num2str(10),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of folds to use in the CV model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'Enable','on',...
    'CallBack', {@EditFold_Callback});
hSliderFoldbiPLSOPLSDA=uicontrol(...
    'Parent',hFoldPanelOPLSDA_biPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',5, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 1,...
    'SliderStep',[1/10 1/10], ...
    'BackgroundColor',[1 1 1],...
    'Enable','on',...
    'CallBack', {@SliderFold_Callback});

%--- Division
hDivisionPanelOPLSDA_biPLS=uipanel(...
    'Parent',hCrossVal_biPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.12 1 0.25],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hLeftDivbiPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_biPLS,...
    'Style','text',...
    'String','1',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.08 0.09 0.08 0.28]); 
hRightDivbiPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_biPLS,...
    'Style','text',...
    'String','100',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.85 0.09 0.12 0.28]); 
hEditDivbiPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_biPLS,...
    'Style','edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of samples to use in the CV model',...
    'Units','Normalized',...
    'Position',[0.38 0.07 0.25 0.28],...
    'CallBack', {@EditPercIn_Callback});
hSliderDivbiPLSOPLSDA=uicontrol(...
    'Parent',hDivisionPanelOPLSDA_biPLS,...
    'Style','slider',...
    'TooltipString','',...
    'Units','Normalized',...
    'Min' ,1,'Max',100, ...
    'Position',[0.07 0.45 0.89 0.31], ...
    'Value', 70,...
    'SliderStep',[1/99 1/99], ...
    'BackgroundColor',[1 1 1],...
    'CallBack', {@SliderSliderDiv_Callback});

%---------- Spectral Division Panel (Residuals vs Intervals)
hSpecDiv_biPLS_Panel_oplsda=uipanel(...
    'Parent',Options_biPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Spectral Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.35 1 0.217],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
%hMethodCV_Results=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','text',...
    'String','Pre-processing',...
    'Units','Normalized',...
    'horizontalalignment','l',...
    'BackgroundColor',[1 1 1],...
    'Position',[0.05 0.69 0.4 0.2]);  
hbiPLSprocess_oplsda = uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','popupmenu',...
    'Units','Normalized',...
    'TooltipString','Selects the method for Cross-Validation',...
    'FontWeight','normal',...
    'HorizontalAlignment','center',...
    'String',...
    'mean|auto|msc mean|msc auto',...
    'Position',[0.55 0.85 0.4 0.09],...
    'Enable','on');

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.46 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Intervals:' );
hEditIntervals_biPLS_oplsda=uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',20,...
    'Units','Normalized',...
    'Position',[0.35 0.51 0.3 0.2 ]); 

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.26 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Segments:' );
hEditSegments_biPLS_oplsda=uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Space between spectra',...
    'String',5,...
    'Units','Normalized',...
    'Position',[0.35 0.30 0.3 0.2 ]); 

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.06 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Variables:' );
hEditVariables_biPLS_oplsda=uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Use space to separate the desired variables',...
    'String',1,...
    'Units','Normalized',...
    'Enable','off',...
    'Position',[0.35 0.09 0.3 0.2 ]); 

mls = sprintf('%s\n%s','Variable','Selection');
%hTextUseVariables_biPLS=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.71 0.30 0.21 0.24],...
    'horizontalalignment','r',...
    'BackgroundColor',[1 1 1],...
    'String',mls);
hCheckUseVariables_biPLS_oplsda = uicontrol(...
    'Parent',hSpecDiv_biPLS_Panel_oplsda,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Enable you select which intervals the biPLS shoud use in its calculations',...
    'Position',[0.77 0.09 0.08 0.17],...
    'BackgroundColor',[1 1 1],...
    'Callback',{@EnableVariables_biPLS_Callback});

%---------- Spectral Division Panel (Prediction)
hSpecDiv_biPLS_Predic_oplsda=uipanel(...
    'Parent',Options_biPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Title','Spectral Division',...
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0.0 0.35 1 0.217],...
    'BackgroundColor',[1 1 1],...
    'Visible','off');

%hTextStart=
uicontrol(...
    'Parent',hSpecDiv_biPLS_Predic_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.05 0.46 0.3 0.2 ],...
    'horizontalalignment','left',...
    'BackgroundColor',[1 1 1],...    
    'String','Latent Variables:' );
hEditLV_biPLS_oplsda=uicontrol(...
    'Parent',hSpecDiv_biPLS_Predic_oplsda,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','',...
    'String',10,...
    'Units','Normalized',...
    'Position',[0.35 0.51 0.3 0.2 ]); 
% 
% %hTextStart=
% uicontrol(...
%     'Parent',hSpecDiv_biPLS_Predic,...
%     'Style','text',...
%     'Units','Normalized',...
%     'Position',[0.05 0.06 0.3 0.2 ],...
%     'horizontalalignment','left',...
%     'BackgroundColor',[1 1 1],...    
%     'String','Variables:' );
% hEditVariables_biPLS=uicontrol(...
%     'Parent',hSpecDiv_biPLS_Predic,...
%     'Style','edit',...
%     'BackgroundColor','w',...
%     'TooltipString','Use space to separate the desired variables',...
%     'String',1,...
%     'Units','Normalized',...
%     'Enable','off',...
%     'Position',[0.35 0.09 0.3 0.2 ]); 

%---------- Run iPLS & Export Data Panel
Export_biPLS_Panel_oplsda=uipanel(...
    'Parent',Options_biPLS_Panel_oplsda,...
    'Units','normalized',...            
    'Titleposition','centertop',...
    'FontWeight','bold',...
    'Position',[0 0.207 1 0.14],...
    'BackgroundColor',[1 1 1],...
    'Visible','on');
hExport_iPLSData_oplsda = uicontrol(...
    'parent',Export_biPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Export Table',...
    'Units','Normalized',...
    'TooltipString','Export data of pca analysis to a .txt file',...
    'Position',[0.03 0.5 0.45 0.42],...
    'Callback',{@ExportData});    
hExport_iPLSFigures_oplsda = uicontrol(...
    'parent',Export_biPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Export biPLS Figure',...
    'Units','Normalized',...
    'TooltipString','Export curent figures',...
    'Position',[0.52 0.5 0.45 0.42],...
    'Callback',{@ExportFigure});    

h_biPLS_Apply_oplsda = uicontrol(...
    'parent',Export_biPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Apply',...
    'Units','Normalized',...
    'TooltipString','',...
    'Position',[0.03 0.07 0.45 0.42],...
    'Callback',{@biPLS_Apply_Callback}); 
h_biPLS_Run_oplsda = uicontrol(...
    'parent',Export_biPLS_Panel_oplsda,...
    'style','PushButton',...
    'String','Run',...
    'Units','Normalized',...
    'TooltipString','',...
    'Enable','off',...
    'Position',[0.52 0.07 0.45 0.42],...
    'Callback',{@biPLS_Run_Callback});

%---------- Tips for user
hTipsbiPLS_oplsda=uipanel(...
    'Parent',Options_biPLS_Panel_oplsda,...
    'Title','Tips',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'BackgroundColor',[1 1 1],...    
    'Position',[0.0 0 1 0.205]);
%hTextStart=
uicontrol(...
    'Parent',hTipsbiPLS_oplsda,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.0 0.15 1 0.85],...
    'BackgroundColor',[1 1 1],...    
    'horizontalalignment','left',...
    'String','Sample and/or measurement abnormalities (outliers) as detected by PLS inner relation plots should generally be removed prior to the application of iPLS/biPLS' ); 

%% ---------Plot Initialization 
   StructureGui()
   set(hPLOTfigure,'Visible','on');        
%% ---------Callbacks
%% ----------------- Structure
    function PCAMethod(source,eventdata) %#ok<*INUSD> 
        GUIData = guidata(hPLOTfigure); 
        method = 'PCA';
        StructureGui()
        guidata(hPLOTfigure,GUIData);
    end
    function PLSDAMethod(source,eventdata)
        GUIData = guidata(hPLOTfigure); 
        method = 'PLSDA';
        StructureGui()
        guidata(hPLOTfigure,GUIData);
    end
    function OPLSMethod(source,eventdata)
        GUIData = guidata(hPLOTfigure); 
        method = 'OPLS';
        StructureGui()
        guidata(hPLOTfigure,GUIData);
    end
    function OPLSDAMethod(source,eventdata)
        GUIData = guidata(hPLOTfigure); 
        method = 'OPLSDA';
        StructureGui()
        guidata(hPLOTfigure,GUIData);
    end
    function ConfusionMatrix(source,eventdata)
        GUIData = guidata(hPLOTfigure);
        if strcmp(method, 'PLSDA') 

            if ~isempty(Labels)                 
%                 set(nConfMatrixTxt,'RowName',GNATData.ClassesValue);
            else
                set(nConfMatrixTxt,'RowName','Class ' + string((1:size(GNATData.ycalM,2))'));  
            end

            Data=[...
                GUIData.modelPLSDA.class_param.sensitivity',... 
                GUIData.modelPLSDA.class_param.FPR',... 
                GUIData.modelPLSDA.class_param.specificity',... 
                GUIData.modelPLSDA.class_param.FNR',... 
                GUIData.modelPLSDA.class_param.precision'];
            set(nConfMatrixTxt,'Data',Data);     

            % Auto recize table
            % jscroll = findjobj(nConfMatrixTxt);
            % jTable = jscroll.getViewport.getView;
            % jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)

            if ~isempty(Labels)                 
%                 set(nConfMatrixTxt,'RowName',GNATData.ClassesValue);
%                 GNATData.ycalM
            else
                set(nConfTableTxt,'ColumnName','Class ' + string((1:size(GNATData.ycalM,2))'));                
                set(nConfTableTxt,'RowName','Predicted as ' + string((1:size(GNATData.ycalM,2))'));
            end           
            set(nConfTableTxt,'Data',GUIData.modelPLSDA.classification.ConfusionMatrix);

        elseif strcmp(method, 'OPLSDA')

        end
        guidata(hPLOTfigure,GUIData);
    end
    function StructureGui(source,eventdata)
        GUIData = guidata(hPLOTfigure);
        if strcmp(method, 'PCA') 
            % Turning off all other Tabs, except PCA
            hTabCrossValidation.Parent = [];
            hTabModelPLSDA.Parent = [];
            hTabModelOPLS.Parent = [];
            hTabModelOPLSDA.Parent = [];
            hTabScoreLoadingResidual.Parent = hTabGroup;

            % Turning on axis depending on the user input (Score, Loadings and Residuals)
            Opt = GNATData.PlotOpt; 
            if sum(Opt) == 3
                Axes31.Parent = AxesSLRPanel;
                Axes32.Parent = AxesSLRPanel;
                Axes33.Parent = AxesSLRPanel;
            elseif sum(Opt) == 2
                Axes21.Parent = AxesSLRPanel;
                Axes22.Parent = AxesSLRPanel;
            elseif sum(Opt) == 1
                Axes.Parent = AxesSLRPanel;            
            end
            
            % Structure of popup menus (X, Y and Z axis)
            % Scores
            set(hpopupPCX,'string',GNATData.parameters.AxesPlot(:,1));
            set(hpopupPCY,'string',GNATData.parameters.AxesPlot(:,1));
            set(hpopupPCZ,'string',GNATData.parameters.AxesPlot(:,1));
            if GNATData.ncomp > 2
                set(hpopupPCZ,'Value',3);
            end     
            % Loadings
            set(hpopupPCXLoading,'string',GNATData.parameters.AxesPlot(:,1));
            set(hpopupPCYLoading,'string',GNATData.parameters.AxesPlot(:,1));

            % Turning off the editbox 'hCheckEllipse' for datasets without classes
            c = unique(Classes);
            if sum(c) < 1
                set(hCheckEllipse,'enable','off');
            end

            % Plot results of the pca_svd function
            PlotCheck_Callback()

            % Resizing all components of the GUI for all types of monitors
            txtHand = findall(hPLOTfigure, '-property', 'FontUnits'); 
            set(txtHand, 'FontUnits', 'normalized')

        elseif strcmp(method, 'PLSDA')
            % Turning of all other Tabs, except PLSDA
            hTabScoreLoadingResidual.Parent = [];
            hTabModelOPLS.Parent = [];
            hTabModelOPLSDA.Parent = [];  
            hTabModelPLSDA.Parent = hTabGroup;
            hTabCrossValidation.Parent = hTabGroup;
            hTab_iPLS_PLSDA.Parent = hTabGroup;
            hTab_biPLS_PLSDA.Parent = hTabGroup;

            % Popup menu for the score plot 
            Factor = str2double(get(hEditFactorsModelPLSDA,'String')); 
            LV = 1:Factor;
            set(hScore_PLSDA_Model_X,'string',LV);
            set(hScore_PLSDA_Model_Y,'string',LV);
            set(hScore_PLSDA_Model_Z,'string',LV);
            
            % Sliders for Cross-Validation 
            set(hRightFold,'string',num2str(size(GNATData.ycalV,1)));
            set(hSliderFoldCVPLS,'Max',size(GNATData.ycalV,1));
            set(hSliderFoldCVPLS,'SliderStep',[1/((size(GNATData.ycalV,1))-1) 1/((size(GNATData.ycalV,1))-1)]);
            set(hSliderFoldCVPLS,'Value',10);
            
            % GNAT figure in empty plots
            mpath= mfilename('fullpath');
            mname=mfilename;
            mlength=numel(mname);
            mpath((end-mlength+1):end)=[];
            axpath=[mpath 'axes_small.png'];
            if exist(axpath,'file')
                axim=imread(axpath);
                image(AxesPLSDA,axim);
                image(AxesiPLS_residual,axim);                
            end        
            
            set(AxesPLSDA,'xcolor',[1 1 1]);set(AxesPLSDA,'ycolor',[1 1 1])
            set(AxesiPLS_residual,'xcolor',[1 1 1]);set(AxesiPLS_residual,'ycolor',[1 1 1])

            % Supressing the warning message for java functions that will be removed 
            % (Altman, Y.M., 2011. Undocumented secrets of MATLAB-Java programming. CRC Press.)            
            oldWarningState1 = warning ('off', 'MATLAB:ui:javaframe:PropertyToBeRemoved');
            oldWarningState2 = warning ('off', 'MATLAB:hg:uicontrol:StringMustBeNonEmpty');
            
            % Correcting column size uiTable Figures of Merit
%             jscroll = findjobj(hFigureMeritTable);
%             jTable = jscroll.getViewport.getView;
%             jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % Correcting column size uiTable Confusion Matrix
%             jscroll = findjobj(hConfusionTable);
%             jTable = jscroll.getViewport.getView;
%             jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % % Correcting column size uiTable Folds
            % jscroll = findjobj(hClassInfoTable);
            % jTable = jscroll.getViewport.getView;
            % jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % set(hClassInfoTable,'Visible','off')
            % % Correcting column size uiTable Limits iPLS
            % jscroll = findjobj(hTable_iPLS_intervals);
            % jTable = jscroll.getViewport.getView;
            % jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % % Correcting column size uiTable Limits iPLS
            % jscroll = findjobj(hinfoInterval_biPLS);
            % jTable = jscroll.getViewport.getView;
            % jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % % Correcting column size uiTable VIP 
            % jscroll = findjobj(nVIPTablePpm);
            % jTable = jscroll.getViewport.getView;
            % jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)

            % Revert to displaying the warning
            warning(oldWarningState1);  
            warning(oldWarningState2); 

            % Creating vector of options Model Classes
            clss = num2cell(unique(Classes));
            clss{end+1,1} = 'all';
            set(hRunClasses_PLSDA,'string',clss);

            % Unable Cal/Val control for the score plots for the TABs Score, ROC and Measures Model.
            children = get(hCalValGroup_pls,'Children');
            set(children,'Enable','off');

            % Removing the outliers determined by the user
            remove = ismember(GNATData.objetos.treinamento,GNATData.outlier); 
            GNATData.xcal(remove,:) = [];
            GNATData.ycalM(remove,:) = [];
            GNATData.ycalV(remove,:) = [];

            MethodCheck_CV_Callback()
            ModelPLSDA()
            ConfusionMatrix()
% 
%             txtHand = findall(hTabModelPLSDA, '-property', 'FontUnits'); 
%             set(txtHand, 'FontUnits', 'normalized')   
% % 
%             txtHand = findall(hTabCrossValidation, '-property', 'FontUnits'); 
%             set(txtHand, 'FontUnits', 'normalized')   
% 
%             txtHand = findall(hTab_iPLS_PLSDA, '-property', 'FontUnits'); 
%             set(txtHand, 'FontUnits', 'normalized')   
% 
%             txtHand = findall(hTab_biPLS_PLSDA, '-property', 'FontUnits'); 
%             set(txtHand, 'FontUnits', 'normalized')   
        elseif strcmp(method, 'OPLS')
            % Turning of all other Tabs, except PCA
            hTabScoreLoadingResidual.Parent = [];
            hTabCrossValidation.Parent = [];
            hTabModelPLSDA.Parent = [];
            hTabModelOPLS.Parent = hTabGroup;
            hTabModelOPLSDA.Parent = [];            


        elseif strcmp(method, 'OPLSDA')
            % Turning of all other Tabs, except OPLSDA
            hTabScoreLoadingResidual.Parent = [];
            hTabModelPLSDA.Parent = [];
            hTabModelOPLS.Parent = [];
            hTabModelOPLSDA.Parent = hTabGroup;   
            hTabCrossValidation_oplsda.Parent = hTabGroup;
            hTab_iPLS_OPLSDA.Parent = hTabGroup;
            hTab_biPLS_OPLSDA.Parent = hTabGroup;

            % Popup menu for the score plot 
            Factor = str2double(get(hEditFactorsModelOPLSDA,'String')); 
            LV = 1:Factor;
            set(hScore_OPLSDA_Model_X,'string',1:str2double(get(hEditFactorsModelOPLSDA,'String')));
            set(hScore_OPLSDA_Model_Y,'string',1:str2double(get(hEditFactorsModelOPLSDA,'String')));
            set(hScore_OPLSDA_Model_Z,'string',1:str2double(get(hEditFactorsModelOPLSDA,'String')));

            set(hRightFoldCVOPLSDA,'string',size(GNATData.TableContent,1));
            set(hSliderFoldCVOPLSDA,'Max',size(GNATData.TableContent,1));
            set(hSliderFoldCVOPLSDA,'SliderStep',[1/((size(GNATData.TableContent,1))-1) 1/((size(GNATData.TableContent,1))-1)]);
            
            mpath= mfilename('fullpath');
            mname=mfilename;
            mlength=numel(mname);
            mpath((end-mlength+1):end)=[];
            axpath=[mpath 'axes_small.png'];
            if exist(axpath,'file')
                axim=imread(axpath);
                image(AxesOPLSDA,axim);
                image(AxesiPLS_residual_oplsda,axim);                
            end     

            set(AxesOPLSDA,'xcolor',[1 1 1]);set(AxesOPLSDA,'ycolor',[1 1 1])
            set(AxesiPLS_residual_oplsda,'xcolor',[1 1 1]);set(AxesiPLS_residual_oplsda,'ycolor',[1 1 1])     

            % Supressing the warning message for java functions that will be removed 
            % (Altman, Y.M., 2011. Undocumented secrets of MATLAB-Java programming. CRC Press.)            
            oldWarningState1 = warning ('off', 'MATLAB:ui:javaframe:PropertyToBeRemoved');
            oldWarningState2 = warning ('off', 'MATLAB:hg:uicontrol:StringMustBeNonEmpty');

            % Correcting column size uiTable Figures of Merit
%             jscroll = findjobj(hFigureMeritTable);
%             jTable = jscroll.getViewport.getView;
%             jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % Correcting column size uiTable Confusion Matrix
%             jscroll = findjobj(hConfusionTable);
%             jTable = jscroll.getViewport.getView;
%             jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % Correcting column size uiTable Folds
%             jscroll = findjobj(hClassInfoTableOPLSDA);
%             jTable = jscroll.getViewport.getView;
%             jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % set(hClassInfoTableOPLSDA,'Visible','off')
            % Correcting column size uiTable Limits iPLS
            jscroll = findjobj(hTable_iPLS_intervals_oplsda); %#ok<*UDIM> 
            jTable = jscroll.getViewport.getView;
            jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)
            % Correcting column size uiTable Limits iPLS
            jscroll = findjobj(hinfoInterval_biPLS_oplsda); %#ok<*UDIM>  
            jTable = jscroll.getViewport.getView;
            jTable.setAutoResizeMode(jTable.AUTO_RESIZE_SUBSEQUENT_COLUMNS)            

            % Revert to displaying the warning
            warning(oldWarningState1);  
            warning(oldWarningState2); 

            % Creating vector of options Model Classes
            clss = num2cell(unique(Classes));
            clss{end+1,1} = 'all';
            set(hRunClasses_OPLSDA,'string',clss);

            % Unable Cal/Val control for the score plots for the TABs Score, ROC and Measures Model.
            children = get(hCalValGroup_oplsda,'Children');
            set(children,'Enable','off');

            % Removing the outliers determined by the user
            remove = ismember(GNATData.objetos.treinamento,GNATData.outlier); 
            GNATData.xcal(remove,:) = [];
            GNATData.ycalM(remove,:) = [];
            GNATData.ycalV(remove,:) = [];

            MethodCheck_CV_Callback_OPLSDA()
            ModelOPLSDA() 
            ConfusionMatrix()
        end
        guidata(hPLOTfigure,GUIData);
    end
%% ----------------- PCA
    function ModelPCA(source,eventdata)
        GUIData = guidata(hPLOTfigure);

        % Getting the processing parameters
        opt.prepr{1} = get(hProcessing_PCA,'Value');            
        switch  opt.prepr{1}
            case 1
                opt.prepr{1} = 'mean';
            case 2 
                opt.prepr{1} = 'auto';
            case 3
                opt.prepr{1} = 'pareto';
        end

        % Recalculating PCA model with new user parameters             
        if isfield(GNATData,'BinPCA') % Model with bin method applied
            matrix=GNATData.BinPCA.normalized_buckets;
            GNATData.parameters = pca_svd(matrix, GNATData.ncomp,GNATData.confvalue,opt);
        else % Model with raw kdata
            GNATData.parameters = pca_svd(GNATData.raw_matrix, GNATData.ncomp,GNATData.confvalue,opt);     
        end

        % Plot results of the pca_svd function
        PlotCheck_Callback()
        
        guidata(hPLOTfigure,GUIData);  
    end
    function PlotCheck_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);
        
        % Making a numerical label for each sample
        labels_s = num2cell(1:GNATData.arraydim);
        if any(GNATData.outlier)
            labels_s(GNATData.outlier) = [];        
        end
        symbols = {'o','s','^','d','h','v','*','x','<','>','p'};  
        colors = ['g','b','m','c','y','b'];
        
        % Saving the class sequence
        [cc,ia]=unique(Classes);
        ClassesValue = cc; 
        if ClassesValue==0 % no classes
            ClassesValue = 1;
        end
        ClassesValue=num2str(ClassesValue);
        GNATData.ClassesValue = ClassesValue;
        
        % Create legend for classe define by the user
        if ~isempty(Labels) 
            UserLegend = Labels(ia); 
            a = cellfun(@isempty,UserLegend);
            str = string(cc);
            aa = cellstr(str);
            aa(~a) = {''};
            UserLegend(a) = {''};
            ab = append(aa,UserLegend);                     
            if isempty(UserLegend{1})
                UserLegend{1} = '0';                
            end
        end    

        if sum(GNATData.ClassesValue == '0') == 1
            UserLegend{1} = '0';
            colors = ['r', colors];
        else
            % do nothing
        end
        
        % Permutating the number of symbols and colors for classes > 7
        if size(ClassesValue,1) > size(colors,2)
            k = ceil(size(ClassesValue,1)./size(colors,2));
            c = repmat(colors,1,k);
            Clr = c(1:size(ClassesValue,1));
        else
            c = repmat(colors,1,2);
            Clr = c(1:size(ClassesValue,1));
        end      

        if size(ClassesValue,1) > size(symbols,2)
            k = ceil(size(ClassesValue,1)./size(symbols,2));
            s = repmat(symbols,1,k);  
            Sym = s(1:size(ClassesValue,1));          
        else
            s = repmat(symbols,1,2);
            Sym = s(1:size(ClassesValue,1));         
        end     
        
        % Parameters to construct plots
        S = char(Sym);
        X = sum(GNATData.PlotOpt);       
        Opt = GNATData.PlotOpt; 
        
        if X==1
%------- One plot            
            if Opt(1) == 1
                 % 3D SCORE
                 % Defining the current axis
                 if get(hCheckUse3D,'value')
                     % Plotting 3D data with classes
                     %Cleaning Axis
                     cla(Axes)

                     GUIData.Axes.h3 = gscatter3(...
                        GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),...
                        GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))),...
                        GNATData.parameters.Scores(:,(get(hpopupPCZ,'value'))),...
                        Classes,Clr,S,6,'auto');   
                     axis('tight');

                     % Defing the apperance 
                     set(GUIData.Axes.h3,'LineWidth',1);
                     set(Axes,'LineWidth',1); 
                     set(Axes,'Box','on');
         
                     % Determining the ellipses for every class 
                     hold on;
                     res_list = Error_elipse3D(GNATData.parameters.Scores(:,[(get(hpopupPCX,'value')),(get(hpopupPCY,'value')),(get(hpopupPCZ,'value'))]),Classes,Clr, ...
                         get(hpopupPCX,'value'),get(hpopupPCY,'value'),get(hpopupPCZ,'value'));
                     if res_list.exit == 1
                         return
                     end
                     hold off;

                     % Determining the limits for X, Y and Z axis
                     set(Axes,'XLim',[-max(abs(get(Axes,'XLim'))).*1.5 max(abs(get(Axes,'XLim'))).*1.5]);
                     set(Axes,'YLim',[-max(abs(get(Axes,'YLim'))).*1.5 max(abs(get(Axes,'YLim'))).*1.5]);
                     set(Axes,'ZLim',[-max(abs(get(Axes,'ZLim'))).*1.5 max(abs(get(Axes,'ZLim'))).*1.5]);

                     % Determining the axis labels
                     xlabel(Axes,GNATData.parameters.AxesPlot((get(hpopupPCX,'value')),1),'FontSize',10, 'FontWeight','bold');
                     ylabel(Axes,GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                     zlabel(Axes,GNATData.parameters.AxesPlot((get(hpopupPCZ,'value')),1),'FontSize',10, 'FontWeight','bold');
                     line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
                     line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');
                     line([0 0],[0 0],[min(zlim) max(zlim)],'color',[1 0 0],'linestyle','--');
                                                            
                     % Displaying the labels and legend for points
                     GNATData.labelScore = text(GNATData.parameters.Scores(:,(get(hpopupPCX,'value')))*1.1,GNATData.parameters.Scores(:,(get(hpopupPCY,'value')))*1.1,GNATData.parameters.Scores(:,(get(hpopupPCZ,'value')))*1.1,labels_s);
                     if ~isempty(Labels)
                        GNATData.legendScore = legend(Axes,ab,'Location','northwest');
                     else
                        GNATData.legendScore = legend(Axes,ClassesValue,'Location','northwest');
                     end        

                     % Check the user plot inputs
                     EnableLabel_Callback()
                     EnableLegend_Callback()
                     EnableEllipse_Callback()
                 % 2D SCORE
                 else
                     % Plotting 2D data with classes
                     GUIData.Axes.h = gscatter(GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))),...
                        Classes,Clr,S,6,'on');                  
                     for n = 1:length(GUIData.Axes.h)                             
                         set(GUIData.Axes.h(n,1), 'MarkerFaceColor', Clr(n));
                     end                   
                     set(Axes, 'YLimMode', 'auto');
                     set(Axes, 'YLimMode', 'auto');   

                     % Defing the apperance               
                     set(GUIData.Axes.h,'LineWidth',1);
                     set(Axes,'LineWidth',1);
                     set(Axes,'Box','on');

                     % Determining the ellipses for all data points
                     res_list = ellipseParam(GNATData.parameters.Scores, 2, (get(hpopupPCX,'value')), (get(hpopupPCY,'value')),1);
                     if res_list.exit == 1
                         return
                     end

                     % Plot the first ellipse 95%
                     [~,xax,yax]=ellipse_GNAT(res_list.Ellipse{1,1}, res_list.Ellipse{1,2}, 0, 0, 0, 'r','--');

                     % Plot the second ellipse 99%
                     ellipse_GNAT(res_list.Ellipse{1,3}, res_list.Ellipse{1,4}, 0, 0, 0, 'b','--');

                     % Determining the ellipses for every class
                     hold on;
                     Error_elipse(GNATData.parameters.Scores(:,[(get(hpopupPCX,'value')),(get(hpopupPCY,'value'))]),Classes,Clr) 
                     hold off;

                     % Painting black (Rolling stones) the area outside the elipse
                     axis tight
                     xl = xlim; yl = ylim;
                     xlim([xl(1)*1.05 xl(2)*1.05])
                     ylim([yl(1)*1.5 yl(2)*1.5])
                     xl = xlim; yl = ylim;
                     x_frame=[xl(1),xl(2),xl(2),xl(1),xl(1)];
                     y_frame=[yl(1),yl(1),yl(2),yl(2),yl(1)];                      
                     x = [x_frame, xax]; 
                     y = [y_frame, yax];
                     fill = patch(x,y, [0 0 0.25], 'EdgeColor', 'none');
                     alpha(fill,0.06)
                     axis tight % optional

                     % Determining the axis labels
                     xlabel(Axes,GNATData.parameters.AxesPlot((get(hpopupPCX,'value')),1),'FontSize',10, 'FontWeight','bold');
                     ylabel(Axes,GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                     line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
                     line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');
                     
                     % Displaying the labels and legend for points
                     GNATData.labelScore = labelpoints(GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))), labels_s,'N',0.05,1, 'FontSize', 10); 
                     if ~isempty(Labels)
                        GNATData.legendScore = legend(Axes,ab,'Location','northwest');
                     else
                        GNATData.legendScore = legend(Axes,ClassesValue,'Location','northwest');
                     end        

                     grid on
                     GNATData.legendScore.String = GNATData.legendScore.String(1:n);

                     % Check the user plot inputs
                     EnableLabel_Callback()
                     EnableLegend_Callback()
                     EnableEllipse_Callback()
                end    
            % Loadings
            elseif Opt(2) == 1
                % BinPCA = 1
                axes(Axes);
                if isfield(GNATData,'BinPCA')
                    % 2D Loadings
                    if get(hCheck2DLoadings,'value')
                        GUIData.Axes.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(Axes,'Box','on');
                        set(gca,'xdir','reverse');
                        set(Axes,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Variables','FontSize',10, 'FontWeight','bold');
                        ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                        guidata(hPLOTfigure,GUIData); 
                        row = dataTipTextRow("Variable",GNATData.BinPCA.number_of_variables);
                        GUIData.Axes.h.DataTipTemplate.DataTipRows(end+1) = row;
                    % 1D Loadings
                    else
                        GUIData.Axes.h=plot(GNATData.BinPCA.number_of_variables,GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(gca,'xdir','reverse');
                        set(Axes,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold');
                        row = dataTipTextRow("Variable",GNATData.BinPCA.number_of_variables);
                        GUIData.Axes.h.DataTipTemplate.DataTipRows(end+1) = row;                        
                    end
                % BinPCA = 0
                else
                    % 2D Loadings
                    if get(hCheck2DLoadings,'value')
                        GUIData.Axes.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(gca,'xdir','reverse');
                        set(Axes,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Variables','FontSize',10, 'FontWeight','bold');
                        ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                        guidata(hPLOTfigure,GUIData); 
                        row = dataTipTextRow("Variable",GNATData.ppmscale(1,:));
                        GUIData.Axes.h.DataTipTemplate.DataTipRows(end+1) = row;
                        
                    else
                        GUIData.Axes.h=plot(GNATData.ppmscale(1,:),GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(gca,'xdir','reverse');
                        set(Axes,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold');   
                        row = dataTipTextRow("Variable",GNATData.ppmscale(1,:));
                        GUIData.Axes.h.DataTipTemplate.DataTipRows(end+1) = row;                        
                    end
                end
            % Residuals
            elseif Opt(3) == 1
                axes(Axes);             
                GUIData.Axes.h = gscatter(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:),Classes,Clr,S,6,'off');               
                for n = 1:length(GUIData.Axes.h)
                  set(GUIData.Axes.h(n,1), 'MarkerFaceColor', Clr(n));
                end              
                axis('tight');
                set(gca,'Box','on');  
                set(gca,'LineWidth',1);
                xlabel('Hotteling T²','FontSize',10, 'FontWeight','bold');
                ylabel('Q Residuals','FontSize',10, 'FontWeight','bold');
                if max(GNATData.parameters.Qres) > GNATData.parameters.Qlim
                    line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (max(GNATData.parameters.Qres)).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                                      
                else
                    line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (GNATData.parameters.Qlim).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                      
                end
                if max(GNATData.parameters.T2) > GNATData.parameters.T2lim
                    line([0 (max(GNATData.parameters.T2)).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                                                       
                else
                    line([0 (GNATData.parameters.T2lim).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                   
                end                                  
                GNATData.labelResidual = labelpoints(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:), labels_s,'N',0.05,1, 'FontSize', 10);  
                if ~isempty(Labels)
                   GNATData.legendResidual = legend(Axes,ab,'Location','northwest');
                else
                   GNATData.legendResidual = legend(Axes,ClassesValue,'Location','northwest');
                end     

                % Check the user plot inputs
                EnableLabel_Callback()
                EnableLegend_Callback()
            end           
        elseif X==2
%------- Two plots            
            if Opt (1) == 1
                % Score + Loadings
                axes(Axes21)
                axis('tight');
                % 3D SCORE
                %Cleaning Axis
                cla(Axes21)
                if get(hCheckUse3D,'value')
                    GUIData.Axes21.h = gscatter3(...
                        GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),...
                        GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))),...
                        GNATData.parameters.Scores(:,(get(hpopupPCZ,'value'))),...
                        Classes,Clr,S,6,'auto');        
                     axis('tight');

                     % Defing the apperance 
                     set(GUIData.Axes21.h,'LineWidth',1);
                     set(Axes21,'LineWidth',1); 
                     set(Axes21,'Box','on');

                     % Determining the ellipses for every class
                     hold on;
                     res_list = Error_elipse3D(GNATData.parameters.Scores(:,[(get(hpopupPCX,'value')),(get(hpopupPCY,'value')),(get(hpopupPCZ,'value'))]),Classes,Clr, ...
                          get(hpopupPCX,'value'),get(hpopupPCY,'value'),get(hpopupPCZ,'value'));
                     if res_list.exit == 1
                         return
                     end
                     hold off;
                        
                     % Determining the limits for X, Y and Z axis
                     set(Axes21,'XLim',[-max(abs(get(Axes21,'XLim'))).*1.5 max(abs(get(Axes21,'XLim'))).*1.5]);
                     set(Axes21,'YLim',[-max(abs(get(Axes21,'YLim'))).*1.5 max(abs(get(Axes21,'YLim'))).*1.5]);
                     set(Axes21,'ZLim',[-max(abs(get(Axes21,'ZLim'))).*1.5 max(abs(get(Axes21,'ZLim'))).*1.5]);

                     % Determining the axis labels
                     xlabel(Axes21,GNATData.parameters.AxesPlot((get(hpopupPCX,'value')),1),'FontSize',10, 'FontWeight','bold');
                     ylabel(Axes21,GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                     zlabel(Axes21,GNATData.parameters.AxesPlot((get(hpopupPCZ,'value')),1),'FontSize',10, 'FontWeight','bold');
                     line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
                     line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');
                     line([0 0],[0 0],[min(zlim) max(zlim)],'color',[1 0 0],'linestyle','--');
                                                        
                     % Displaying the labels and legend for points
                     GNATData.labelScore = text(GNATData.parameters.Scores(:,(get(hpopupPCX,'value')))*1.1,GNATData.parameters.Scores(:,(get(hpopupPCY,'value')))*1.1,GNATData.parameters.Scores(:,(get(hpopupPCZ,'value')))*1.1,labels_s);
                     if ~isempty(Labels)
                        GNATData.legendScore = legend(Axes21,ab,'Location','northwest');
                     else
                        GNATData.legendScore = legend(Axes21,ClassesValue,'Location','northwest');
                     end              

                     % Check the user plot inputs
                     EnableLabel_Callback()
                     EnableLegend_Callback()
                     EnableEllipse_Callback()
                % 2D Score
                else
                    GUIData.Axes21.h = gscatter(GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))),Classes,Clr,S,6,'off');    
                    for n = 1:length(GUIData.Axes21.h)
                      set(GUIData.Axes21.h(n,1), 'MarkerFaceColor', Clr(n));
                    end   

                     % Defing the apperance    
                     set(GUIData.Axes21.h,'LineWidth',1);
                     set(Axes21,'LineWidth',1);
                     set(Axes21,'Box','on');

                     set(Axes21, 'YLimMode', 'auto');
                     set(Axes21, 'YLimMode', 'auto');    
                   
                     % Determining the ellipses for all data points
                     res_list = ellipseParam(GNATData.parameters.Scores, 2, (get(hpopupPCX,'value')), (get(hpopupPCY,'value')),1);
                     if res_list.exit == 1
                         return
                     end

                     % Plot the first ellipse 95%
                     [~,xax,yax]=ellipse_GNAT(res_list.Ellipse{1,1}, res_list.Ellipse{1,2}, 0, 0, 0, 'r','--');
                     
                     % Plot the second ellipse 99%
                     hfinal2=ellipse_GNAT(res_list.Ellipse{1,3}, res_list.Ellipse{1,4}, 0, 0, 0, 'b','--');
                     
                     % Determining the ellipses for every class
                     hold on;
                     Error_elipse(GNATData.parameters.Scores(:,[(get(hpopupPCX,'value')),(get(hpopupPCY,'value'))]),Classes,Clr) 
                     hold off; 

                     % Painting black (Rolling stones) the area outside the elipse
                     axis tight 
                     xl = xlim; yl = ylim;
                     xlim([xl(1)*1.05 xl(2)*1.05])
                     ylim([yl(1)*1.5 yl(2)*1.5])
                     xl = xlim; yl = ylim;
                     x_frame=[xl(1),xl(2),xl(2),xl(1),xl(1)];
                     y_frame=[yl(1),yl(1),yl(2),yl(2),yl(1)];                    
                     x = [x_frame, xax]; 
                     y = [y_frame, yax];
                     fill = patch(x,y, [0 0 0.25], 'EdgeColor', 'none');
                     alpha(fill,0.06)
                     axis tight % optional
                       
                     % Determining the axis labels
                     xlabel(Axes21,GNATData.parameters.AxesPlot((get(hpopupPCX,'value')),1),'FontSize',10, 'FontWeight','bold');
                     ylabel(Axes21,GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                     line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
                     line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');

                     % Displaying the labels and legend for points
                     GNATData.labelScore = labelpoints(GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))), labels_s,'N',0.05,1, 'FontSize', 10);
                     if ~isempty(Labels)
                        GNATData.legendScore = legend(Axes21,ab,'Location','northwest');
                     else
                        GNATData.legendScore = legend(Axes21,ClassesValue,'Location','northwest');
                     end
  
                     grid on                              
                     GNATData.legendScore.String = GNATData.legendScore.String(1:n);

                     % Check the user plot inputs
                     EnableLabel_Callback()
                     EnableLegend_Callback()
                     EnableEllipse_Callback()
                end  
                
                if Opt (2) == 1
                    % BinPCA = 1
                    axes(Axes22)
                    if isfield(GNATData,'BinPCA')
                        % 2D Loadings
                        if get(hCheck2DLoadings,'value')
                            GUIData.Axes22.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                            axis('tight');
                            set(GUIData.Axes22.h,'LineWidth',1);
                            set(gca,'LineWidth',1);
                            set(Axes22,'Box','on');
                            set(gca,'xdir','reverse');
                            set(Axes22,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                            xlabel('Variables','FontSize',10, 'FontWeight','bold');
                            ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                            guidata(hPLOTfigure,GUIData); 
                            row = dataTipTextRow("Variable",GNATData.BinPCA.number_of_variables);
                            GUIData.Axes.h.DataTipTemplate.DataTipRows(end+1) = row;                           
                        % 1D Loadings
                        else
                         GUIData.Axes22.h=plot(GNATData.BinPCA.number_of_variables,GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                            axis('tight');
                            set(GUIData.Axes22.h,'LineWidth',1);
                            set(gca,'LineWidth',1);
                            set(gca,'xdir','reverse');
                            set(Axes22,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                            xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold'); 
                        end
                    % BinPCA = 0
                    else
                        if get(hCheck2DLoadings,'value')
                            GUIData.Axes22.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                            axis('tight');
                            set(GUIData.Axes22.h,'LineWidth',1);
                            set(gca,'LineWidth',1);
                            set(gca,'xdir','reverse');
                            set(Axes22,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                            xlabel('Variables','FontSize',10, 'FontWeight','bold');
                            ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                            guidata(hPLOTfigure,GUIData);  
                            row = dataTipTextRow("Variable",GNATData.ppmscale(1,:));
                            GUIData.Axes22.h.DataTipTemplate.DataTipRows(end+1) = row;
                        else
                         GUIData.Axes22.h=plot(GNATData.ppmscale(1,:),GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                            axis('tight');
                            set(GUIData.Axes22.h,'LineWidth',1);
                            set(gca,'LineWidth',1);
                            set(gca,'xdir','reverse');
                            set(Axes22,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                            xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold');   
                        end
                    end
                
                % Score + Residuals    
                elseif Opt(3) == 1
                    axes(Axes22)
                    GUIData.Axes22.h = gscatter(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:),Classes,Clr,S,6,'off');                    
                    for n = 1:length(GUIData.Axes22.h)
                      set(GUIData.Axes22.h(n,1), 'MarkerFaceColor', Clr(n));
                    end                                                   
                    set(GUIData.Axes22.h,'LineWidth',1);
                    axis('tight');
                    set(gca,'Box','on');
                    set(gca,'LineWidth',1);                      
                    xlabel('Hotteling T²','FontSize',10, 'FontWeight','bold');
                    ylabel('Q Residuals','FontSize',10, 'FontWeight','bold');
                    if max(GNATData.parameters.Qres) > GNATData.parameters.Qlim
                        line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (max(GNATData.parameters.Qres)).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                                      
                    else
                        line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (GNATData.parameters.Qlim).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                      
                    end
                    if max(GNATData.parameters.T2) > GNATData.parameters.T2lim
                        line([0 (max(GNATData.parameters.T2)).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                                                       
                    else
                        line([0 (GNATData.parameters.T2lim).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                   
                    end                    
                    GNATData.labelResidual = labelpoints(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:), labels_s,'N',0.05,1, 'FontSize', 10); %change this function (label points) to another
                    if ~isempty(Labels)
                        GNATData.legendResidual = legend(Axes22,ab, 'Location','northwest');
                    else
                        GNATData.legendResidual = legend(Axes22,ClassesValue, 'Location','northwest');
                    end      

                    % Check the user plot inputs
                    EnableLabel_Callback()
                    EnableLegend_Callback()
                end
            % Loading + Residuals
            elseif Opt (1) == 0
                axes(Axes21)
                if isfield(GNATData,'BinPCA')
                    % 2D Loadings
                    if get(hCheck2DLoadings,'value')
                        GUIData.Axes21.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes21.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(Axes21,'Box','on');
                        set(gca,'xdir','reverse');
                        set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Variables','FontSize',10, 'FontWeight','bold');
                        ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                        guidata(hPLOTfigure,GUIData); 
                        row = dataTipTextRow("Variable",GNATData.BinPCA.number_of_variables);
                        GUIData.Axes.h.DataTipTemplate.DataTipRows(end+1) = row;                      
                    % 1D Loadings
                    else
                     GUIData.Axes21.h=plot(GNATData.BinPCA.number_of_variables,GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes21.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(gca,'xdir','reverse');
                        set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold'); 
                    end
                % BinPCA = 0
                else
                    if get(hCheck2DLoadings,'value')
                        GUIData.Axes21.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes21.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(gca,'xdir','reverse');
                        set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Variables','FontSize',10, 'FontWeight','bold');
                        ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                        guidata(hPLOTfigure,GUIData);     
                        row = dataTipTextRow("Variable",GNATData.ppmscale(1,:));
                        GUIData.Axes21.h.DataTipTemplate.DataTipRows(end+1) = row;
                    else
                     GUIData.Axes21.h=plot(GNATData.ppmscale(1,:),GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                        axis('tight');
                        set(GUIData.Axes21.h,'LineWidth',1);
                        set(gca,'LineWidth',1);
                        set(gca,'xdir','reverse');
                        set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                        xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold');                       
                    end
                end

                axes(Axes22)
                GUIData.Axes22.h = gscatter(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:),Classes,Clr,S,6,'off'); 
                for n = 1:length(GUIData.Axes22.h)
                  set(GUIData.Axes22.h(n,1), 'MarkerFaceColor', Clr(n));
                end                 

                set(gca,'Box','on');
                set(gca,'LineWidth',1);                 
                xlabel('Hotteling T²','FontSize',10, 'FontWeight','bold');
                ylabel('Q Residuals','FontSize',10, 'FontWeight','bold');              
                if max(GNATData.parameters.Qres) > GNATData.parameters.Qlim
                    line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (max(GNATData.parameters.Qres)).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                                      
                else
                    line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (GNATData.parameters.Qlim).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                      
                end
                if max(GNATData.parameters.T2) > GNATData.parameters.T2lim
                    line([0 (max(GNATData.parameters.T2)).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                                                       
                else
                    line([0 (GNATData.parameters.T2lim).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                   
                end  
                GNATData.labelResidual = labelpoints(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:), labels_s,'N',0.05,1, 'FontSize', 10); %change function for another  
                if ~isempty(Labels)
                    GNATData.legendResidual = legend(Axes22,ab, 'Location','northwest');
                else
                    GNATData.legendResidual = legend(Axes22,ClassesValue, 'Location','northwest');
                end    
                    
                % Check the user plot inputs
                EnableLabel_Callback()
                EnableLegend_Callback()
            end        
        elseif X==3
%------- Three plots             
            %% Score plot
            axes(Axes31)

            cla(Axes31)
            if get(hCheckUse3D,'value')
                GUIData.Axes31.h = gscatter3(...
                    GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),...
                    GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))),...
                    GNATData.parameters.Scores(:,(get(hpopupPCZ,'value'))),...
                    Classes,Clr,S,6,'auto'); 
                 axis('tight');

                 % Defing the apperance 
                 set(GUIData.Axes31.h,'LineWidth',1);
                 set(Axes31,'LineWidth',1); 
                 set(Axes31,'Box','on');

                 % Determining the ellipses for every class
                 hold on;
                 res_list = Error_elipse3D(GNATData.parameters.Scores(:,[(get(hpopupPCX,'value')),(get(hpopupPCY,'value')),(get(hpopupPCZ,'value'))]),Classes,Clr, ...
                      get(hpopupPCX,'value'),get(hpopupPCY,'value'),get(hpopupPCZ,'value'));
                 if res_list.exit == 1
                     return
                 end
                 hold off;
                   
                 % Determining the limits for X, Y and Z axis
                 set(Axes31,'XLim',[-max(abs(get(Axes31,'XLim'))).*1.5 max(abs(get(Axes31,'XLim'))).*1.5]);
                 set(Axes31,'YLim',[-max(abs(get(Axes31,'YLim'))).*1.5 max(abs(get(Axes31,'YLim'))).*1.5]);
                 set(Axes31,'ZLim',[-max(abs(get(Axes31,'ZLim'))).*1.5 max(abs(get(Axes31,'ZLim'))).*1.5]);

                 % Determining the axis labels
                 xlabel(Axes31,GNATData.parameters.AxesPlot((get(hpopupPCX,'value')),1),'FontSize',10, 'FontWeight','bold');
                 ylabel(Axes31,GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                 zlabel(Axes31,GNATData.parameters.AxesPlot((get(hpopupPCZ,'value')),1),'FontSize',10, 'FontWeight','bold');
                 line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
                 line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');
                 line([0 0],[0 0],[min(zlim) max(zlim)],'color',[1 0 0],'linestyle','--');
                                                        
                 % Displaying the labels and legend for points
                 GNATData.labelScore = text(GNATData.parameters.Scores(:,(get(hpopupPCX,'value')))*1.1,GNATData.parameters.Scores(:,(get(hpopupPCY,'value')))*1.1,GNATData.parameters.Scores(:,(get(hpopupPCZ,'value')))*1.1,labels_s);
                 if ~isempty(Labels)
                     GNATData.legendScore = legend(Axes31,ab,'Location','northwest');
                 else
                     GNATData.legendScore = legend(Axes31,ClassesValue,'Location','northwest');
                 end

                 % Check the user plot inputs
                 EnableLabel_Callback()
                 EnableLegend_Callback()
                 EnableEllipse_Callback()
            % 2D SCORE     
            else
                 GUIData.Axes31.h = gscatter(GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))),...
                    Classes,Clr,S,6,'off');

                 for n = 1:length(GUIData.Axes31.h)
                   set(GUIData.Axes31.h(n,1), 'MarkerFaceColor', Clr(n));
                 end      
                 set(Axes31, 'YLimMode', 'auto');
                 set(Axes31, 'YLimMode', 'auto');    

                 % Defing the apperance  
                 set(GUIData.Axes31.h,'LineWidth',1);
                 set(Axes31,'LineWidth',1);
                 set(Axes31,'Box','on');

                 % Determining the ellipses for all data points
                 res_list = ellipseParam(GNATData.parameters.Scores, 2, (get(hpopupPCX,'value')), (get(hpopupPCY,'value')),1);
                 if res_list.exit == 1
                     return
                 end

                 % Plot the first ellipse 95%
                 [~,xax,yax]=ellipse_GNAT(res_list.Ellipse{1,1}, res_list.Ellipse{1,2}, 0, 0, 0, 'r','--');

                 % Plot the second ellipse 99%
                 hfinal2=ellipse_GNAT(res_list.Ellipse{1,3}, res_list.Ellipse{1,4}, 0, 0, 0, 'b','--');

                 % Displaying the labels and legend for points
                 hold on;
                 Error_elipse(GNATData.parameters.Scores(:,[(get(hpopupPCX,'value')),(get(hpopupPCY,'value'))]),Classes,Clr) 
                 hold off;

                 % Painting black (Rolling stones) the area outside the elipse
                 axis tight
                 xl = xlim; yl = ylim;
                 xlim([xl(1)*1.05 xl(2)*1.05])
                 ylim([yl(1)*1.5 yl(2)*1.5])
                 xl = xlim; yl = ylim;
                 x_frame=[xl(1),xl(2),xl(2),xl(1),xl(1)];
                 y_frame=[yl(1),yl(1),yl(2),yl(2),yl(1)];               
                 x = [x_frame, xax]; 
                 y = [y_frame, yax];
                 fill = patch(x,y, [0 0 0.25], 'EdgeColor', 'none');
                 alpha(fill,0.06)
                 axis tight % optional  
                               
                 % Determining the axis labels
                 xlabel(Axes31,GNATData.parameters.AxesPlot((get(hpopupPCX,'value')),1),'FontSize',10, 'FontWeight','bold');
                 ylabel(Axes31,GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                 line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
                 line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');

                 % Displaying the labels and legend for points
                 GNATData.labelScore = labelpoints(GNATData.parameters.Scores(:,(get(hpopupPCX,'value'))),GNATData.parameters.Scores(:,(get(hpopupPCY,'value'))), labels_s,'N',0.05,1, 'FontSize', 10);
                 if ~isempty(Labels)
                     GNATData.legendScore = legend(Axes31,ab,'Location','northwest');
                 else
                     GNATData.legendScore = legend(Axes31,ClassesValue,'Location','northwest');
                 end 
                 grid on 
                 GNATData.legendScore.String = GNATData.legendScore.String(1:n);

                 % Check the user plot inputs
                 EnableLabel_Callback()
                 EnableLegend_Callback()
                 EnableEllipse_Callback()
            end             
            %% Loading plot
            axes(Axes32)
            if isfield(GNATData,'BinPCA')
                % 2D Loadings
                if get(hCheck2DLoadings,'value')
                    GUIData.Axes32.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                    axis('tight');
                    set(GUIData.Axes32.h,'LineWidth',1);
                    set(gca,'LineWidth',1);
                    set(Axes21,'Box','on');
                    set(gca,'xdir','reverse');
                    set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                    xlabel('Variables','FontSize',10, 'FontWeight','bold');
                    ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                    guidata(hPLOTfigure,GUIData); 
                    row = dataTipTextRow("Variable",GNATData.BinPCA.number_of_variables);
                    GUIData.Axes.h.DataTipTemplate.DataTipRows(end+1) = row;                      
                % 1D Loadings
                else
                 GUIData.Axes32.h=plot(GNATData.BinPCA.number_of_variables,GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                    axis('tight');
                    set(GUIData.Axes32.h,'LineWidth',1);
                    set(gca,'LineWidth',1);
                    set(gca,'xdir','reverse');
                    set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                    xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold'); 
                end
            % BinPCA = 0
            else
                if get(hCheck2DLoadings,'value')
                    GUIData.Axes32.h=scatter(GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))),GNATData.parameters.Loadings(:,(get(hpopupPCYLoading,'value'))));
                    axis('tight');
                    set(GUIData.Axes32.h,'LineWidth',1);
                    set(gca,'LineWidth',1);
                    set(gca,'xdir','reverse');
                    set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                    xlabel('Variables','FontSize',10, 'FontWeight','bold');
                    ylabel(GNATData.parameters.AxesPlot((get(hpopupPCY,'value')),1),'FontSize',10, 'FontWeight','bold');
                    guidata(hPLOTfigure,GUIData);     
                    row = dataTipTextRow("Variable",GNATData.ppmscale(1,:));
                    GUIData.Axes32.h.DataTipTemplate.DataTipRows(end+1) = row;
                else
                 GUIData.Axes32.h=plot(GNATData.ppmscale(1,:),GNATData.parameters.Loadings(:,(get(hpopupPCXLoading,'value'))));
                    axis('tight');
                    set(GUIData.Axes32.h,'LineWidth',1);
                    set(gca,'LineWidth',1);
                    set(gca,'xdir','reverse');
                    set(Axes21,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
                    xlabel('Chemical shift (ppm)','FontSize',10, 'FontWeight','bold');                       
                end
            end
            
            %% Residual plot
            axes(Axes33);axis('tight'); 
            GUIData.Axes33.h = gscatter(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:),Classes,Clr,S,6,'off');
            for n = 1:length(GUIData.Axes33.h)
              set(GUIData.Axes33.h(n,1), 'MarkerFaceColor', Clr(n));
            end                                     
            set(GUIData.Axes33.h,'LineWidth',1);set(gca,'LineWidth',1);set(gca,'Box','on');             
            xlabel('Hotteling T²','FontSize',10, 'FontWeight','bold');
            ylabel('Q Residuals','FontSize',10, 'FontWeight','bold');
            if max(GNATData.parameters.Qres) > GNATData.parameters.Qlim
                line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (max(GNATData.parameters.Qres)).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                                      
            else
                line([GNATData.parameters.T2lim GNATData.parameters.T2lim],[0 (GNATData.parameters.Qlim).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                      
            end
            if max(GNATData.parameters.T2) > GNATData.parameters.T2lim
                line([0 (max(GNATData.parameters.T2)).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                                                       
            else
                line([0 (GNATData.parameters.T2lim).*1.25],[GNATData.parameters.Qlim GNATData.parameters.Qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                   
            end  
            GNATData.labelResidual = labelpoints(GNATData.parameters.T2(1,:),GNATData.parameters.Qres(1,:), labels_s,'N',0.05,1, 'FontSize', 10); %change function for another 
            if ~isempty(Labels)
                GNATData.legendResidual = legend(Axes33,ab, 'Location','northwest');
            else
                GNATData.legendResidual = legend(Axes33,ClassesValue, 'Location','northwest');
            end   

            % Check the user plot inputs
            EnableLabel_Callback()
            EnableLegend_Callback()
        end 
        guidata(hPLOTfigure,GUIData);       
    end
    function Error_elipse(Scores,Classes,Clr)
        GUIData = guidata(hPLOTfigure);
        [cUnq,~,~] = unique(Classes);
        numP = size(cUnq,1);
%         numC = size(cInd,1);
        for k = 1:numP
            % indices of points in this group
            idx = (Classes == cUnq(k));
        
            % substract mean
            Mu = mean(Scores(idx,:));
            X0 = bsxfun(@minus, Scores(idx,:), Mu);
        
            STD = 2;                     % 2 standard deviations
            conf = 2*normcdf(STD)-1;     % covers around 95% of population
            scale = chi2inv(conf,2);     % inverse chi-squared with dof=#dimensions
            
            Cov = cov(X0) * scale;
            [V, D] = eig(Cov);
            [D, order] = sort(diag(D), 'descend');
            D = diag(D);
            V = V(:, order);
        
            t = linspace(0,2*pi,100);
            e = [cos(t) ; sin(t)];        % unit circle            

            VV = V*sqrt(D);               % scale eigenvectors
            e = bsxfun(@plus, VV*e, Mu'); % project circle back to orig space
        
            % plot cov and major/minor axes
            fill = patch(e(1,:), e(2,:), Clr(k), 'EdgeColor', 'none');
            polyarea(e(1,:), e(2,:));
            alpha(fill,0.2)
            GUIData.fill(k) = fill;
        end
        guidata(hPLOTfigure,GUIData);
    end
    function res_list = Error_elipse3D(Scores,Classes,Clr,pcx, pcy, pcz)
        GUIData = guidata(hPLOTfigure);
        [cUnq,~,~] = unique(Classes);
        numP = size(cUnq,1);

        if pcx == 0 || pcy == 0 || pcz == 0
            warndlg('No component is provided either in PCx or PCy, or both.','Warning');
            res_list.exit = 1;
            return
        end
        
        if pcx == pcy || pcx == pcz || pcy == pcz
            warndlg('Please provide two different components in PCx, PCy and PCz.','Warning');
            res_list.exit = 1;
            return
        end

        for k = 1:numP
            % indices of points in this group
            idx = (Classes == k);
        
            % substract mean
            Mu = mean(Scores(idx,:));
            X0 = bsxfun(@minus, Scores(idx,:), Mu);
        
            STD = 2;                     % 2 standard deviations
            conf = 2*normcdf(STD)-1;     % covers around 95% of population
            scale = chi2inv(conf,2);     % inverse chi-squared with dof=#dimensions
            
            Cov = cov(X0) * scale;

            [U,L] = eig(Cov);
            
            % For N standard deviations spread of data, the radii of the eliipsoid will
            % be given by N*SQRT(eigenvalues).
            
            N = 1; % choose your own N
            radii = N*sqrt(diag(L));
            
            % generate data for "unrotated" ellipsoid
            [xc,yc,zc] = ellipsoid(0,0,0,radii(1),radii(2),radii(3));
            
            % rotate data with orientation matrix U and center M
            a = kron(U(:,1),xc); 
            b = kron(U(:,2),yc); 
            c = kron(U(:,3),zc);

            data = a+b+c; 
            n = size(data,2);
            x = data(1:n,:)+Mu(1); 
            y = data(n+1:2*n,:)+Mu(2); 
            z = data(2*n+1:end,:)+Mu(3);
            
            fill = surf(x,y,z,'FaceAlpha',0.1);
            fill.EdgeColor = convertCharsToStrings(Clr(k));
            fill.EdgeAlpha = 0.5;
            fill.MeshStyle = 'column';
            fill.FaceColor = convertCharsToStrings(Clr(k)); 

            GUIData.fill(k) = fill;
        end
        res_list.exit = 0;
        guidata(hPLOTfigure,GUIData);
    end
    function EnableZaxis_Callback(source,eventdata)
        if get(hCheckUse3D,'value')
            set(hpopupPCZ,'enable','on')
            PlotCheck_Callback()
        else
            set(hpopupPCZ,'enable','off')
            PlotCheck_Callback()
        end
    end
    function Enable2DLoading_Callback(source,eventdata)
        if get(hCheck2DLoadings,'value')
            set(hpopupPCYLoading,'enable','on')
            PlotCheck_Callback()
        else
            set(hpopupPCYLoading,'enable','off')
            PlotCheck_Callback()
        end
    end
    function ChangingScore_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);
        PlotCheck_Callback()        
        guidata(hPLOTfigure,GUIData);
    end  
    function EnableLabel_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);
        if strcmp(method, 'PCA') 
            if get(hCheckLabels,'value')
                if isfield(GNATData,'labelScore')
                    set(GNATData.labelScore,'Visible','on')
                end
                if isfield(GNATData,'labelResidual')
                    set(GNATData.labelResidual,'Visible','on')
                end 
                if isfield(GNATData,'labelLoading')
                    set(GNATData.labelLoading,'Visible','off')
                end             
            else
                if isfield(GNATData,'labelScore')
                    set(GNATData.labelScore,'Visible','off')
                end
                if isfield(GNATData,'labelResidual')
                    set(GNATData.labelResidual,'Visible','off')
                end 
                if isfield(GNATData,'labelLoading')
                    set(GNATData.labelLoading,'Visible','off')
                end 
            end
        elseif strcmp(method, 'PLSDA')
            if get(hCheckLabels_pls,'value')
                set(GNATData.labelScore,'Visible','on')
            else
                set(GNATData.labelScore,'Visible','off')
            end            
        elseif strcmp(method, 'OPLSDA')
            if get(hCheckLabels_opls,'value')
                set(GNATData.labelScore,'Visible','on')
            else
                set(GNATData.labelScore,'Visible','off')
            end
        end
        guidata(hPLOTfigure,GUIData);
    end
    function EnableLegend_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);
        if strcmp(method, 'PCA') 
            if get(hCheckLegend,'value')
                if isfield(GNATData,'labelScore')
                    set(GNATData.legendScore,'Visible','on')
                else
                end
                if isfield(GNATData,'labelResidual')
                    set(GNATData.legendResidual,'Visible','on')
                else
                end            
            else
                if isfield(GNATData,'labelScore')
                    set(GNATData.legendScore,'Visible','off')
                else
                end
                if isfield(GNATData,'labelResidual') 
                    set(GNATData.legendResidual,'Visible','off')
                else
                end  
            end
        elseif strcmp(method, 'PLSDA')
            if get(hCheckLegend_pls,'value')
                set(GNATData.legendScore,'Visible','on')
            else
                set(GNATData.legendScore,'Visible','off')
            end
        elseif strcmp(method, 'OPLSDA')
            if get(hCheckLegend_opls,'value')
                set(GNATData.legendScore,'Visible','on')
            else
                set(GNATData.legendScore,'Visible','off')
            end            
        end
        guidata(hPLOTfigure,GUIData);
    end
    function EnableEllipse_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);
        if isfield(GUIData,'fill')
            if strcmp(method, 'PCA') 
                if get(hCheckEllipse,'value')
                    set(GUIData.fill,'Visible','on')
                else
                    set(GUIData.fill,'Visible','off')
                end
            elseif strcmp(method, 'PLSDA')
                if get(hCheckEllipse_pls,'value')
                    set(GUIData.fill,'Visible','on')
                else
                    set(GUIData.fill,'Visible','off')
                end           
            elseif strcmp(method, 'OPLSDA')
                if get(hCheckEllipse_opls,'value')
                    set(GUIData.fill,'Visible','on')
                else
                    set(GUIData.fill,'Visible','off')
                end           
            end     
        end
        guidata(hPLOTfigure,GUIData);
    end
%% ----------------- HCA

%% ----------------- iPLS
    function MethodCheck_iPLS_Callback(source,eventdata)
        GUIData.iPLS.method_cv = get(hMethodiPLS,'value');
        set(h_iPLS_Run,'Enable','off');

        switch GUIData.CV.method_cv
            case 1 %'K-fold'
                set(hEditFold,'Enable','on')
                set(hEditFold,'String',num2str(10))
                set(hSliderFold,'Enable','on')
                set(hFoldCV,'ForegroundColor',[0 0 0])
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])
                
                set(hEditDiv,'Enable','off')
                set(hSliderDiv,'Enable','off')
                set(hDivisiton,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                           
            case 2 %'Leane-One-Out'
                set(hEditFold,'Enable','off')
                set(hEditFold,'String',num2str(size(GNATData.xcal',2)))
                set(hSliderFold,'Enable','off')
                set(hFoldCV,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftFold,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightFold,'ForegroundColor',[0.5 0.5 0.5])

                set(hEditDiv,'Enable','off')
                set(hSliderDiv,'Enable','off')
                set(hDivisiton,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                
            case 3 %'Contiguous Block'
                set(hEditFold,'Enable','on')
                set(hSliderFold,'Enable','on')
                set(hFoldCV,'ForegroundColor',[0 0 0])
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])

                set(hEditDiv,'Enable','off')
                set(hSliderDiv,'Enable','off')
                set(hDivisiton,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                
            case 4 %'Monte Carlo'
                set(hEditFold,'Enable','on')
                set(hSliderFold,'Enable','on')
                set(hFoldCV,'ForegroundColor',[0 0 0])
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])

                set(hEditDiv,'Enable','on')
                set(hSliderDiv,'Enable','on')
                set(hDivisiton,'ForegroundColor',[0 0 0])
                set(hLeftDivision,'ForegroundColor',[0 0 0])
                set(hRightDivision,'ForegroundColor',[0 0 0])                 
            otherwise
                %Do nothing
        end

    end
    function iPLS_Apply_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  
        
        % Get user input: Cross-validation
        GUIData.iPLS.Fold = str2double(get(hEditFoldiPLS,'String'));
        GUIData.iPLS.LV = str2double(get(hEditCVGroupiPLS,'String'));
        GUIData.iPLS.Division = str2double(get(hEditDiviPLS,'String')); 
        GUIData.iPLS.shuffle = get(hCheckshuffleiPLS,'Value');
        GUIData.iPLS.method_cv = get(hMethodiPLS,'value');
        % Get user input
        GUIData.iPLS.Process = get(hiPLSprocess,'String');
        GUIData.iPLS.Intervals = str2num(get(hEditIntervals_iPLS,'string')); %#ok<ST2NM>
        GUIData.iPLS.Segments = str2double(get(hEditSegments_iPLS,'String'));
        GUIData.iPLS.Plottype = 'Cum';
        GUIData.iPLS.Labeltype = 'wavlabel'; %'wavlabel' 'intlabel' 'varlabel'
        GUIData.iPLS.Limits = get(hBinCheck,'Value');
        set(h_iPLS_Run,'Enable','on');        
        
        % Perform the division in Cal and Val
        [index,test_X,train_X,test_y,train_y] = CrossValidation_splits(GNATData.xcal,...
            GNATData.ycalM,GUIData.iPLS.method_cv,GUIData.iPLS.shuffle,GUIData.iPLS.Fold,GUIData.iPLS.Division);   

        % Save the split
        GUIData.iPLS.index = index;
        GUIData.iPLS.test_X = test_X;
        GUIData.iPLS.train_X = train_X;
        GUIData.iPLS.test_y = test_y;
        GUIData.iPLS.train_y = train_y;

        % Checking if the "External limits" option was selected
        if GUIData.iPLS.Limits == 2
        % Checking if the BinPCA GUI is oppen and the binning limits was calculated       
            hBinFigure = findobj('Type','figure','Tag','Bin');
            if ~isempty(hBinFigure)
                BinPCA = guidata(hBinFigure);
                if isfield(BinPCA,'index_intervals_ppm')
                    GUIData.iPLS.Intervals = BinPCA.index_intervals_ppm;
                end 
            end
        end       
        guidata(hPLOTfigure,GUIData); 
    end
    function iPLS_Run_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 
      
        % Separation of datasets according to the user's input
        NClass = size(GNATData.ycalM,2); 
        Division = (GUIData.iPLS.Division)./100; 
        
        % Matrix divided in calibration and validation at GNAT
        X = GNATData.xcal;
        Y = GNATData.ycalM;

        [~,ycl]=max(Y,[],2);
        Y=ycl; 
        ns=size(X,1);
        
        if isfield(GNATData,'BinPCA')
            Model=ipls(X,Y,GUIData.iPLS.LV,GUIData.iPLS.Process,GUIData.iPLS.Intervals,GNATData.BinPCA.intervals,'syst123',GUIData.iPLS.Segments);
            if Model.breakTag == 1
                return
            end
        else
            Model=ipls(X,Y,GUIData.iPLS.LV,GUIData.iPLS.Process,GUIData.iPLS.Intervals,Export_Inf.Specscale,'syst123',GUIData.iPLS.Segments);  
            if Model.breakTag == 1
                return
            end
        end
          
        plotipls=iplsplot(Model,GUIData.iPLS.Labeltype,[],[],GUIData.iPLS.Plottype);

        % Cumulated plots
        axes(AxesiPLS_residual)
        [~,m] = size(Model.rawX);
        if strcmp(GUIData.iPLS.Plottype,'Cum2')
            if strcmp(GUIData.iPLS.Labeltype,'wavlabel') && (Model.xaxislabels(1)>Model.xaxislabels(2))
                fill(flipud(plotipls.Xint(:)),plotipls.ResponseMinusTwoPC(:),'w',flipud(plotipls.Xint(:)),plotipls.ResponseMinusOnePC(:),'w', flipud(plotipls.Xint(:)),plotipls.Response(:),[0.75 0.75 0.75])
            else
                fill(plotipls.Xint(:),plotipls.ResponseMinusTwoPC(:),'w',plotipls.Xint(:),plotipls.ResponseMinusOnePC(:),'w', plotipls.Xint(:),plotipls.Response(:),[0.75 0.75 0.75])
            end
        elseif ismember(GUIData.iPLS.Plottype,plotipls.plottype_cell([1 3:end]))
            if strcmp(GUIData.iPLS.Labeltype,'wavlabel') && (Model.xaxislabels(1)>Model.xaxislabels(2))
                fill(flipud(plotipls.Xint(:)),plotipls.Response(:),[0.75 0.75 0.75])
            else
                fill(plotipls.Xint(:),plotipls.Response(:),[0.9 0.9 0.9]) % Note: substitute [0.75 0.75 0.75]'c' for cyan
            end
        else
            % Nothing
        end
        
        if strcmp(Model.val_method,'test')
            plottitle = sprintf('Dotted line is RMSEP for the ideal global model using %g LV''s',plotipls.optimal_lv_global);
            ylabel('RMSEP','FontSize',10)
        elseif strcmp(Model.val_method,'none')
            plottitle = sprintf('Dotted line is RMSEC for the ideal global model using %g LV''s',plotipls.optimal_lv_global);
            ylabel('RMSEC','FontSize',10)
        else
            plottitle = sprintf('Dotted line is RMSECV  for the ideal global model using %g LV''s',plotipls.optimal_lv_global);
            ylabel('RMSECV','FontSize',10)
        end
        title(plottitle,'FontSize',10,'FontWeight','Bold')                
        
        hold on
            axis tight;
            set(AxesiPLS_residual,'Xdir','reverse');
            ordinate = plotipls.RMSE(Model.intervals+1,plotipls.optimal_lv_global+1);
            actualaxis=axis;
            plot(AxesiPLS_residual,actualaxis(1:2),[1 1]*ordinate,':k', 'LineWidth', 2);
            
            if ~isempty(plotipls.max_yaxis)
                axis([actualaxis(1) actualaxis(2) actualaxis(3) plotipls.max_yaxis]);
                actualaxis(4)=plotipls.max_yaxis;
            end
            Xaxis = linspace(actualaxis(1),actualaxis(2),m);
            if strcmp(GUIData.iPLS.Labeltype,'wavlabel') && (Model.xaxislabels(1)>Model.xaxislabels(2))
                plot(AxesiPLS_residual,fliplr(Xaxis),plotipls.Xmean./max(plotipls.Xmean)*actualaxis(4),'-k') % Scaled spectrum
            else
                plot(AxesiPLS_residual,Xaxis,plotipls.Xmean./max(plotipls.Xmean)*actualaxis(4),'-k') % Scaled spectrum
            end
            set(AxesiPLS_residual,'XTick',plotipls.NumberofTicksandWhere)
            labels = arrayfun(@(v) sprintf('%.5f', v), round(plotipls.NumberofTicksandWhere,2), 'UniformOutput', false);
            set(AxesiPLS_residual,'XTick',str2double(labels))
            for i=1:Model.intervals
      	        if strcmp(GUIData.iPLS.Labeltype,'wavlabel') && (Model.xaxislabels(1)>Model.xaxislabels(2))
                    text(mean(plotipls.Xint(2:3,i)),0.03*(actualaxis(4)-actualaxis(3))+actualaxis(3),int2str(plotipls.min_ix(Model.intervals-(i-1))),'Color','k','FontAngle','italic');
                else
                    text(mean(plotipls.Xint(2:3,i)),0.03*(actualaxis(4)-actualaxis(3))+actualaxis(3),int2str(plotipls.min_ix(i)),'Color','b','FontAngle','italic');
                end
            end
        hold off

        [~,Idx] = min(plotipls.Response(2,:),[],2);

        plotarea = findobj(AxesiPLS_residual_idx_Tab, 'tag', 'ax2');           
        plsrmse(Model,Idx,plotarea);

        table = intervals(Model);
        set(hTable_iPLS_intervals,'Data',table);
        guidata(hPLOTfigure,GUIData); 
        return
% 
%         for i=1:GUIData.CV.LV
%             cmatrix{i}=cmatrixcalc(Ypredcv(:,i), Y, max(Y));
%             ccrate{i}=100*diag(cmatrix{i})./sum(cmatrix{i},2); 
%             cct(i)=100*sum(diag(cmatrix{i}))/length(Y);            
%         end

        model.CrossVal.ConfusionMatrix=cmatrix; 
        model.CrossVal.CorrClassRate=ccrate; 
        model.CrossVal.TotalClassErr=cct; 
        
        % ===============================
        % Error calculatio (RMSECV) as a average for all classes.
        plot(AxesRMSECV,1:GUIData.CV.LV, sum(model.rmsecv,2), 'o-r')
        xlabel(AxesRMSECV,'Number of Latent Variables','FontSize',14,'FontName','Times New Roman');
        ylabel(AxesRMSECV,'RMSECV (%)','FontSize',14,'FontName','Times New Roman');
        title(AxesRMSECV,'Selection of the optimal number of LVs')

        % ===============================
        % Constructing Tables for Figures of Merit and Confusion table        
%         GUIData.ConfTable = ConfTable_CV_2(cvv.y_LV_calibration,cvv.LV_calibration,cvv.ts);   
%         C = [];
%         for i = 1:size(ChemoData.ycalM,2)
%             C(i,:) = [GUIData.ConfTable.class_param_cal(1).accuracy(1) GUIData.ConfTable.class_param_cal(1).sensitivity(:,i) GUIData.ConfTable.class_param_cal(1).specificity(:,i)];
%         end
%            
%         figmerit={'Accuracy','Sensitivity','Specificity'};
%         set(hFigureMeritTable,'Data',C,'rowname',GUIData.ConfTable.columns(:,1:end-1),'columnname',figmerit);

        set(hConfusionTable,'Data',model.CrossVal.ConfusionMatrix{1});
        set(hConfusion_PLS,'Enable','on');
        set(hConfusion_PLS,'string',1:GUIData.CV.LV);
        
        GUIData.modelPLSDA_cv = model;
        guidata(hPLOTfigure,GUIData);  

        % ===============================
%         set(AxesOutlierPLSDA,'Visible','on');     
%         axes(AxesOutlierPLSDA); 
%         % Ploting results:
%         for n=1:GUIData.CV.LV
%             mi=doPLSDA(GNATData.xcal, GNATData.ycalM, n, opt);
%             outlier(n).tsq=mi.tsq;
%             outlier(n).qres=mi.qres;
%             outlier(n).tsqlim=mi.tsqlim;
%             outlier(n).qlim=mi.qlim;
%         end
%         
%         scatter(AxesOutlierPLSDA,outlier(1).tsq,outlier(1).qres)
%         hold on
%         
%         set(AxesOutlierPLSDA,'xtick',[],'FontSize',18,'FontName','Times New Roman');...
%         set(AxesOutlierPLSDA,'xtickMode', 'auto');hold on;
%         xlabel(AxesOutlierPLSDA,'Hotelling T^2','FontSize',14,'FontName','Times New Roman');
%         ylabel(AxesOutlierPLSDA,'Residuos em Q','FontSize',14,'FontName','Times New Roman');    
% 
%         if max(outlier(1).qres) > outlier(1).qlim
%             line(AxesOutlierPLSDA,[outlier(1).tsqlim outlier(1).tsqlim],[0 max(ylim).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                                      
%         else
%             line(AxesOutlierPLSDA,[outlier(1).tsqlim outlier(1).tsqlim],[0 (outlier(1).qlim).*1.25],'color',[1 0 0],'linestyle','--'); % T2 Limit                                                      
%         end
% 
%         if max(outlier(1).tsq) > outlier(1).tsqlim
%             line(AxesOutlierPLSDA,[0 (max(outlier(1).tsq)).*1.25],[outlier(1).qlim outlier(1).qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                                                       
%         else
%             line(AxesOutlierPLSDA,[0 (outlier(1).tsqlim).*1.25],[outlier(1).qlim outlier(1).qlim],'color',[1 0 0],'linestyle','--'); % Q limit                                                   
%         end     
%         axis('tight');
        guidata(hPLOTfigure,GUIData);  
    end

%% ----------------- biPLS
    function ChangeTab_biPLS_Callback(source,eventdata)
        Tab = get(hTabGroupbiPLS_PLSDA,'SelectedTab');
        % Turn on and off Visualization Panel for each Tab
        switch Tab
            case hTabResiduals_Intervals_biPLS
                set(hSpecDiv_biPLS_Panel,'Visible','on')
                set(hSpecDiv_biPLS_Predic,'Visible','off')
            case hTabPredMeasure_biPLS
                set(hSpecDiv_biPLS_Panel,'Visible','off')
                set(hSpecDiv_biPLS_Predic,'Visible','on')                      
        end
    end
    function EnableVariables_biPLS_Callback(source,eventdata)
        if get(hCheckUseVariables_biPLS,'value')
            set(hEditVariables_biPLS,'enable','on')
            set(h_biPLS_Run,'Enable','off'); 
        else
            set(hEditVariables_biPLS,'enable','off')
        end
    end
    function MethodCheck_biPLS_Callback(source,eventdata)
        GUIData.iPLS.method_cv = get(hMethodiPLS,'value');
        set(h_iPLS_Run,'Enable','off');

        switch GUIData.CV.method_cv
            case 1 %'K-fold'
                set(hEditFold,'Enable','on')
                set(hEditFold,'String',num2str(10))
                set(hSliderFold,'Enable','on')
                set(hFoldCV,'ForegroundColor',[0 0 0])
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])
                
                set(hEditDiv,'Enable','off')
                set(hSliderDiv,'Enable','off')
                set(hDivisiton,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                           
            case 2 %'Leane-One-Out'
                set(hEditFold,'Enable','off')
                set(hEditFold,'String',num2str(size(GNATData.xcal',2)))
                set(hSliderFold,'Enable','off')
                set(hFoldCV,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftFold,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightFold,'ForegroundColor',[0.5 0.5 0.5])

                set(hEditDiv,'Enable','off')
                set(hSliderDiv,'Enable','off')
                set(hDivisiton,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                
            case 3 %'Contiguous Block'
                set(hEditFold,'Enable','on')
                set(hSliderFold,'Enable','on')
                set(hFoldCV,'ForegroundColor',[0 0 0])
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])

                set(hEditDiv,'Enable','off')
                set(hSliderDiv,'Enable','off')
                set(hDivisiton,'ForegroundColor',[0.5 0.5 0.5])
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                
            case 4 %'Monte Carlo'
                set(hEditFold,'Enable','on')
                set(hSliderFold,'Enable','on')
                set(hFoldCV,'ForegroundColor',[0 0 0])
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])

                set(hEditDiv,'Enable','on')
                set(hSliderDiv,'Enable','on')
                set(hDivisiton,'ForegroundColor',[0 0 0])
                set(hLeftDivision,'ForegroundColor',[0 0 0])
                set(hRightDivision,'ForegroundColor',[0 0 0])                 
            otherwise
                %Do nothing
        end

    end
    function biPLS_Apply_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  
        
        % Get user input: Cross-validation
        GUIData.biPLS.Fold = str2double(get(hEditFoldbiPLS,'String'));
        GUIData.biPLS.LV = str2double(get(hEditCVGroupbiPLS,'String'));
        GUIData.biPLS.Division = str2double(get(hEditDivbiPLS,'String')); 
        GUIData.biPLS.shuffle = get(hCheckshufflebiPLS,'Value');
        GUIData.biPLS.method_cv = get(hMethodbiPLS,'value');
        % Get user input
        GUIData.biPLS.Process = get(hbiPLSprocess,'String');
        GUIData.biPLS.Intervals = str2double(get(hEditIntervals_biPLS,'String'));
        GUIData.biPLS.Variables = str2num(get(hEditVariables_biPLS,'String')); %#ok<ST2NM>
        GUIData.biPLS.Segments = str2double(get(hEditSegments_biPLS,'String'));
        GUIData.biPLS.Plottype = 'Cum';
        GUIData.biPLS.Labeltype = 'wavlabel'; %'wavlabel' 'intlabel' 'varlabel'
        set(h_biPLS_Run,'Enable','on');        
        
        % Perform the division in Cal and Val
        [index,test_X,train_X,test_y,train_y] = CrossValidation_splits(GNATData.xcal,...
            GNATData.ycalM,GUIData.biPLS.method_cv,GUIData.biPLS.shuffle,GUIData.biPLS.Fold,GUIData.biPLS.Division);   

        % Save the split
        GUIData.biPLS.index = index;
        GUIData.biPLS.test_X = test_X;
        GUIData.biPLS.train_X = train_X;
        GUIData.biPLS.test_y = test_y;
        GUIData.biPLS.train_y = train_y;

        guidata(hPLOTfigure,GUIData); 
    end
    function biPLS_Run_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 

        % Checking if the binning limits was calculated
        hBinFigure = findobj('Type','figure','Tag','Bin');
        if ~isempty(hBinFigure)
            BinPCA = guidata(hBinFigure);
            NmrData.pca.BinPCA=BinPCA;
            if isempty(BinPCA.non_normalized_buckets)
                NmrData.pca = rmfield(NmrData.pca, 'BinPCA');
            end 
        end
        
        % Separation of datasets according to the user's input
        NClass = size(GNATData.ycalM,2); 
        Division = (GUIData.biPLS.Division)./100; 
        
        % Matrix divided in calibration and validation at GNAT
        X = GNATData.xcal;
        Y = GNATData.ycalM;

        [~,ycl]=max(Y,[],2);
        Y=ycl; 
        ns=size(X,1);

        Ypredcv=zeros(ns,GUIData.biPLS.LV);
        rmsecv=zeros(GUIData.biPLS.LV,1);
        YResiduals=zeros(ns,NClass,GUIData.biPLS.LV);
            
        if get(hCheckUseVariables_biPLS,'value')
            FinalModel=plsmodel(GUIData.biPLS.biModel,GUIData.biPLS.Variables,GUIData.biPLS.LV,GUIData.biPLS.Process,'syst123',GUIData.biPLS.Segments);
            plotarea = findobj(AxesbiPLS_RMSE, 'type', 'axes');           
            plsrmse(FinalModel,[],plotarea);
            
            Tab = get(hTabGroupbiPLS_PLSDA,'SelectedTab');
            if Tab == hTabPredMeasure_biPLS
                plotarea_pred = findobj(AxesbiPLS_Predic, 'type', 'axes'); 
                plotarea_int = findobj(AxesbiPLS_Interval, 'type', 'axes');
                GUIData.biPLS.pred.LV = str2double(get(hEditLV_biPLS,'String'));
                plspvsm(FinalModel,GUIData.biPLS.pred.LV,[],1,plotarea_pred,plotarea_int,hPLOTfigure);
                set(plotarea_int,'xdir','reverse');
            end            
        else
            biModel=bipls(X,Y,GUIData.biPLS.LV,GUIData.biPLS.Process,GUIData.biPLS.Intervals,Export_Inf.Specscale,'syst123',GUIData.biPLS.Segments); 
%             biModel=bipls(X,Y,GUIData.biPLS.LV,GUIData.biPLS.Process,GUIData.biPLS.Intervals,GNATData.BinPCA.intervals,'syst123',GUIData.biPLS.Segments);  
            
            GUIData.biPLS.biModel = biModel;
        end
        
        if size(GUIData.biPLS.biModel.RevIntInfo,1)~=size(GUIData.biPLS.biModel.RevRMSE,1)
            start_interval_to_remove=size(GUIData.biPLS.biModel.RevRMSE,1);
            GUIData.biPLS.biModel.RevIntInfo(start_interval_to_remove:end,:)=[];
            GUIData.biPLS.biModel.RevRMSE(start_interval_to_remove:end,:)=[];    
            GUIData.biPLS.biModel.RevVars(start_interval_to_remove:end,:)=[];
        end
         
         % RMSE associated with each Variable 
        TableData(:,1)=(1:size(GUIData.biPLS.biModel.RevIntInfo,1))';
        TableData(:,2)=GUIData.biPLS.biModel.RevIntInfo;
        TableData(:,3)=GUIData.biPLS.biModel.RevRMSE;
        TableData(:,4)=GUIData.biPLS.biModel.RevVars;
        set(hinfoInterval_biPLS,'Data',TableData); 
        
        guidata(hPLOTfigure,GUIData); 
    end

%% ----------------- PLSDA
% ------------------------- Parameters CV------------------%
    function MethodCheck_CV_Callback(source,eventdata)
        GUIData.CV.method_cv = get(hMethodCV,'value');
        set(hCVRun,'Enable','off');
        switch GUIData.CV.method_cv
            case 1 %'K-fold'
                set(hEditCVFoldPLS,'Enable','on')
                set(hEditCVFoldPLS,'String',num2str(10))
                set(hSliderFoldCVPLS,'Enable','on')
                set(hSliderFoldCVPLS,'Value',10)
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])                
                set(hEditDivPLS,'Enable','off')
                set(hSliderDivCVPLS,'Enable','off')
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                           
            case 2 %'Leane-One-Out'
                set(hEditCVFoldPLS,'Enable','off')
                set(hEditCVFoldPLS,'String',num2str(size(GNATData.xcal',2)))
                set(hSliderFoldCVPLS,'Enable','off')
                set(hSliderFoldCVPLS,'Value',size(GNATData.xcal',2));
                set(hLeftFold,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightFold,'ForegroundColor',[0.5 0.5 0.5])
                set(hEditDivPLS,'Enable','off')
                set(hSliderDivCVPLS,'Enable','off')
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                
            case 3 %'Contiguous Block'
                set(hEditCVFoldPLS,'Enable','on')
                set(hSliderFoldCVPLS,'Enable','on')
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])
                set(hEditDivPLS,'Enable','off')
                set(hSliderDivCVPLS,'Enable','off')
                set(hLeftDivision,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivision,'ForegroundColor',[0.5 0.5 0.5])                
            case 4 %'Monte Carlo'
                set(hEditCVFoldPLS,'Enable','on')
                set(hSliderFoldCVPLS,'Enable','on')
                set(hLeftFold,'ForegroundColor',[0 0 0])
                set(hRightFold,'ForegroundColor',[0 0 0])
                set(hEditDivPLS,'Enable','on')
                set(hSliderDivCVPLS,'Enable','on')
                set(hLeftDivision,'ForegroundColor',[0 0 0])
                set(hRightDivision,'ForegroundColor',[0 0 0])                 
            otherwise
                %Do nothing
        end
        guidata(hPLOTfigure,GUIData); 
    end    
    function EditFold_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 

        % Turn off the Run button untill the apply button is pressed
        set(hCVRun,'Enable','off');  

        % Take and check the user input
        Fold=round(str2num(get(hEditCVFoldPLS,'String'))); %#ok<ST2NM>
        set(hSliderFoldCVPLS,'Value',Fold);
        if isempty(Fold)
            warndlg('Fold must be numeric')
            uiwait(gcf)
            set(hEditCVFoldPLS,'String',num2str(1));
            set(hSliderFoldCVPLS,'Value',1);
        elseif ~isnumeric(Fold)
            warndlg('Fold must be numeric')
            uiwait(gcf)
            set(hEditCVFoldPLS,'String',num2str(1));
            set(hSliderFoldCVPLS,'Value',1); 
        elseif Fold < 1   
            warndlg('Fold must be equal or gratter than 1')
            uiwait(gcf)
            set(hEditCVFoldPLS,'String',num2str(1));
            set(hSliderFoldCVPLS,'Value',1); 
        elseif Fold > size(GNATData.ycalV,1)
            a = size(GNATData.ycalV,1);
            warndlg(sprintf('Fold must be less than %g', a));
            uiwait(gcf)
            set(hEditCVFoldPLS,'String',num2str(10));
            set(hSliderFoldCVPLS,'Value',10); 
        else
            set(hSliderFoldCVPLS,'Value',Fold);
        end 

        guidata(hPLOTfigure,GUIData);        
    end
    function SliderFold_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);

        % Turn off the Run button untill the apply button is pressed
        set(hCVRun,'Enable','off');  

        % Take and set the user input
        Fold=round(get(hSliderFoldCVPLS,'Value'));
        set(hEditCVFoldPLS,'String',num2str(Fold)); 
        set(hCVRun,'Enable','off');

        guidata(hPLOTfigure,GUIData);        
    end
    function EditMaxLV_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 

        % Turn off the Run button untill the apply button is pressed
        set(hCVRun,'Enable','off');  

        % Take and check the user input        
        MaxLV=round(str2num(get(hEditCVS,'String'))); %#ok<ST2NM>
        set(hSliderCVPLS,'Value',MaxLV);
        if isempty(MaxLV)
            warndlg('Number of Latent Variables  must be numeric')
            uiwait(gcf)
            set(hEditCVLVPLS,'String',num2str(1));
            set(hSliderCVPLS,'Value',1);
        elseif ~isnumeric(MaxLV)
            warndlg('Number of Latent Variables  must be numeric')
            uiwait(gcf)
            set(hEditCVLVPLS,'String',num2str(10));
            set(hSliderCVPLS,'Value',10);
        elseif MaxLV > 20
            warndlg('Number of Latent Variables must be less than 20')
            uiwait(gcf)
            set(hEditCVLVPLS,'String',num2str(10));
            set(hSliderCVPLS,'Value',10);                        
        else
            set(hSliderCVPLS,'Value',MaxLV);
        end    
        
        guidata(hPLOTfigure,GUIData);        
    end
    function SliderCVGroup_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);

        % Turn off the Run button untill the apply button is pressed
        set(hCVRun,'Enable','off');  

        % Take and set the user input 
        CVGroup=round(get(hSliderCVPLS,'Value'));
        set(hEditCVLVPLS,'String',num2str(CVGroup));
        set(hCVRun,'Enable','off');

        guidata(hPLOTfigure,GUIData); 
    end
    function EditPercIn_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);

        % Turn off the Run button untill the apply button is pressed
        set(hCVRun,'Enable','off');  

        % Take and check the user input 
        Div=round(str2num(get(hEditDivPLS,'String'))); %#ok<ST2NM>
        set(hSliderDivCVPLS,'Value',Div);        
        if isempty(Div)
            warndlg('Percentage must be numeric')
            uiwait(gcf)
            set(hEditDivPLS,'String',num2str(70));
            set(hSliderDivCVPLS,'Value',70);
        elseif ~isnumeric(Div)
            warndlg('Percentage must be numeric')
            uiwait(gcf)
            set(hEditDivPLS,'String',num2str(70));
            set(hSliderDivCVPLS,'Value',70);
        elseif Div > 100
            warndlg('Percentage must be beteewn 1 and 100')
            uiwait(gcf)
            set(hEditDivPLS,'String',num2str(70));
            set(hSliderDivCVPLS,'Value',70);   
        elseif Div < 0
            warndlg('Percentage must be beteewn 1 and 100')
            uiwait(gcf)
            set(hEditDivPLS,'String',num2str(70));
            set(hSliderDivCVPLS,'Value',70);              
        else
            set(hSliderDivCVPLS,'Value',Div);
        end         

        guidata(hPLOTfigure,GUIData);        
    end
    function SliderSliderDiv_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 

        % Turn off the Run button untill the apply button is pressed
        set(hCVRun,'Enable','off');  

        % Take and check the user input 
        Div=round(get(hSliderDivCVPLS,'Value'));
        set(hEditDivPLS,'String',num2str(Div)); 
        set(hCVRun,'Enable','off');

        guidata(hPLOTfigure,GUIData);        
    end
% ------------------------- Cross-Validation --------------%
    function CVApply_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  
        
        % Get user input
        GUIData.CV.Fold = str2double(get(hEditCVFoldPLS,'String'));
        GUIData.CV.LV = str2double(get(hEditCVLVPLS,'String'));
        GUIData.CV.Division = str2double(get(hEditDivPLS,'String')); 
        GUIData.CV.shuffle = get(hCheckshuffle,'Value');     
        
        % Perform the division in Cal and Val
        [index,test_X,train_X,test_y,train_y] = CrossValidation_splits(GNATData.xcal,...
            GNATData.ycalM,GUIData.CV.method_cv,GUIData.CV.shuffle,GUIData.CV.Fold,GUIData.CV.Division);           

        % Construct the color table for calibration and validation for each fold
        Samples = "Sample_" + string(1:size(GNATData.xcal',2));
        ycalV = string(GNATData.ycalV);       
        colergen = @(cor,text) ['<html><table border=0 width=20 bgcolor=',cor,'><TR><TD>',text,'</TD></TR> </table><html>'];
        index.fold = ycalV;
        columns = zeros(1,GUIData.CV.Fold);
        for i = 1:GUIData.CV.Fold
            index.fold(index.test{i},i) = colergen('#D95319','V');
            index.fold(index.train{i},i) = colergen('#4DBEEE','C');
            columns(1,i) = sprintf("Fold %02d",i);   
        end    
        folds = string(index.fold);
        set(hClassInfoTable,'Data',[cellstr(Samples'),cellstr(ycalV),cellstr(folds)]);
        set(hClassInfoTable,'Visible','on')        
        set(hClassInfoTable,'columnname',['Sample','Class',columns]);

        % Save the split
        GUIData.CV.index = index;
        GUIData.CV.test_X = test_X;
        GUIData.CV.train_X = train_X;
        GUIData.CV.test_y = test_y;
        GUIData.CV.train_y = train_y;

        % Enable the run button
        set(hCVRun,'Enable','on');  

        guidata(hPLOTfigure,GUIData); 
    end
    function CVRun_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 
        
        % Separation of datasets according to the user's input
        NClass = size(GNATData.ycalM,2); 
        Division = (GUIData.CV.Division)./100; 
        
        % Matrix divided in calibration and validation at GNAT
        X = GNATData.xcal;
        Y = GNATData.ycalM;

        [~,ycl]=max(Y,[],2);
        Y=ycl; 
        ns=size(X,1);

        Ypredcv=zeros(ns,GUIData.CV.LV);
        YResiduals=zeros(ns,NClass,GUIData.CV.LV); 

        % Parameters defined by me to PLS calculation - Create objects in the future for the user control this one
        opt.prepr={'mean' 'mean'};
        opt.algorithm='simpls';
        opt.detailedoutput='on';
        opt.classcriterion='maxY';        
       
        % Contruction of the Cross Validation model
        h=waitbar(0,'Building the PLS-DA cross validation model');
        for k = 1:GUIData.CV.Fold
            h=waitbar(k/GUIData.CV.Fold);
            for i=1:GUIData.CV.LV
                indextest=GUIData.CV.index.test{k};
                % Creating the model
                mi=doPLSDA(GUIData.CV.train_X{k}, GUIData.CV.train_y{k}, i, opt,GNATData.ycalV);
                % Testing the model
                pi=doPLSDApred(GUIData.CV.test_X{k}, GUIData.CV.test_y{k}, mi);
                % Predicted classes
                Ypredcv(indextest,i)=pi.classification.PredClass;
                % Calculate the residual for each class and n of LV
                YResiduals(indextest,:,i) = pi.YResiduals;
                YpredQ2(k,:)=pi.Q2;
            end   
        end
        close(h)
        
        rmsecv=(YResiduals).^2;
        GUIData.CV.model.rmsecv=reshape(sqrt(rmsecv./ns),[],GUIData.CV.LV)';
        GUIData.CV.model.CrossVal.PredClassCV=Ypredcv; 
        GUIData.CV.model.CrossVal.TrueClass=Y;
        GUIData.CV.model.YResiduals=YResiduals;       
        GUIData.CV.model.YpredQ2=YpredQ2;  

        % Error calculatio (RMSECV) as a average for all classes.
        plot(AxesRMSECV,1:GUIData.CV.LV, sum(GUIData.CV.model.rmsecv,2), 'o-r')
        xlabel(AxesRMSECV,'Number of Latent Variables','FontSize',14);
        ylabel(AxesRMSECV,'Root Mean Squared Error of Cross-Validation (%)','FontSize',14);
        axis tight
        title(AxesRMSECV,'Selection of the optimal number of LVs')

        % Constructing Tables for Figures of Merit and Confusion table        
        cmatrix=cell(1,GUIData.CV.LV); 
        ccrate=cell(1,GUIData.CV.LV);
        cct=zeros(1,GUIData.CV.LV);
        
        for i=1:GUIData.CV.LV
            cmatrix{i}=cmatrixcalc(Ypredcv(:,i), Y, max(Y));
            ccrate{i}=100*diag(cmatrix{i})./sum(cmatrix{i},2); 
            cct(i)=100*sum(diag(cmatrix{i}))/length(Y);            
        end
        GUIData.CV.model.CrossVal.ConfusionMatrix=cmatrix; 
        GUIData.CV.model.CrossVal.CorrClassRate=ccrate; 
        GUIData.CV.model.CrossVal.TotalClassErr=cct; 

        set(hConfusionTable,'Data',GUIData.CV.model.CrossVal.ConfusionMatrix{1});
        set(hConfusion_PLS,'Enable','on');
        set(hConfusion_PLS,'string',1:GUIData.CV.LV);
        
        guidata(hPLOTfigure,GUIData);  

    end
    function ChangeTabCallback(source,eventdata)
        Tab = get(hTabGroupPLSDA_CV,'SelectedTab');
        % Turn on and off Visualization Panel for each Tab
        switch Tab
            case hTabSplitCV 
                set(hVisualPanelResults,'Visible','on')
                set(hVisualPanelOutlier,'Visible','off')
                set(hVisualPanelConfusion,'Visible','off')   
            case hConfusionMatrix
                set(hVisualPanelResults,'Visible','off')
                set(hVisualPanelOutlier,'Visible','off')
                set(hVisualPanelConfusion,'Visible','on')              
            case hResiduals
                set(hVisualPanelResults,'Visible','on')
                set(hVisualPanelOutlier,'Visible','off')
                set(hVisualPanelConfusion,'Visible','off')                     
        end

        Tab = get(hTabGroupCVOPLSDA,'SelectedTab');
        % Turn on and off Visualization Panel for each Tab
        switch Tab
            case hTabSplitCV_oplsda
                set(hVisualPanelResults_oplsda,'Visible','on')
                set(hVisualPanelOutlier_oplsda,'Visible','off')
                set(hVisualPanelConfusion_oplsda,'Visible','off')   
            case hConfusionMatrix_oplsda
                set(hVisualPanelResults_oplsda,'Visible','off')
                set(hVisualPanelOutlier_oplsda,'Visible','off')
                set(hVisualPanelConfusion_oplsda,'Visible','on')              
            case hResiduals_oplsda
                set(hVisualPanelResults_oplsda,'Visible','on')
                set(hVisualPanelOutlier_oplsda,'Visible','off')
                set(hVisualPanelConfusion_oplsda,'Visible','off')                     
        end
     end
% ------------------------- Model -------------------------%
    function Classes_RMSECV_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  

        if get(hCheckLabelsAllClasses,'Value') == 0
            set(hMethodCV_Class,'Enable','on') 
            set(hMethodCV_Class,'string',"Class 1|Class 2|Class 3");  

            ns=size(GNATData.xcal,1);
            RMSE = sqrt(sum((GUIData.CV.model.YResiduals).^2,1)/(ns));
            GUIData.CV.model.rmsecv=reshape(RMSE,[],GUIData.CV.LV)';

            clss = get(hMethodCV_Class,'Value');
            plot(AxesRMSECV,1:GUIData.CV.LV, GUIData.CV.model.rmsecv(:,clss), 'o-r')
            xlabel(AxesRMSECV,'Number of Latent Variables','FontSize',14);
            ylabel(AxesRMSECV,'Root Mean Squared Error of Cross-Validation (%)','FontSize',14);
            axis tight
            title(AxesRMSECV,'Selection of the optimal number of LVs')
        else
            ns=size(GNATData.xcal,1);
            rmsecv=(GUIData.CV.model.YResiduals).^2;
            GUIData.CV.model.rmsecv=reshape(sqrt(rmsecv./ns),[],GUIData.CV.LV)';

            plot(AxesRMSECV,1:GUIData.CV.LV, sum(GUIData.CV.model.rmsecv,2), 'o-r')
            xlabel(AxesRMSECV,'Number of Latent Variables','FontSize',14);
            ylabel(AxesRMSECV,'Root Mean Squared Error of Cross-Validation (%)','FontSize',14);
            axis tight
            title(AxesRMSECV,'Selection of the optimal number of LVs')  
        end
 

        guidata(hPLOTfigure,GUIData);        
    end  
    function PLS_Tables_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  

        GUIData.PLS_N=get(hConfusion_PLS,'value');
        set(hConfusionTable,'Data',GUIData.modelPLSDA_cv.CrossVal.ConfusionMatrix{GUIData.PLS_N});
        
        guidata(hPLOTfigure,GUIData);
    end
    function ModelPLSDA(source,eventdata)            
        %% Taking user input
        GUIData = guidata(hPLOTfigure);  
        Factor = str2double(get(hEditFactorsModelPLSDA,'String'));        
        if ~isfield(GNATData,'modelPLSDA')        
            % Processing parameters
            opt.prepr{1} = get(hProcessing_PLSDA_Model_s,'Value');            
            switch  opt.prepr{1}
                case 1
                    opt.prepr{1} = 'mean';
                case 2 
                    opt.prepr{1} = 'auto';
                case 3
                    opt.prepr{1} = 'pareto';
            end
            
            opt.algorithm='simpls';
            opt.detailedoutput='on';
            opt.classcriterion='maxY';
            
            opt.ldax='predy';
            opt.prior='uniform';
            opt.cv.cvtype='syst123'; 
            opt.cv.cvsegments=5;          

            % Removing the outliers determined by the user
            remove = ismember(GNATData.objetos.treinamento,GNATData.outlier);     
            outlier = GNATData.Classes;
            Clss = outlier(GNATData.objetos.treinamento);
            labels_s = num2cell(GNATData.objetos.treinamento);
            Clss(remove,:) = [];
            labels_s(remove,:) = [];
           
            if get(hVariables_PLSDA_Model_s,'Value') == 3 
                if isfield(GUIData,'biPLS')
                    selected_intervals = GUIData.biPLS.Variables;
                    Model.allint = GUIData.biPLS.biModel.allint;
                    if selected_intervals == 0 
                        modelPLSDA=doPLSDA(GNATData.xcal, GNATData.ycalM, Factor, opt,GNATData.ycalV);
                        modelpred=doPLSDApred(GNATData.xval, GNATData.yvalM, modelPLSDA);
                    else  
                        selected_vars=[];
                        for i=1:max(size(selected_intervals))
                           temp=Model.allint(selected_intervals(i),2):Model.allint(selected_intervals(i),3);
                           selected_vars=[selected_vars temp]; %#ok<*AGROW> 
                        end
                        modelPLSDA=doPLSDA(GNATData.xcal(:,selected_vars), GNATData.ycalM, Factor, opt,GNATData.ycalV);
                        modelpred=doPLSDApred(GNATData.xval(:,selected_vars), GNATData.yvalM, modelPLSDA);
                    end
                else
                    warndlg('It is necessary to first calculate the limits for the biPLS model')
                    uiwait(gcf)
                    return
                end
            else
                modelPLSDA = doPLSDA(GNATData.xcal, GNATData.ycalM, Factor, opt,GNATData.ycalV);
                modelpred  = doPLSDApred(GNATData.xval, GNATData.yvalM, modelPLSDA);
            end
                
            % Updating popup menu for the score plot 
            Xs = get(hScore_PLSDA_Model_X,'value');
            Ys = get(hScore_PLSDA_Model_Y,'value');
            Zs = get(hScore_PLSDA_Model_Z,'value');
            set(hScore_PLSDA_Model_X,'string',modelPLSDA.AxesXPlot(:,1));  
            set(hScore_PLSDA_Model_Y,'string',modelPLSDA.AxesXPlot(:,1));
            set(hScore_PLSDA_Model_Z,'string',modelPLSDA.AxesXPlot(:,1));

            % Table Variance Captured by PLS-DA
            TableData(:,1)=modelPLSDA.eigvalue;
            TableData(:,2)=modelPLSDA.explvar{1,1};
            TableData(:,3)=cumsum(modelPLSDA.explvar{1,1});
            set(hTableEigenvalues,'Data',TableData);

            % Making a numerical label for each sample   
            symbols = {'o','s','^','d','h','v','*','x','<','>','p'};  
            colors = ['g','b','m','c','y','b'];
            
            % Saving the class sequence
            [cc,ia]=unique(GNATData.Classes);
            ClassesValue = num2str(cc);                
            GNATData.ClassesValue = ClassesValue;
            
            % Create legend for classe define by the user
            if ~isempty(Labels) 
                UserLegend = Labels(ia); 
                a = cellfun(@isempty,UserLegend);
                str = string(cc);
                aa = cellstr(str);
                aa(~a) = {''};
                UserLegend(a) = {''};
                ab = append(aa,UserLegend);                     
                if isempty(UserLegend{1})
                    UserLegend{1} = '0';                
                end
            end    
            if sum(GNATData.ClassesValue == '0') == 1
                UserLegend{1} = '0';
                colors = ['r', colors];
            else
                % do nothing
            end
            
            % Permutating the number of symbols and colors for class > 7
            if size(ClassesValue,1) > size(colors,2)
                k = ceil(size(ClassesValue,1)./size(colors,2));
                c = repmat(colors,1,k);
                Clr = c(1:size(ClassesValue,1)); 
            else
                c = repmat(colors,1,2);
                Clr = c(1:size(ClassesValue,1));
            end                     
            if size(ClassesValue,1) > size(symbols,2)
                k = ceil(size(ClassesValue,1)./size(symbols,2));
                s = repmat(symbols,1,k);  
                Sym = s(1:size(ClassesValue,1));            
            else
                s = repmat(symbols,1,2);
                Sym = s(1:size(ClassesValue,1));
            end     
            
            % Parameters to constrct plots
            S = char(Sym);     
            if get(hRadioCalPLSDA,'Value')
                Opt = [1 0 0];
            elseif get(hRadioValPLSDA,'Value')
                Opt = [0 1 0];
            elseif get(hRadioCalValPLSDA,'Value')
                Opt = [0 0 1];
            end

            % Taking the predictive power into the Legend values
%             ClassesValue=[];
%             ClassesValue=num2str(cc);
%             ClassesValue = cellstr(ClassesValue);
%             ClassesValue(end+1)=cellstr(['R2: ' num2str(modelPLSDA.R2)]);
%             ClassesValue(end+1)=cellstr(['Q2: ' num2str(modelpred.Q2)]);
%             ClassesValue = cellstr(ClassesValue);
        else
            modelPLSDA = GNATData.modelPLSDA;
            modelpred=doPLSDApred(GUIData.CV.test_X{k}, GUIData.CV.test_y{k}, modelPLSDA);
        end
         
        %% Score plots
        axes(hAxesScorePLSDA);
        % 3D SCORE
        % Defining the current axis
        if get(hCheckUse3D_PLSDA,'value')
             % Plotting 3D data with classes
             GUIData.AxesScorePLS.h3 = gscatter3(...
                modelPLSDA.scores{1,1}(:,(get(hScore_PLSDA_Model_X,'value'))),...
                modelPLSDA.scores{1,1}(:,(get(hScore_PLSDA_Model_Y,'value'))),...
                modelPLSDA.scores{1,1}(:,(get(hScore_PLSDA_Model_Z,'value'))),...
                Clss,Clr,S,6,'auto');   
             axis('tight');

             % Defing the apperance 
             set(GUIData.AxesScorePLS.h3,'LineWidth',1);
             set(hAxesScorePLSDA,'LineWidth',1); 
             set(hAxesScorePLSDA,'Box','on');

             % Determining the ellipses for every class
             hold on;
             Error_elipse3D(modelPLSDA.scores{1, 1}(:,[(get(hScore_PLSDA_Model_X,'value')),(get(hScore_PLSDA_Model_Y,'value')),(get(hScore_PLSDA_Model_Z,'value'))]),Clss,Clr) 
             hold off;             
                
             % Determining the limits for X, Y and Z axis
             set(hAxesScorePLSDA,'XLim',[-max(abs(get(hAxesScorePLSDA,'XLim'))).*1.5 max(abs(get(hAxesScorePLSDA,'XLim'))).*1.5]);
             set(hAxesScorePLSDA,'YLim',[-max(abs(get(hAxesScorePLSDA,'YLim'))).*1.5 max(abs(get(hAxesScorePLSDA,'YLim'))).*1.5]);
             set(hAxesScorePLSDA,'ZLim',[-max(abs(get(hAxesScorePLSDA,'ZLim'))).*1.5 max(abs(get(hAxesScorePLSDA,'ZLim'))).*1.5]);

             % Determining the axis labels
             xlabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_X,'value')),1),'FontSize',10, 'FontWeight','bold');
             ylabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_Y,'value')),1),'FontSize',10, 'FontWeight','bold');
             zlabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_Z,'value')),1),'FontSize',10, 'FontWeight','bold');
             line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
             line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');
             line([0 0],[0 0],[min(zlim) max(zlim)],'color',[1 0 0],'linestyle','--');
                                                    
             % Displaying the labels and legend for points
             GNATData.labelScore = text(modelPLSDA.scores{1,1}(:,(get(hScore_PLSDA_Model_X,'value')))*1.1,modelPLSDA.scores{1, 1}(:,(get(hScore_PLSDA_Model_Y,'value')))*1.1,modelPLSDA.scores{1, 1}(:,(get(hScore_PLSDA_Model_Z,'value')))*1.1, labels_s); 
             if ~isempty(Labels)
                GNATData.legendScore = legend(hAxesScorePLSDA,ab,'Location','northwest');
             else
                GNATData.legendScore = legend(hAxesScorePLSDA,ClassesValue,'Location','northwest');
             end 

         % 2D SCORE
         else    
             GUIData.AxesScorePLS.h = gscatter(hAxesScorePLSDA,modelPLSDA.scores{1,1}(:,(get(hScore_PLSDA_Model_X,'value'))),modelPLSDA.scores{1, 1}(:,(get(hScore_PLSDA_Model_Y,'value'))),...
                Clss,Clr,S,6,'on');                  
             for n = 1:length(GUIData.AxesScorePLS.h)                             
                 set(GUIData.AxesScorePLS.h(n,1), 'MarkerFaceColor', Clr(n));
             end                   
             set(hAxesScorePLSDA, 'YLimMode', 'manual');
             set(hAxesScorePLSDA, 'YLimMode', 'manual');       

             % Defing the apperance   
             set(GUIData.AxesScorePLS.h,'LineWidth',1);
             set(gca,'LineWidth',1);
             set(gca,'Box','on');

             % Confidence limit based on Hotelling T2
             res_list = ellipseParam(modelPLSDA.scores{1, 1}, 2, (get(hScore_PLSDA_Model_X,'value')),(get(hScore_PLSDA_Model_Y,'value')),2);
             if res_list.exit == 1
                 return
             end         

             % Plot the first ellipse 95%
             [~,xax,yax]=ellipse_GNAT(res_list.Ellipse{1,2}, res_list.Ellipse{1,1}, 0, 0, 0, 'r','--');

             % Plot the second ellipse 99%
             ellipse_GNAT(res_list.Ellipse{1,4}, res_list.Ellipse{1,3}, 0, 0, 0, 'b','--');

             % Determining the ellipses for every class
             Error_elipse(modelPLSDA.scores{1, 1}(:,[(get(hScore_PLSDA_Model_X,'value')),(get(hScore_PLSDA_Model_Y,'value'))]),Clss,Clr) 
             
             % Painting black (Rolling stones) the area outside the elipse  
             axis(hAxesScorePLSDA,'tight')
             drawnow % for some reason, axis 'tight' doesn't work. That's why I'm pausing here to load all the figure elements before continue
             xl = xlim(gca); yl = ylim(gca);
             xlim([xl(1)*1.05 xl(2)*1.05])
             ylim([yl(1)*1.5 yl(2)*1.5])   
             xl = xlim(gca); yl = ylim(gca);    
             x_frame=[xl(1),xl(2),xl(2),xl(1),xl(1)];
             y_frame=[yl(1),yl(1),yl(2),yl(2),yl(1)];         
             x = [x_frame, xax]; 
             y = [y_frame, yax];
             fill = patch(x,y, [0 0 0.25], 'EdgeColor', 'none');
             alpha(fill,0.06)
             axis tight % optional

             % Determining the axis labels
             xlabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_X,'value')),1),'FontSize',10, 'FontWeight','bold');
             ylabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_Y,'value')),1),'FontSize',10, 'FontWeight','bold');
             line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
             line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');  
    
             % Displaying the labels and legend for points
             GNATData.labelScore = labelpoints(modelPLSDA.scores{1,1}(:,(get(hScore_PLSDA_Model_X,'value'))),modelPLSDA.scores{1, 1}(:,(get(hScore_PLSDA_Model_Y,'value'))), labels_s,'N',0.05,1, 'FontSize', 10); 
             if ~isempty(Labels)
                GNATData.legendScore = legend(hAxesScorePLSDA,ab,'Location','northwest');
             else
                GNATData.legendScore = legend(hAxesScorePLSDA,ClassesValue,'Location','northwest');
             end   


%              dim = [.2 .5 .3 .3];
%              str = 'Straight Line Plot from 1 to 10';
%              annotation(gcf,'textbox','String',str,'FitBoxToText','on');
             
%              dim = [.74 .56 .1 .1];
%              annotation(hAxesScorePLSDA,'textbox','String',str,'FitBoxToText','on');

             title('PLS-DA model', ['R2: ',num2str(modelPLSDA.R2,'%.4f'),', Q2: ',num2str(modelpred.Q2,'%.4f')]); %modelPLSDA
             
             grid on
         end

        %% Loading plots
        axes(hAxesLoadingPLSDA)
        if isfield(GNATData,'BinPCA')
            GUIData.Axes.h_loadind=plot(hAxesLoadingPLSDA,GNATData.BinPCA.number_of_variables,modelPLSDA.loadings{1,1}(:,(get(hScore_PLSDA_Model_X,'value'))));
        else
            GUIData.Axes.h_loadind=plot(hAxesLoadingPLSDA,GNATData.ppmscale(1,:),modelPLSDA.loadings{1,1}(:,(get(hScore_PLSDA_Model_X,'value'))));
        end
        axis('tight');
        set(GUIData.Axes.h_loadind,'LineWidth',1);
        set(gca,'LineWidth',1);
        set(gca,'xdir','reverse');
        set(hAxesLoadingPLSDA,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
        xlabel(hAxesLoadingPLSDA,'Chemical shift (ppm)','FontSize',10, 'FontWeight','bold');   
        row = dataTipTextRow("Variable",GNATData.ppmscale(1,:));
        GUIData.Axes.h_loadind.DataTipTemplate.DataTipRows(end+1) = row; 

        %% VIP Score Plots
        % `chemical_shifts` - Vector of chemical shifts (x-axis, ppm)
        % `spectrum` - Average NMR spectrum (row vector)
        % `vip_scores` - VIP scores for each variable (from previous calculation)
        % `loadings` (Q) - PLS-DA loadings for the first component (or any selected component)
        axes(hAxesVIPPLSDA);
        cla(hAxesVIPPLSDA)

        spectrum = mean(GNATData.xcal);
        if isfield(GNATData,'BinPCA')
            chemical_shifts = GNATData.BinPCA.number_of_variables;
        else
            chemical_shifts = GNATData.ppmscale(1,:);
        end

        % Normalize spectra and loadings for visualization
        TotVIP_normalised = modelPLSDA.TotVip' / max(modelPLSDA.TotVip) * max(spectrum'); % Scale VIP to match spectrum
        loadings_normalized = modelPLSDA.loadings{1,1}(:,(get(hScore_PLSDA_Model_X,'value')))/  max(abs(modelPLSDA.loadings{1,1}(:,(get(hScore_PLSDA_Model_X,'value'))))) * max(spectrum); % Scale loadings to match spectrum

        hold on
        set(gca,'Xdir','reverse');
        set(gca,'LineWidth',1);
        set(gca,'Box','on');

        % VIP scores
        hVIPPLSDA = bar(chemical_shifts, TotVIP_normalised, 'FaceAlpha', 0.9, 'FaceColor', 'b', 'DisplayName', 'VIP Scores');

        % Add threshold line for VIP scores (Corrected for the magnitude )
        yline(1*10^floor(log10(abs(max(TotVIP_normalised)))), 'b--', 'LineWidth', 1.5, 'DisplayName', 'VIP Threshold');

        % Overlay NMR spectrum
        if get(hCheckSpecVIP,'value') == 1
            plot(chemical_shifts, spectrum, 'k', 'LineWidth', 1.5, 'DisplayName', 'NMR Spectrum');
        end

        % Overlay loadings
        if get(hCheckLoadingVIP,'value') == 1
            plot(chemical_shifts, loadings_normalized, 'r', 'LineWidth', 1.5, 'DisplayName', 'PLS Loadings');
        end

        % Formatting Color
        % Set FaceColor to 'flat' for custom coloring
        hVIPPLSDA.FaceColor = 'flat';

        % Initialize color array
        colors = repmat([0.5 0.5 0.5], length(modelPLSDA.TotVip), 1); % Default to grey

        % Assign blue color to bars above the threshold
        colors(modelPLSDA.TotVip > 1*8^floor(log10(abs(max(modelPLSDA.TotVip)))), :) = repmat([0 0 1], sum(modelPLSDA.TotVip > 1*8^floor(log10(abs(max(modelPLSDA.TotVip))))), 1);

        % Apply the colors to the bars
        hVIPPLSDA.CData = colors;

        % Axis
        xlabel('Chemical Shift (ppm)');
        ylabel('Intensity (a.u.)');
        title('NMR Spectrum, VIP Scores, and PLS Loadings');
        GNATData.legendPLSVIP = legend();
        set(gca, 'XDir', 'reverse'); % Reverse x-axis for NMR convention
        hold off;

        %% VIP Table Plots

        % Find samples above threshold
        if unique(find(colors(:,3)==1)>0)==1 % If there are samples above the threshold
            idx = find(colors(:,3)==1);
            Number = 1:size(idx,1);
            ppm = chemical_shifts(idx);
            VIP_score = TotVIP_normalised(idx);
            [Sort_VIP,idx2] = sort(TotVIP_normalised(idx),'descend');
            ppm = ppm(idx2);

            Data = [Number',ppm',Sort_VIP'];
            set(nVIPTablePpm,'Data',Data); 
        end

        %% Discrimination Plot
        optclss = get(hRunClasses_PLSDA,'value');
        clss = size(unique(Classes),1);

        % Reorganizing samples
        % Training
        order = GNATData.ycalV;
        [Clss,idx] = sortrows(order);
        modelPLSDA.preds = modelPLSDA.preds(idx,:);
        modelPLSDA.classes = modelPLSDA.classes(idx,:);
        % Test
        order = GNATData.yvalV;
        [~,idx] = sortrows(order);
        modelpred.preds = modelpred.preds(idx,:);  

        % Calculate optimal grid dimensions for subplots
        SizeClass = size(modelpred.preds,2);
        nRows = ceil(sqrt(SizeClass));
        nCols = ceil(SizeClass / nRows);

        if Opt(1) == 1
            % Calibration plot
            if optclss > clss % 'all' option selected
                for ki=1:SizeClass

                    subplot(nRows, nCols,ki,'Parent', hDiscriminationPLSDA_Axes);
                    GUIData.AxesPLSDA_c.h = gscatter(1:length(modelPLSDA.preds),modelPLSDA.preds(:,ki),Clss,Clr,S,6,'off');
                    for n = 1:length(GUIData.AxesPLSDA_c.h)
                        set(GUIData.AxesPLSDA_c.h(n,1), 'MarkerFaceColor', Clr(n));
                    end

                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    grid on;hold on;

                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    hold on;

                    xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                    ylabel(sprintf('Class %g',ki),'FontSize',18,'FontName','Times New Woman')
                    
                    set(gca,'YLim',[-0.4 1.2])
                    line([0 (size(Clss,1))*1.02],[modelPLSDA.threshold.class_thr(ki)   modelPLSDA.threshold.class_thr(ki)],'color',[1 0 0],'linestyle','--');
                    xlim('tight');     
                    hold off
                    
                end
            else 
                % Recreating the main axis (hAxesDiscPLSDA) if it was deleted before by the subplot construction
                num_axis = get(hDiscriminationPLSDA_Axes,'Children');
                if size(num_axis,1) > 1
                    delete(num_axis);
                    hAxesDiscPLSDA = axes(...
                        'Parent',hDiscriminationPLSDA_Axes,...
                        'Units','normalized',...
                        'Visible','off',...
                        'Box','off',...
                        'tag','axDisc',...
                        'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65
                end

                axes(hAxesDiscPLSDA);       
                GUIData.AxesPLSDA_c.h = gscatter(1:length(modelPLSDA.preds),modelPLSDA.preds(:,optclss),Clss,Clr,S,6,'off'); 
                for n = 1:length(GUIData.AxesPLSDA_c.h)
                    set(GUIData.AxesPLSDA_c.h(n,1), 'MarkerFaceColor', Clr(n));
                end 

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                grid on;hold on;


                xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Class %g',optclss),'FontSize',18,'FontName','Times New Woman')
                
                set(gca,'YLim',[-0.4 1.2])
                line([0 (size(Clss,1))*1.05],[modelPLSDA.threshold.class_thr(optclss)   modelPLSDA.threshold.class_thr(optclss)],'color',[1 0 0],'linestyle','--');
                xlim('tight')

                hold off
            end
        elseif Opt(2) == 1
           % Validation plot
           if optclss > clss % 'all' option selected
                for ki=1:size(modelpred.preds,2)
                              
                    subplot(nRows, nCols,ki,'Parent', hDiscriminationPLSDA_Axes);
    
                    [Clss,~] = sortrows(GNATData.yvalV);
    
                    GUIData.AxesPLSDA_v.h = gscatter(1:length(modelpred.preds),modelpred.preds(:,ki),Clss,Clr,S,6,'off');                
                    for n = 1:length(GUIData.AxesPLSDA_v.h)
                      set(GUIData.AxesPLSDA_v.h(n,1), 'MarkerFaceColor', Clr(n));
                    end 
    
                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    grid on;hold on;

                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    hold on;

                    xlabel('Sample','FontSize',18,'FontName','Times New Woman')
                    ylabel(sprintf('Classe %g',ki),'FontSize',18,'FontName','Times New Woman')
                    set(gca,'YLim',[-0.4 1.2])
                    line([0 (size(Clss,1))*1.02],[modelPLSDA.threshold.class_thr(ki)   modelPLSDA.threshold.class_thr(ki)],'color',[1 0 0],'linestyle','--');
                    xlim('tight')
                    hold off
                end
           else
                % Recreating the main axis (hAxesDiscPLSDA) if it was deleted before by the subplot construction
                num_axis = get(hDiscriminationPLSDA_Axes,'Children');
                if size(num_axis,1) > 1
                    delete(num_axis);
                    hAxesDiscPLSDA = axes(...
                        'Parent',hDiscriminationPLSDA_Axes,...
                        'Units','normalized',...
                        'Visible','off',...
                        'Box','off',...
                        'tag','axDisc',...
                        'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65
                end

                axes(hAxesDiscPLSDA);
                [Clss,~] = sortrows(GNATData.yvalV);

                GUIData.AxesPLSDA_v.h = gscatter(1:length(modelpred.preds),modelpred.preds(:,optclss),Clss,Clr,S,6,'off');                
                for n = 1:length(GUIData.AxesPLSDA_v.h)
                  set(GUIData.AxesPLSDA_v.h(n,1), 'MarkerFaceColor', Clr(n));
                end 

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                grid on;hold on;


                xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Classe %g',optclss),'FontSize',18,'FontName','Times New Woman')
                set(gca,'YLim',[-0.4 1.2])
                line([0 (size(Clss,1))*1.02],[modelPLSDA.threshold.class_thr(optclss)   modelPLSDA.threshold.class_thr(optclss)],'color',[1 0 0],'linestyle','--');
                xlim('tight')
                hold off
            end
        elseif Opt(3) == 1
           % Calibration & Validation plot
           if optclss > clss % 'all' option selected
                for ki=1:size(modelpred.preds,2)
                         
                    subplot(nRows, nCols,ki,'Parent', hDiscriminationPLSDA_Axes);
                    lngt =  size(modelpred.preds)+size(modelPLSDA.preds);
    
                    [ClssC,~] = sortrows(GNATData.ycalV);
                    [ClssV,~] = sortrows(GNATData.yvalV);
                    Clss = [ClssC' ClssV'];
    
                    GUIData.AxesPLSDA_cv.h = gscatter(1:lngt(1),[modelPLSDA.preds(:,ki)' modelpred.preds(:,ki)'],Clss,Clr,S,6,'off');                 
                    for n = 1:length(GUIData.AxesPLSDA_cv.h)
                      set(GUIData.AxesPLSDA_cv.h(n,1), 'MarkerFaceColor', Clr(n));
                    end 
    
                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    grid on;hold on;

                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    hold on;

                    xlabel('Sample','FontSize',18,'FontName','Times New Woman')
                    ylabel(sprintf('Classe %g',ki),'FontSize',18,'FontName','Times New Woman')

%                 set(gca,'YLim',[-max(abs(get(gca,'YLim'))).*1.5 max(abs(get(gca,'YLim'))).*1.5]);
                    xlim('tight')

                    
                    line([0 (size(Clss',1))*1.02],[modelPLSDA.threshold.class_thr(ki)   modelPLSDA.threshold.class_thr(ki)],'color',[1 0 0],'linestyle','--');
                    line([size(ClssC,1)*1.02 size(ClssC,1)*1.02],[min(ylim)*1.1 max(ylim)*1.1],'color',[0 0 1],'linestyle','--'); 
                    ylim('tight')
                    hold off
                end
           else
                % Recreating the main axis (hAxesDiscPLSDA) if it was deleted before by the subplot construction
                num_axis = get(hDiscriminationPLSDA_Axes,'Children');
                if size(num_axis,1) > 1
                    delete(num_axis);
                    hAxesDiscPLSDA = axes(...
                        'Parent',hDiscriminationPLSDA_Axes,...
                        'Units','normalized',...
                        'Visible','off',...
                        'Box','off',...
                        'tag','axDisc',...
                        'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65
                end

                axes(hAxesDiscPLSDA);
                lngt =  size(modelpred.preds)+size(modelPLSDA.preds);

                [ClssC,~] = sortrows(GNATData.ycalV);
                [ClssV,~] = sortrows(GNATData.yvalV);
                Clss = [ClssC' ClssV'];

                GUIData.AxesPLSDA_cv.h = gscatter(1:lngt(1),[modelPLSDA.preds(:,optclss)' modelpred.preds(:,optclss)'],Clss,Clr,S,6,'off');                 
                for n = 1:length(GUIData.AxesPLSDA_cv.h)
                  set(GUIData.AxesPLSDA_cv.h(n,1), 'MarkerFaceColor', Clr(n));
                end 

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                grid on;hold on;

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;

                xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Classe %g',optclss),'FontSize',18,'FontName','Times New Woman')

%                 set(gca,'YLim',[-max(abs(get(gca,'YLim'))).*1.5 max(abs(get(gca,'YLim'))).*1.5]);
                xlim('tight')
                
                line([0 (size(Clss',1))*1.02],[modelPLSDA.threshold.class_thr(optclss)   modelPLSDA.threshold.class_thr(optclss)],'color',[1 0 0],'linestyle','--');
                line([size(ClssC,1)*1.02 size(ClssC,1)*1.02],[min(ylim)*1.1 max(ylim)*1.1],'color',[0 0 1],'linestyle','--'); 
                ylim('tight')
                hold off
           end
        end
        
        GUIData.modelPLSDA = modelPLSDA;
        GUIData.modelpred = modelpred;
        guidata(hPLOTfigure,GUIData);
    
        %% Permutation test
%         permtest();        
        
        %% Roc curves Plot 
        optclss = get(hRunClasses_PLSDA,'value');
        clss = size(unique(Classes),1);

        [~,col_default] = visualize_colors;
        num_class = max(Classes);
        cnt = 0;
        delete(findobj(hTabROCPLSDA , 'type', 'axes'));
        if optclss > clss % 'all' option selected
            for g=1:num_class
                % roc curve
                cnt = cnt + 1;
                GUIData.ROC.area = subplot(num_class,2,cnt,'Parent', hROCPLSDA);
                TPR = modelpred.threshold.sn(:,g)';
                FPR = 1 - modelpred.threshold.sp(:,g)';
                area(FPR,TPR,'FaceColor',col_default(1,:));
                box on
                xlabel('1 - specificity')
                ylabel('sensitivity')
                % area under ROC curve
                FPRarea = [0 FPR 1 0];
                TPRarea = [0 TPR 0 0];
                AUC = polyarea(FPRarea,TPRarea);
                AUC = round(AUC*100,2)/100;
                title(['ROC curve - class ' num2str(g) ' (AUC: ' num2str(AUC) ')']);
                hold on
                plot([0 1],[0 1],'k--'); %
                hold off

                % specificity and sensitivity
                cnt = cnt + 1;
                GUIData.ROC.thr = subplot(num_class,2,cnt,'Parent', hROCPLSDA);
                hold on
                plot(GUIData.ROC.thr,modelPLSDA.threshold.thr_val(2:end-1,g),modelpred.threshold.sn(2:end-1,g)','b')
                plot(GUIData.ROC.thr,modelPLSDA.threshold.thr_val(2:end-1,g),modelpred.threshold.sp(2:end-1,g)','r')
                hold off
                xlabel('threshold')
                ylabel('sn and sp ')
                title(['sensitivity (blue) and specificity (red) - class ' num2str(g)])
                xlim('tight')
                box on
            end
        else
            % Recreating the main axis (hAxesDiscPLSDA) if it was deleted before by the subplot construction
            GUIData.ROC.area = subplot(3,2,3,'Parent', hROCPLSDA); 
            TPR = modelpred.threshold.sn(:,optclss)';
            FPR = 1 - modelpred.threshold.sp(:,optclss)';
            hold on
            area(FPR,TPR,'FaceColor',col_default(1,:));
            box on
            xlabel('1 - specificity')
            ylabel('sensitivity')
            % area under ROC curve
            FPRarea = [0 FPR 1 0];
            TPRarea = [0 TPR 0 0];
            AUC = polyarea(FPRarea,TPRarea);
            AUC = round(AUC*100,2)/100;
            title(['ROC curve - class ' num2str(optclss) ' (AUC: ' num2str(AUC) ')'])
            plot([0 1],[0 1],'k--'); %
            hold off

            % specificity and sensitivity
            GUIData.ROC.thr = subplot(3,2,4,'Parent', hROCPLSDA);
            subplot(GUIData.ROC.thr)
            hold on
            plot(GUIData.ROC.thr,modelPLSDA.threshold.thr_val(2:end-1,optclss),modelpred.threshold.sn(2:end-1,optclss)','b')
            plot(GUIData.ROC.thr,modelPLSDA.threshold.thr_val(2:end-1,optclss),modelpred.threshold.sp(2:end-1,optclss)','r')
            xlim('tight')
            hold off
            xlabel('threshold')
            ylabel('sn and sp ')
            title(['sensitivity (blue) and specificity (red) - class ' num2str(optclss)])
            box on      

            % % Obtém TPR e specificity (ou FPR diretamente) do seu objeto
            % TPR = modelpred.threshold.sn(:,optclss)';      % sensibilidade (por threshold)
            % SPEC = modelpred.threshold.sp(:,optclss)';     % especificidade (por threshold)
            % FPR = 1 - SPEC;
            % 
            % % Ordena por FPR crescente
            % [FPRs, idx] = sort(FPR, 'ascend');
            % TPRs = TPR(idx);
            % 
            % % Assegura pontos fronteira (0,0) e (1,1) se desejar
            % if FPRs(1) > 0
            %     FPRs = [0, FPRs];
            %     TPRs = [0, TPRs];
            % end
            % if FPRs(end) < 1
            %     FPRs = [FPRs, 1];
            %     TPRs = [TPRs, 1];
            % end
            % 
            % % Calcula AUC com trapz
            % AUC = trapz(FPRs, TPRs);
            % AUC = round(AUC*100,2)/100;
            % 
            % % Plota curva ROC e preenche a área
            % GUIData.ROC.area = subplot(3,2,3,'Parent', hROCPLSDA);
            % plot(FPRs, TPRs, 'k-', 'LineWidth', 1.5); hold on;
            % % hFill = fill([FPRs fliplr(FPRs)], [TPRs zeros(1,numel(TPRs))], col_default(1,:), 'FaceAlpha', 0.25, 'EdgeColor', 'none');
            % plot([0 1],[0 1],'k--'); %








        end

        %% Confusion matrix
        ConfusionMatrix()
        guidata(hPLOTfigure,GUIData);
    end

    function permtest(source,eventdata)
          % check that the model is a pls or opls model.

          n = str2double(get(hEditPermutModelPLSDA,'String'));
          % check if a second argument was supplied correctly
          if isnan(n)
              warndlg('Number of permutation (n) must be a number','Warning'); 
              % use the default number of permutations: 100.
              n = 100;
              return
          elseif n < 1
              warndlg('Number of permutation (n) must be greater than 0','Warning');
              % use the default number of permutations: 100.
              n = 100;
              return
          end
        
%           n = 20;
          % extract the original response matrix from the model.
          Y = GNATData.ycalM;
        
          % initialize the validation arrays.
          S.Rsq.orig = GUIData.modelPLSDA.R2;
          S.Qsq.orig = GUIData.modelpred.Q2;
          S.Rsq.perm = zeros(n, 1);
          S.Qsq.perm = zeros(n, 1);
          S.r = zeros(n, 1);
          S.n = n;
          
          Factor = str2double(get(hEditFactorsModelPLSDA,'String')); 

          % Processing parameters
            opt.prepr{1} = get(hProcessing_PLSDA_Model_s,'Value');            
            switch  opt.prepr{1}
                case 1
                    opt.prepr{1} = 'mean';
                case 2 
                    opt.prepr{1} = 'auto';
                case 3
                    opt.prepr{1} = 'pareto';
            end
            
            opt.algorithm='simpls';
            opt.detailedoutput='on';
            opt.classcriterion='maxY';
            
            opt.ldax='predy';
            opt.prior='uniform';
            opt.cv.cvtype='syst123'; 
            opt.cv.cvsegments=5;   

            % Removing the outliers determined by the user
            remove = ismember(GNATData.objetos.treinamento,GNATData.outlier);     
            outlier = GNATData.Classes;
            Clss = outlier(GNATData.objetos.treinamento);
            labels_s = num2cell(GNATData.objetos.treinamento);
            Clss(remove,:) = [];

          % Defining the current figure
          axes(hAxesPermPLSDA);

          % run through the permutations
          h = waitbar(0,sprintf('Calculating the %d permutated model',0)); 
          tic
          if get(hCheckParPerm,'value') 
              cluster = parcluster;
              parfor idxp = 1:n
%                   waitbar(idxp/n,h, sprintf('Calculating the %d permutated model',idxp)) % update the waitbar
                  % shuffle the response matrix.
                  i = randperm(size(GNATData.ycalM,1))';
                  Yshuf = GNATData.ycalM(i,:);
    
                  % build the model.
                  modelPLSDAperm=doPLSDA(GNATData.xcal, Yshuf, Factor, opt,GNATData.ycalV);
                  modelpredperm=doPLSDApred(GNATData.xval, GNATData.yvalM, modelPLSDAperm);
            
                  % calculate the correlation between the original and shuffled response.
                  r(idxp) = mean(diag(abs(corr(Y, Yshuf))));
            
                  % add the cross-validation statistics to the lot.
                  Rsqperm(idxp) = modelPLSDAperm.R2;
                  Qsqperm(idxp) = modelpredperm.Q2;            
              end
              S.r = r';
              S.Rsq.perm = Rsqperm';
              S.Qsq.perm = Qsqperm';
          else
              for idx = 1 : n
                 waitbar(idx/n,h, sprintf('Calculating the %d permutated model',idx)) % update the waitbar
                 % shuffle the response matrix.
                 i = randperm(size(GNATData.ycalM,1))';
                 Yshuf = GNATData.ycalM(i,:);
    
                 % build the model.
                 modelPLSDAperm=doPLSDA(GNATData.xcal, Yshuf, Factor, opt,GNATData.ycalV);
                 modelpredperm=doPLSDApred(GNATData.xval, GNATData.yvalM, modelPLSDAperm);
            
                 % calculate the correlation between the original and shuffled response.
                 S.r(idx) = mean(diag(abs(corr(Y, Yshuf))));
            
                 % add the cross-validation statistics to the lot.
                 S.Rsq.perm(idx) = modelPLSDAperm.R2;
                 S.Qsq.perm(idx) = modelpredperm.Q2;
              end
          end
          close(h)
          toc

          % non-parametrically calculate the p-values with Monte Carlo correction.
          S.Rsq.p = (sum(S.Rsq.perm >= S.Rsq.orig) + 1) / (n + 1);
          S.Qsq.p = (sum(S.Qsq.perm >= S.Qsq.orig) + 1) / (n + 1);

          if S.Rsq.p<0.01
              S.Rsq.p=0.01;
          end

          if S.Qsq.p<0.01
              S.Qsq.p=0.01;
          end


          % calculate the slopes of the fit lines.
          S.Rsq.m = [S.r - 1] \ (S.Rsq.perm - S.Rsq.orig);
          S.Qsq.m = [S.r - 1] \ (S.Qsq.perm - S.Qsq.orig);
        
          % calculate the two points of the fit lines.
          S.Rsq.xy = [[0; 1], [S.Rsq.orig - S.Rsq.m; S.Rsq.orig]];
          S.Qsq.xy = [[0; 1], [S.Qsq.orig - S.Qsq.m; S.Qsq.orig]];
        
          S.A = Factor;
          %%%% Plot section %%%%
        
          % build the legend strings.
          % r2str = sprintf('R^2 (p = %.02e)', S.Rsq.p);
          % q2str = sprintf('Q^2 (p = %.02e)', S.Qsq.p);
          r2str = 'R^2';
          q2str = 'Q^2';
          legstr = {r2str, q2str};
        
          % build the x-axis label string.
          xstr = sprintf('Correlation of %d permutations using %d components', S.n, S.A);
        
          % plot the cross-validation lines.
          plot(hAxesPermPLSDA,S.Rsq.xy(:,1), S.Rsq.xy(:,2), 'color', [0, 1, 0]);
          hold on
          plot(hAxesPermPLSDA,S.Qsq.xy(:,1), S.Qsq.xy(:,2), 'color', [0, 0, 1]);
          
          % plot the cross-validation points.
          scatter(hAxesPermPLSDA,[1; S.r], [S.Rsq.orig; S.Rsq.perm], [], [0, 1, 0],'MarkerFaceColor', 'g');
          scatter(hAxesPermPLSDA,[1; S.r], [S.Qsq.orig; S.Qsq.perm], [], [0, 0, 1],'MarkerFaceColor', 'b');

          % add a plot legend.
          line([min(xlim) max(xlim)],[0 0],'color','black','linestyle','--');
          GNATData.LegendPerm = legend(hAxesPermPLSDA,legstr,'Location','northwest');
          
          % Information in the figure
          A = 'Permutation test results';
          B = sprintf('Interception: R^2 = %.3f, p-value < %.2f,  Q^2 = %.3f, p-value < %.2f',S.Rsq.xy(1,2), S.Rsq.p, S.Qsq.xy(1,2), S.Qsq.p);
          title({A; B});
          xlabel(xstr);
          ylabel('R^2 / Q^2');
          grid on
          hold off

          % Plot histogram of permuted R² values
          figure('Name','Permutation Test - R² and Q² Distributions','NumberTitle','off');
          subplot(1,2,1)
          histogram(S.Rsq.perm, 'FaceColor', [0.6 0.9 0.6], 'EdgeColor', 'k');
          hold on
          line([S.Rsq.orig S.Rsq.orig], ylim, 'Color', 'g', 'LineWidth', 2, 'LineStyle', '--');
          title(sprintf('R^2 Permutation Distribution\np = %.4f', S.Rsq.p));
          xlabel('R^2 values'); ylabel('Frequency');
          legend('Permuted R^2','Original R^2','Location','best');
          grid on
          hold off

          % Plot histogram of permuted Q² values
          subplot(1,2,2)
          histogram(S.Qsq.perm, 'FaceColor', [0.6 0.6 0.9], 'EdgeColor', 'k');
          hold on
          line([S.Qsq.orig S.Qsq.orig], ylim, 'Color', 'b', 'LineWidth', 2, 'LineStyle', '--');
          title(sprintf('Q^2 Permutation Distribution\np = %.4f', S.Qsq.p));
          xlabel('Q^2 values'); ylabel('Frequency');
          legend('Permuted Q^2','Original Q^2','Location','best');
          grid on
          hold off
    end    
    function ChangingScorePLS_Callback(source,eventdata)
        Tab = get(hTabGroupPLSDA,'SelectedTab');
        % Turn on and off Visualization Panel for each Tab
        switch Tab
            case hTabScorePLSDA
                children = get(hCalValGroup_pls,'Children');
                set(children,'Enable','off');
            case hTabLoadingPLSDA
                children = get(hCalValGroup_pls,'Children');
                set(children,'Enable','off');    
            case hTabVIPPLSDA
                children = get(hCalValGroup_pls,'Children');
                set(children,'Enable','off');                
            case hTabAxesPLSDA
                children = get(hCalValGroup_pls,'Children');
                set(children,'Enable','on');           
            case hTabROCPLSDA
                children = get(hCalValGroup_pls,'Children');
                set(children,'Enable','on');     
            case hTabConfMatPLSDA
                children = get(hCalValGroup_pls,'Children');
                set(children,'Enable','off');                 
        end
     end
    function EnableZaxis_PLSDA_Callback(source,eventdata)
        if get(hCheckUse3D_PLSDA,'value')
            set(hScore_PLSDA_Model_Z,'enable','on')
            ModelPLSDA()
        else
            set(hScore_PLSDA_Model_Z,'enable','off')
            ModelPLSDA()
        end
    end
    function resize(FigH, ~, AxesH)
        persistent blockCalls  % Reject calling this function again until it is finished
        if any(blockCalls)
            return
        end
        blockCalls = true;
        
        doResize = true;
        while doResize   % Repeat until the figure does not change its size anymore
           siz = get(FigH, 'Position');
           pause(1.0);  % Of course here are some real calculations
           set(AxesH, 'Position', [5, 5, siz(3:4)-10]);
           drawnow;
           
           doResize = ~isequal(siz, get(FigH, 'Position'));
        end
        
        blockCalls = false;  % Allow further calls again
    end
    function Xshuf = shuffle (X)
       % randomly shuffle the rows.
       [~, idx] = sort(rand(rows(X), 1));
       Xshuf = X(idx,:);
    end

%% ----------------- OPLS
    function ModelOPLS(source,eventdata)
        GUIData = guidata(hPLOTfigure);  

        Factor = str2double(get(hEditFactorsModel,'String'));   
        nOSC = str2double(get(hEditOrthogonalModel,'String')); 
        
        % Create a case where the model wasn't create by the user 
        
        modelOPLS = opls2(GNATData.xcal, GNATData.ycalM,nOSC, Factor, GNATData.xval);
        
        if get(hRadioCal,'Value')
            Opt = [1 0 0];
        elseif get(hRadioVal,'Value')
            Opt = [0 1 0];
        elseif get(hRadioCalVal,'Value')
            Opt = [0 0 1];
        end

        delete(findobj(AxesModelTab, 'type', 'axes'));

        if Opt(1) == 1
            % Calibration plot
            for ki=1:size(modelpred.preds,2)
                            
                Nome{1,1}='1' ;  Nome{1,2} = 'k';
                Nome{2,1}='2' ; Nome{2,2} = 'm';
                Nome{3,1}='3' ;  Nome{3,2} = 'r';
                          
                subplot(2,2,ki,'Parent', AxesModelTab);
%                 tp1=find(YpredM(:,ki));
                
                plot(1:length(modelPLSDA.preds),modelPLSDA.preds(:,ki),'o','MarkerFaceColor','b'), hold on
                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;
                marc=strcat(Nome{ki,2},'o');
    %             plot(tp1,yprev_cal(tp1,ki),marc,'MarkerFaceColor',marc(:,1)), hold on
                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;
    %             hline(ts(ki),'r')
                title(Nome{ki,1},'FontSize',14,'FontName','Times New Woman')
                xlabel('Sample','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Classe %g',ki),'FontSize',18,'FontName','Times New Woman')
            end
        elseif Opt(2) == 1
           % Validation plot
            for ki=1:size(modelpred.preds,2)
                            
                Nome{1,1}='1' ;  Nome{1,2} = 'k';
                Nome{2,1}='2' ;  Nome{2,2} = 'm';
                Nome{3,1}='3' ;  Nome{3,2} = 'r';
                          
                subplot(2,2,ki,'Parent', AxesModelTab);
%                 tp1=find(YpredM(:,ki));
                
                plot(1:length(modelpred.preds),modelpred.preds(:,ki),'o','MarkerFaceColor','b'), hold on
                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;
                marc=strcat(Nome{ki,2},'o');
    %             plot(tp1,yprev_cal(tp1,ki),marc,'MarkerFaceColor',marc(:,1)), hold on
                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;
    %             hline(ts(ki),'r')
                title(Nome{ki,1},'FontSize',14,'FontName','Times New Woman')
                xlabel('Sample','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Classe %g',ki),'FontSize',18,'FontName','Times New Woman')
            end

        elseif Opt(3) == 1
           % Calibration & Validation plot
            for ki=1:size(modelpred.preds,2)
                            
                Nome{1,1}='1' ;  Nome{1,2} = 'k';
                Nome{2,1}='2' ;  Nome{2,2} = 'm';
                Nome{3,1}='3' ;  Nome{3,2} = 'r';
                          
                subplot(2,2,ki,'Parent', AxesModelTab);
%                 tp1=find(YpredM(:,ki));
                lngt =  size(modelpred.preds)+size(modelPLSDA.preds);

                plot(1:lngt(1),[modelPLSDA.preds(:,ki)' modelpred.preds(:,ki)'],'o','MarkerFaceColor','b'), hold on
                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;
                marc=strcat(Nome{ki,2},'o');
    %             plot(tp1,yprev_cal(tp1,ki),marc,'MarkerFaceColor',marc(:,1)), hold on
                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;
    %             hline(ts(ki),'r')
                title(Nome{ki,1},'FontSize',14,'FontName','Times New Woman')
                xlabel('Sample','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Classe %g',ki),'FontSize',18,'FontName','Times New Woman')
            end
        end
        guidata(hPLOTfigure,GUIData);
    end

%% ----------------- OPLSDA
% ------------------------- Parameters CV------------------%
    function MethodCheck_CV_Callback_OPLSDA(source,eventdata)
        GUIData.CV.method_cv = get(hMethodCVOPLSDA,'value');
        set(hCVRunOPLSDA,'Enable','off');
        switch GUIData.CV.method_cv
            case 1 %'K-fold'
                set(hEditFoldOPLSDA,'Enable','on')
                set(hEditFoldOPLSDA,'String',num2str(10))
                set(hSliderFoldCVOPLSDA,'Enable','on')
                set(hSliderFoldCVOPLSDA,'Value',10)
                set(hLeftFoldCVOPLSDA,'ForegroundColor',[0 0 0])
                set(hRightFoldCVOPLSDA,'ForegroundColor',[0 0 0])                
                set(hEditFoldOPLSDA,'Enable','on')
                set(hSliderFoldCVOPLSDA,'Enable','off')
                set(hLeftDivisionOPLSDA,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivisionOPLSDA,'ForegroundColor',[0.5 0.5 0.5])                           
            case 2 %'Leane-One-Out'
                set(hEditFoldOPLSDA,'Enable','off')
                set(hEditFoldOPLSDA,'String',num2str(size(GNATData.xcal',2)))
                set(hSliderFoldCVOPLSDA,'Enable','off')
                set(hSliderFoldCVOPLSDA,'Value',size(GNATData.xcal',2));
                set(hLeftFoldCVOPLSDA,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightFoldCVOPLSDA,'ForegroundColor',[0.5 0.5 0.5])
                set(hEditFoldOPLSDA,'Enable','off')
                set(hSliderFoldCVOPLSDA,'Enable','off')
                set(hLeftDivisionOPLSDA,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivisionOPLSDA,'ForegroundColor',[0.5 0.5 0.5])                
            case 3 %'Contiguous Block'
                set(hEditFoldOPLSDA,'Enable','on')
                set(hSliderFoldCVOPLSDA,'Enable','on')
                set(hLeftFoldCVOPLSDA,'ForegroundColor',[0 0 0])
                set(hRightFoldCVOPLSDA,'ForegroundColor',[0 0 0])
                set(hEditFoldOPLSDA,'Enable','off')
                set(hSliderFoldCVOPLSDA,'Enable','off')
                set(hLeftDivisionOPLSDA,'ForegroundColor',[0.5 0.5 0.5])
                set(hRightDivisionOPLSDA,'ForegroundColor',[0.5 0.5 0.5])                
            case 4 %'Monte Carlo'
                set(hEditFoldOPLSDA,'Enable','on')
                set(hSliderFoldCVOPLSDA,'Enable','on')
                set(hLeftFoldCVOPLSDA,'ForegroundColor',[0 0 0])
                set(hRightFoldCVOPLSDA,'ForegroundColor',[0 0 0])
                set(hEditFoldOPLSDA,'Enable','on')
                set(hSliderFoldCVOPLSDA,'Enable','on')
                set(hLeftDivisionOPLSDA,'ForegroundColor',[0 0 0])
                set(hRightDivisionOPLSDA,'ForegroundColor',[0 0 0])                 
            otherwise
                %Do nothing
        end
        guidata(hPLOTfigure,GUIData); 
    end    
    function EditFold_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 

        % Turn off the Run button untill the apply button is pressed
        set(hCVRunOPLSDA,'Enable','off');  

        % Take and check the user input
        Fold=round(str2num(get(hEditFoldOPLSDA,'String'))); %#ok<ST2NM>
        set(hSliderFoldCVOPLSDA,'Value',Fold);
        if isempty(Fold)
            warndlg('Fold must be numeric')
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(1));
            set(hSliderFoldCVOPLSDA,'Value',1);
        elseif ~isnumeric(Fold)
            warndlg('Fold must be numeric')
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(1));
            set(hSliderFoldCVOPLSDA,'Value',1); 
        elseif Fold < 1   
            warndlg('Fold must be equal or gratter than 1')
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(1));
            set(hSliderFoldCVOPLSDA,'Value',1); 
        elseif Fold > size(GNATData.ycalV,1)
            a = size(GNATData.ycalV,1);
            warndlg(sprintf('Fold must be less than %g', a));
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(10));
            set(hSliderFoldCVOPLSDA,'Value',10); 
        else
            set(hSliderFoldCVOPLSDA,'Value',Fold);
        end 

        guidata(hPLOTfigure,GUIData);        
    end
    function SliderFold_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);

        % Turn off the Run button untill the apply button is pressed
        set(hCVRunOPLSDA,'Enable','off');  

        % Take and set the user input
        Fold=round(get(hSliderFoldCVOPLSDA,'Value'));
        set(hEditFoldOPLSDA,'String',num2str(Fold)); 
        set(hCVRunOPLSDA,'Enable','off');

        guidata(hPLOTfigure,GUIData);        
    end
    function EditMaxLV_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 

        % Turn off the Run button untill the apply button is pressed
        set(hCVRunOPLSDA,'Enable','off');  

        % Take and check the user input        
        MaxLV=round(str2num(get(hEditCVOPLSDA,'String'))); %#ok<ST2NM>
        set(hSliderCVOPLSDA,'Value',MaxLV);
        if isempty(MaxLV)
            warndlg('Number of Latent Variables  must be numeric')
            uiwait(gcf)
            set(hEditCVOPLSDA,'String',num2str(1));
            set(hSliderCVOPLSDA,'Value',1);
        elseif ~isnumeric(MaxLV)
            warndlg('Number of Latent Variables  must be numeric')
            uiwait(gcf)
            set(hEditCVOPLSDA,'String',num2str(10));
            set(hSliderCVOPLSDA,'Value',10);
        elseif MaxLV > 20
            warndlg('Number of Latent Variables must be less than 20')
            uiwait(gcf)
            set(hEditCVOPLSDA,'String',num2str(10));
            set(hSliderCVOPLSDA,'Value',10);                        
        else
            set(hSliderCVOPLSDA,'Value',MaxLV);
        end    
        
        guidata(hPLOTfigure,GUIData);        
    end
    function SliderCVGroup_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);

        % Turn off the Run button untill the apply button is pressed
        set(hCVRunOPLSDA,'Enable','off');  

        % Take and set the user input 
        CVGroup=round(get(hSliderCVOPLSDA,'Value'));
        set(hEditCVOPLSDA,'String',num2str(CVGroup));
        set(hCVRunOPLSDA,'Enable','off');

        guidata(hPLOTfigure,GUIData); 
    end
    function EditPercIn_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);

        % Turn off the Run button untill the apply button is pressed
        set(hCVRunOPLSDA,'Enable','off');  

        % Take and check the user input 
        Div=round(str2num(get(hEditFoldOPLSDA,'String'))); %#ok<ST2NM>
        set(hSliderFoldCVOPLSDA,'Value',Div);        
        if isempty(Div)
            warndlg('Percentage must be numeric')
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(70));
            set(hSliderFoldCVOPLSDA,'Value',70);
        elseif ~isnumeric(Div)
            warndlg('Percentage must be numeric')
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(70));
            set(hSliderFoldCVOPLSDA,'Value',70);
        elseif Div > 100
            warndlg('Percentage must be beteewn 1 and 100')
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(70));
            set(hSliderFoldCVOPLSDA,'Value',70);   
        elseif Div < 0
            warndlg('Percentage must be beteewn 1 and 100')
            uiwait(gcf)
            set(hEditFoldOPLSDA,'String',num2str(70));
            set(hSliderFoldCVOPLSDA,'Value',70);              
        else
            set(hSliderFoldCVOPLSDA,'Value',Div);
        end         

        guidata(hPLOTfigure,GUIData);        
    end
    function SliderSliderDiv_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 

        % Turn off the Run button untill the apply button is pressed
        set(hCVRunOPLSDA,'Enable','off');  

        % Take and check the user input 
        Div=round(get(hSliderFoldCVOPLSDA,'Value'));
        set(hEditFoldOPLSDA,'String',num2str(Div)); 
        set(hCVRunOPLSDA,'Enable','off');

        guidata(hPLOTfigure,GUIData);        
    end
% ------------------------- Cross-Validation --------------%
    function CVApply_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  
        
        % Get user input
        GUIData.CV.Fold = str2double(get(hEditFoldOPLSDA,'String'));
        GUIData.CV.LV = str2double(get(hEditCVOPLSDA,'String'));
        GUIData.CV.Division = str2double(get(hEditFoldOPLSDA,'String')); 
        GUIData.CV.shuffle = get(hCheckshuffleOPLSDA,'Value');     
        
        % Perform the division in Cal and Val
        [index,test_X,train_X,test_y,train_y] = CrossValidation_splits(GNATData.xcal,...
            GNATData.ycalM,GUIData.CV.method_cv,GUIData.CV.shuffle,GUIData.CV.Fold,GUIData.CV.Division);           

        % Construct the color table for calibration and validation for each fold
        Samples = "Sample_" + string(1:size(GNATData.xcal',2));
        ycalV = string(GNATData.ycalV);       
        colergen = @(cor,text) ['<html><table border=0 width=20 bgcolor=',cor,'><TR><TD>',text,'</TD></TR> </table><html>'];
        index.fold = ycalV;
        columns = zeros(1,GUIData.CV.Fold);
        for i = 1:GUIData.CV.Fold
            index.fold(index.test{i},i) = colergen('#D95319','V');
            index.fold(index.train{i},i) = colergen('#4DBEEE','C');
            columns(1,i) = sprintf("Fold %02d",i);   
        end    
        folds = string(index.fold);
        set(hClassInfoTableOPLSDA,'Data',[cellstr(Samples'),cellstr(ycalV),cellstr(folds)]);
        set(hClassInfoTableOPLSDA,'Visible','on')        
        set(hClassInfoTableOPLSDA,'columnname',['Sample','Class',columns]);

        % Save the split
        GUIData.CV.index = index;
        GUIData.CV.test_X = test_X;
        GUIData.CV.train_X = train_X;
        GUIData.CV.test_y = test_y;
        GUIData.CV.train_y = train_y;

        % Enable the run button
        set(hCVRunOPLSDA,'Enable','on');  

        guidata(hPLOTfigure,GUIData); 
    end
    function CVRun_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure); 
        
        % Separation of datasets according to the user's input
        NClass = size(GNATData.ycalM,2); 
        Division = (GUIData.CV.Division)./100; 
        
        % Matrix divided in calibration and validation at GNAT
        X = GNATData.xcal;
        Y = GNATData.ycalM;

        [~,ycl]=max(Y,[],2);
        Y=ycl; 
        ns=size(X,1);

        Ypredcv=zeros(ns,GUIData.CV.LV);
        YResiduals=zeros(ns,NClass,GUIData.CV.LV); 

        % Parameters defined by me to PLS calculation - Create objects in the future for the user control this one
        opt.prepr={'mean' 'mean'};
        opt.algorithm='simpls';
        opt.detailedoutput='on';
        opt.classcriterion='maxY';        
       
        % Contruction of the Cross Validation model
        h=waitbar(0,'Building the PLS-DA cross validation model');
        for k = 1:GUIData.CV.Fold
            h=waitbar(k/GUIData.CV.Fold);
            for i=1:GUIData.CV.LV
                indextest=GUIData.CV.index.test{k};
                % Creating the model
                mi=doPLSDA(GUIData.CV.train_X{k}, GUIData.CV.train_y{k}, i, opt,GNATData.ycalV);
                % Testing the model
                pi=doPLSDApred(GUIData.CV.test_X{k}, GUIData.CV.test_y{k}, mi);
                % Predicted classes
                Ypredcv(indextest,i)=pi.classification.PredClass;
                % Calculate the residual for each class and n of LV
                YResiduals(indextest,:,i) = pi.YResiduals;
                YpredQ2(k,:)=pi.Q2;
            end   
        end
        close(h)
        
        rmsecv=(YResiduals).^2;
        GUIData.CV.model.rmsecv=reshape(sqrt(rmsecv./ns),[],GUIData.CV.LV)';
        GUIData.CV.model.CrossVal.PredClassCV=Ypredcv; 
        GUIData.CV.model.CrossVal.TrueClass=Y;
        GUIData.CV.model.YResiduals=YResiduals;       
        GUIData.CV.model.YpredQ2=YpredQ2;  

        % Error calculatio (RMSECV) as a average for all classes.
        plot(AxesRMSECVOPLSDA,1:GUIData.CV.LV, sum(GUIData.CV.model.rmsecv,2), 'o-r')
        xlabel(AxesRMSECVOPLSDA,'Number of Latent Variables','FontSize',14);
        ylabel(AxesRMSECVOPLSDA,'Root Mean Squared Error of Cross-Validation (%)','FontSize',14);
        axis tight
        title(AxesRMSECVOPLSDA,'Selection of the optimal number of LVs')

        % Constructing Tables for Figures of Merit and Confusion table        
        cmatrix=cell(1,GUIData.CV.LV); 
        ccrate=cell(1,GUIData.CV.LV);
        cct=zeros(1,GUIData.CV.LV);
        
        for i=1:GUIData.CV.LV
            cmatrix{i}=cmatrixcalc(Ypredcv(:,i), Y, max(Y));
            ccrate{i}=100*diag(cmatrix{i})./sum(cmatrix{i},2); 
            cct(i)=100*sum(diag(cmatrix{i}))/length(Y);            
        end
        GUIData.CV.model.CrossVal.ConfusionMatrix=cmatrix; 
        GUIData.CV.model.CrossVal.CorrClassRate=ccrate; 
        GUIData.CV.model.CrossVal.TotalClassErr=cct; 

        set(hConfusionTable,'Data',GUIData.CV.model.CrossVal.ConfusionMatrix{1});
        set(hConfusion_PLS,'Enable','on');
        set(hConfusion_PLS,'string',1:GUIData.CV.LV);
        
        guidata(hPLOTfigure,GUIData);  

    end
    function ChangeTab_OPLSDA_Callback(source,eventdata)
        Tab = get(hTabGroupPLSDA_CV,'SelectedTab');
        % Turn on and off Visualization Panel for each Tab
        switch Tab
            case hTabSplitCV 
                set(hVisualPanelResults,'Visible','on')
                set(hVisualPanelOutlier,'Visible','off')
                set(hVisualPanelConfusion,'Visible','off')   
            case hConfusionMatrix
                set(hVisualPanelResults,'Visible','off')
                set(hVisualPanelOutlier,'Visible','off')
                set(hVisualPanelConfusion,'Visible','on')              
            case hResiduals
                set(hVisualPanelResults,'Visible','on')
                set(hVisualPanelOutlier,'Visible','off')
                set(hVisualPanelConfusion,'Visible','off')                     
        end

        Tab = get(hTabGroupCVOPLSDA,'SelectedTab');
        % Turn on and off Visualization Panel for each Tab
        switch Tab
            case hTabSplitCV_oplsda
                set(hVisualPanelResults_oplsda,'Visible','on')
                set(hVisualPanelOutlier_oplsda,'Visible','off')
                set(hVisualPanelConfusion_oplsda,'Visible','off')   
            case hConfusionMatrix_oplsda
                set(hVisualPanelResults_oplsda,'Visible','off')
                set(hVisualPanelOutlier_oplsda,'Visible','off')
                set(hVisualPanelConfusion_oplsda,'Visible','on')              
            case hResiduals_oplsda
                set(hVisualPanelResults_oplsda,'Visible','on')
                set(hVisualPanelOutlier_oplsda,'Visible','off')
                set(hVisualPanelConfusion_oplsda,'Visible','off')                     
        end
     end
% ------------------------- Model -------------------------%
    function Classes_RMSECV_OPLSDA_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  

        if get(hCheckLabelsAllClasses,'Value') == 0
            set(hMethodCV_Class,'Enable','on') 
            set(hMethodCV_Class,'string',"Class 1|Class 2|Class 3");  

            ns=size(GNATData.xcal,1);
            RMSE = sqrt(sum((GUIData.CV.model.YResiduals).^2,1)/(ns));
            GUIData.CV.model.rmsecv=reshape(RMSE,[],GUIData.CV.LV)';

            clss = get(hMethodCV_Class,'Value');
            plot(AxesRMSECVOPLSDA,1:GUIData.CV.LV, GUIData.CV.model.rmsecv(:,clss), 'o-r')
            xlabel(AxesRMSECVOPLSDA,'Number of Latent Variables','FontSize',14);
            ylabel(AxesRMSECVOPLSDA,'Root Mean Squared Error of Cross-Validation (%)','FontSize',14);
            axis tight
            title(AxesRMSECVOPLSDA,'Selection of the optimal number of LVs')
        else
            ns=size(GNATData.xcal,1);
            rmsecv=(GUIData.CV.model.YResiduals).^2;
            GUIData.CV.model.rmsecv=reshape(sqrt(rmsecv./ns),[],GUIData.CV.LV)';

            plot(AxesRMSECVOPLSDA,1:GUIData.CV.LV, sum(GUIData.CV.model.rmsecv,2), 'o-r')
            xlabel(AxesRMSECVOPLSDA,'Number of Latent Variables','FontSize',14);
            ylabel(AxesRMSECVOPLSDA,'Root Mean Squared Error of Cross-Validation (%)','FontSize',14);
            axis tight
            title(AxesRMSECVOPLSDA,'Selection of the optimal number of LVs')  
        end
 

        guidata(hPLOTfigure,GUIData);        
    end  
    function OPLS_Tables_Callback(source,eventdata)
        GUIData = guidata(hPLOTfigure);  

        GUIData.PLS_N=get(hConfusion_PLS,'value');
        set(hConfusionTable,'Data',GUIData.modelPLSDA_cv.CrossVal.ConfusionMatrix{GUIData.PLS_N});
        
        guidata(hPLOTfigure,GUIData);
    end

    function ModelOPLSDA(source,eventdata)
        %% Taking user input
        GUIData = guidata(hPLOTfigure);  
        Factor = str2double(get(hEditFactorsModelOPLSDA,'String'));   
        nOSC = str2double(get(hEditOrthogonalModel,'String')); % we are aways removing only the first component

        if ~isfield(GNATData,'modelOPLSDA')
            % modify option of plots to create
            set(hScore_OPLSDA_Model_X,'string',1:str2double(get(hEditFactorsModelOPLSDA,'String')));
            set(hScore_OPLSDA_Model_Y,'string',1:str2double(get(hEditFactorsModelOPLSDA,'String')));
            set(hScore_OPLSDA_Model_Z,'string',1:str2double(get(hEditFactorsModelOPLSDA,'String')));
    
            % processing parameters
            opt.prepr{1} = get(hProcessing_OPLSDA_Model_s,'Value');
            switch  opt.prepr{1}
                case 1
                    opt.prepr{1} = 'mean';
                case 2 
                    opt.prepr{1} = 'auto';
                case 3
                    opt.prepr{1} = 'pareto';
            end
    
            % Processing parameters
            opt.algorithm='simpls';
            opt.detailedoutput='on';
            opt.classcriterion='maxY';
            
            opt.ldax='predy';
            opt.prior='uniform';
            opt.cv.cvtype='syst123'; 
            opt.cv.cvsegments=5; 
    
            % Removing the outliers determined by the user
            remove = ismember(GNATData.objetos.treinamento,GNATData.outlier);     
            outlier = GNATData.Classes;
            Clss = outlier(GNATData.objetos.treinamento);
            labels_s = num2cell(GNATData.objetos.treinamento);
            Clss(remove,:) = [];
            labels_s(remove,:) = [];

            if get(hVariables_OPLSDA_Model_s,'Value') == 3 
                selected_intervals = GUIData.biPLS.Variables;
                Model.allint = GUIData.biPLS.biModel.allint;
                if selected_intervals == 0 
                    modelOPLSDA=doPLSDA(GNATData.xcal, GNATData.ycalM, Factor, opt);
                    modelpred=doPLSDApred(GNATData.xval, GNATData.yvalM, modelOPLSDA);
                else  
                    selected_vars=[];
                    for i=1:max(size(selected_intervals))
                       temp=Model.allint(selected_intervals(i),2):Model.allint(selected_intervals(i),3);
                       selected_vars=[selected_vars temp];
                    end
                    modelOPLSDA=doPLSDA(GNATData.xcal(:,selected_vars), GNATData.ycalM, Factor, opt);
                    modelpred=doPLSDApred(GNATData.xval(:,selected_vars), GNATData.yvalM, modelOPLSDA);
                end
            else
                modelOPLSDA = oplsda(GNATData.xcal, GNATData.ycalM,nOSC, Factor, GNATData.xval,GNATData.yvalM,opt);
            end

            GUIData.modelOPLSDA = modelOPLSDA;
            assignin('base','modelOPLSDA',GUIData.modelOPLSDA)

            % Table Variance Captured by OPLS-DA
            % TableData(:,1)=modelOPLSDA.eigvalue;
            % TableData(:,2)=modelOPLSDA.explvar{1,1};
            % TableData(:,3)=cumsum(modelOPLSDA.explvar{1,1});
            % set(hTableEigenvalues,'Data',TableData);

            % Making a numerical label for each sample               
            symbols = {'o','s','^','d','h','v','*','x','<','>','p'};  
            colors = ['g','b','m','c','y','b'];
            
            % Saving the class sequence
            [cc,ia]=unique(GNATData.Classes);
            ClassesValue = num2str(cc);                
            GNATData.ClassesValue = ClassesValue;
        
            % Create legend for classe define by the user
            if ~isempty(Labels) 
                UserLegend = Labels(ia); 
                a = cellfun(@isempty,UserLegend);
                str = string(cc);
                aa = cellstr(str);
                aa(~a) = {''};
                UserLegend(a) = {''};
                ab = append(aa,UserLegend);                     
                if isempty(UserLegend{1})
                    UserLegend{1} = '0';                
                end
            end    
            if sum(GNATData.ClassesValue == '0') == 1
                UserLegend{1} = '0';
                colors = ['r', colors];
            else
                % do nothing
            end
        
            % Permutating the number of symbols and colors for class > 7
            if size(ClassesValue,1) > size(colors,2)
                k = ceil(size(ClassesValue,1)./size(colors,2));
                c = repmat(colors,1,k);
                Clr = c(str2num(ClassesValue));
            else
                c = repmat(colors,1,2);
                Clr = c(str2num(ClassesValue));
            end                     
            if size(ClassesValue,1) > size(symbols,2)
                k = ceil(size(ClassesValue,1)./size(symbols,2));
                s = repmat(symbols,1,k);  
                Sym = s(str2num(ClassesValue));            
            else
                s = repmat(symbols,1,2);
                Sym = s(str2num(ClassesValue)); 
            end     
        
            % Parameters to constrct plots
            S = char(Sym);
            if get(hRadioCalOPLSDA,'Value')
                Opt = [1 0 0];
            elseif get(hRadioValOPLSDA,'Value')
                Opt = [0 1 0];
            elseif get(hRadioCalValOPLSDA,'Value')
                Opt = [0 0 1];
            end 
        
            PCx = get(hScore_OPLSDA_Model_X,'Value');
            PCy = get(hScore_OPLSDA_Model_Y,'Value');
            PCz = get(hScore_OPLSDA_Model_Z,'Value');

            %% Score plots
            axes(hAxesScoreOPLSDA);   
            % Score Model Plot           
            % 3D SCORE
            % Defining the current axis
    %         if get(hCheckUse3D_OPLSDA,'value')
    %             % Plotting 3D data with classes
    %             GUIData.AxesScoreOPLS.h3 = gscatter3(...
    %                modelPLSDA.scores{1,1}(:,(get(PCx,'value'))),...
    %                modelPLSDA.scores{1,1}(:,(get(PCy,'value'))),...
    %                modelPLSDA.scores{1,1}(:,(get(PCz,'value'))),...
    %                 Clss,Clr,S,6,'auto');   
    %             axis('tight');
    % 
    %             % Defing the apperance 
    %             set(GUIData.AxesScoreOPLS.h3,'LineWidth',1);
    %             set(hAxesScorePLSDA,'LineWidth',1); 
    %             set(hAxesScorePLSDA,'Box','on');
    % 
    %             % Determining the ellipses for every class
    %             hold on;
    %             Error_elipse3D(modelPLSDA.scores{1, 1}(:,[(get(hScore_PLSDA_Model_X,'value')),(get(hScore_PLSDA_Model_Y,'value')),(get(hScore_PLSDA_Model_Z,'value'))]),Clss,Clr) 
    %             hold off;             
    %                 
    %             % Determining the limits for X, Y and Z axis
    %             set(hAxesScorePLSDA,'XLim',[-max(abs(get(hAxesScorePLSDA,'XLim'))).*1.5 max(abs(get(hAxesScorePLSDA,'XLim'))).*1.5]);
    %             set(hAxesScorePLSDA,'YLim',[-max(abs(get(hAxesScorePLSDA,'YLim'))).*1.5 max(abs(get(hAxesScorePLSDA,'YLim'))).*1.5]);
    %             set(hAxesScorePLSDA,'ZLim',[-max(abs(get(hAxesScorePLSDA,'ZLim'))).*1.5 max(abs(get(hAxesScorePLSDA,'ZLim'))).*1.5]);
    % 
    %             % Determining the axis labels
    %             xlabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_X,'value')),1),'FontSize',10, 'FontWeight','bold');
    %             ylabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_Y,'value')),1),'FontSize',10, 'FontWeight','bold');
    %             zlabel(hAxesScorePLSDA,modelPLSDA.AxesXPlot((get(hScore_PLSDA_Model_Z,'value')),1),'FontSize',10, 'FontWeight','bold');
    %             line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
    %             line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');
    %             line([0 0],[0 0],[min(zlim) max(zlim)],'color',[1 0 0],'linestyle','--');
    %                                                     
    %             % Displaying the labels and legend for points
    %             GNATData.labelScore = text(modelPLSDA.scores{1,1}(:,(get(hScore_PLSDA_Model_X,'value')))*1.1,modelPLSDA.scores{1, 1}(:,(get(hScore_PLSDA_Model_Y,'value')))*1.1,modelPLSDA.scores{1, 1}(:,(get(hScore_PLSDA_Model_Z,'value')))*1.1, labels_s); 
    %             if ~isempty(Labels)
    %                GNATData.legendScore = legend(hAxesScorePLSDA,ab,'Location','northwest');
    %             else
    %                GNATData.legendScore = legend(hAxesScorePLSDA,ClassesValue,'Location','northwest');
    %             end 
    % 
    %         % 2D SCORE
    %         else 
            GUIData.AxesOPLSDA_c.h = gscatter(hAxesScoreOPLSDA,modelOPLSDA.PLSmodel.T(:,PCx),modelOPLSDA.OSCmodel.T_orth(:,1),Clss,Clr,S,6,'off'); 
            for n = 1:length(GUIData.AxesOPLSDA_c.h)
              set(GUIData.AxesOPLSDA_c.h(n,1), 'MarkerFaceColor', Clr(n));
            end 
            set(hAxesScoreOPLSDA, 'YLimMode', 'manual');
            set(hAxesScoreOPLSDA, 'YLimMode', 'manual'); 
            axis tight % optional

            % Defing the apperance
            set(GUIData.AxesOPLSDA_c.h,'LineWidth',1);
            set(hAxesScoreOPLSDA,'LineWidth',1);
            set(hAxesScoreOPLSDA,'Box','on');

            % Confidence limit based on Hotelling T2
            res_list = ellipseParam([modelOPLSDA.OSCmodel.T_orth modelOPLSDA.PLSmodel.T ], 2, PCx, PCy,3);
            if res_list.exit == 1
                return
            end
    
            % Plot the first ellipse 95%
            [~,xax,yax]=ellipse_GNAT(res_list.Ellipse{1,2}, res_list.Ellipse{1,1}, 0, 0, 0, 'r','--');

            % Plot the second ellipse 99%
            ellipse_GNAT(res_list.Ellipse{1,4}, res_list.Ellipse{1,3}, 0, 0, 0, 'b','--');  

            % Determining the ellipses for every class
            Error_elipse([modelOPLSDA.PLSmodel.T(:,PCx) modelOPLSDA.OSCmodel.T_orth],Clss,Clr) 
            drawnow % for some reason, axis 'tight' doesn't work. That's why I'm pausing here to load all the figure elements before continue

            % Painting black (Rolling stones) the area outside the elipse         
            axis (hAxesScoreOPLSDA,'tight'); 
            drawnow % for some reason, axis 'tight' doesn't work. That's why I'm pausing
            xl = xlim(gca); yl = ylim(gca);
            xlim([xl(1)*1.05 xl(2)*1.05])
            ylim([yl(1)*1.5 yl(2)*1.5])   
            xl = xlim(gca); yl = ylim(gca);
            x_frame=[xl(1),xl(2),xl(2),xl(1),xl(1)];
            y_frame=[yl(1),yl(1),yl(2),yl(2),yl(1)];    
            x = [x_frame, xax]; 
            y = [y_frame, yax];
            fill = patch(x,y, [0 0 0.25], 'EdgeColor', 'none');
            alpha(fill,0.06)
            axis tight % optional
    
            % Determining the axis labels
            xlabel(hAxesScoreOPLSDA,modelOPLSDA.AxesXPlot(PCx,1),'FontSize',10, 'FontWeight','bold');
            ylabel(hAxesScoreOPLSDA,'to1','FontSize',10, 'FontWeight','bold');
            line([min(xlim) max(xlim)],[0 0],'color',[1 0 0],'linestyle','--');
            line([0 0],[min(ylim) max(ylim)],'color',[1 0 0],'linestyle','--');             
    
            % Displaying the labels and legend for points
            GNATData.labelScore = text(modelOPLSDA.PLSmodel.T(:,PCx)*1.05,modelOPLSDA.OSCmodel.T_orth(:,1)*1.05,labels_s);
            if ~isempty(Labels)
               GNATData.legendScore = legend(hAxesScoreOPLSDA,ab,'Location','northwest');
            else
               GNATData.legendScore = legend(hAxesScoreOPLSDA,ClassesValue,'Location','northwest');
            end  
            
            title('OPLS-DA model', ['R2: ',num2str(modelOPLSDA.R2,'%.4f'),', Q2: ',num2str(modelOPLSDA.Q2,'%.4f')]); %modelPLSDA
            grid on
        end


        %% Loading plots % correct
        axes(hAxesLoadingOPLSDA)
        if isfield(GNATData,'BinPCA')
            GUIData.Axes.h_loadind=plot(hAxesLoadingOPLSDA,GNATData.BinPCA.number_of_variables,modelOPLSDA.PLSmodel.loadings{1,1}(:,(get(hScore_OPLSDA_Model_X,'value'))));
        else
            GUIData.Axes.h_loadind=plot(hAxesLoadingOPLSDA,GNATData.ppmscale(1,:),modelOPLSDA.PLSmodel.loadings{1,1}(:,(get(hScore_OPLSDA_Model_X,'value'))));
        end
        axis('tight');
        set(GUIData.Axes.h_loadind,'LineWidth',1);
        set(gca,'LineWidth',1);
        set(gca,'xdir','reverse');
        set(hAxesLoadingOPLSDA,'YLim',[-max(abs(get(gca,'YLim'))).*1.1 max(abs(get(gca,'YLim'))).*1.1]);
        xlabel(hAxesLoadingOPLSDA,'Chemical shift (ppm)','FontSize',10, 'FontWeight','bold');   
        row = dataTipTextRow("Variable",GNATData.ppmscale(1,:));
        GUIData.Axes.h_loadind.DataTipTemplate.DataTipRows(end+1) = row; 

        %% Permutation test
        %         permtest();        
        
        

        %% VIP Score Plots
        axes(hAxesVIPOPLSDA);
        cla(hAxesVIPOPLSDA)
       

        spectrum = mean(GNATData.xcal);
        if isfield(GNATData,'BinPCA')
            chemical_shifts = GNATData.BinPCA.number_of_variables;
        else
            chemical_shifts = GNATData.ppmscale(1,:);
        end

        % Normalize spectra and loadings for visualization
        TotVIP_normalised = modelOPLSDA.TotVip' / max(modelOPLSDA.TotVip) * max(spectrum'); % Scale VIP to match spectrum
        loadings_normalized = modelOPLSDA.PLSmodel.loadings{1,1}(:,(get(hScore_OPLSDA_Model_X,'value')))/  max(abs(modelOPLSDA.PLSmodel.loadings{1,1}(:,(get(hScore_OPLSDA_Model_X,'value'))))) * max(spectrum); % Scale loadings to match spectrum

        hold on
        set(gca,'Xdir','reverse');
        set(gca,'LineWidth',1);
        set(gca,'Box','on');

        % VIP scores
        hVIPOPLSDA = bar(chemical_shifts, TotVIP_normalised, 'FaceAlpha', 0.9, 'FaceColor', 'b', 'DisplayName', 'VIP Scores');

        % Add threshold line for VIP scores (Corrected for the magnitude )
        yline(1*10^floor(log10(abs(max(TotVIP_normalised)))), 'b--', 'LineWidth', 1.5, 'DisplayName', 'VIP Threshold');
    
        % Overlay NMR spectrum
        if get(hCheckSpecVIP,'value') == 1
            plot(chemical_shifts, spectrum, 'k', 'LineWidth', 1.5, 'DisplayName', 'NMR Spectrum');
        end

        % Overlay loadings
        if get(hCheckLoadingVIP,'value') == 1
            plot(chemical_shifts, loadings_normalized, 'r', 'LineWidth', 1.5, 'DisplayName', 'PLS Loadings');
        end
    
        % Formatting
        % Color
        % Set FaceColor to 'flat' for custom coloring
        hVIPOPLSDA.FaceColor = 'flat';

        % Initialize color array
        colors = repmat([0.5 0.5 0.5], length(modelOPLSDA.TotVip), 1); % Default to grey

        % Assign blue color to bars above the threshold
        colors(modelOPLSDA.TotVip > 1*5^floor(log10(abs(max(modelOPLSDA.TotVip)))), :) = repmat([0 0 1], sum(modelOPLSDA.TotVip > 1*5^floor(log10(abs(max(modelOPLSDA.TotVip))))), 1);

        % Apply the colors to the bars
        hVIPOPLSDA.CData = colors;

        % Axis
        xlabel('Chemical Shift (ppm)');
        ylabel('Intensity (a.u.)');
        title('NMR Spectrum, VIP Scores, and PLS Loadings');
        GNATData.legendOPLSVIP = legend();
        set(gca, 'XDir', 'reverse'); % Reverse x-axis for NMR convention
        hold off;


        %% Discrimination Plot
        optclss = get(hRunClasses_OPLSDA,'value');
        clss = size(unique(Classes),1);
        Clss = Classes(GNATData.objetos.treinamento);

        % Calculate optimal grid dimensions for subplots
        SizeClass = size(modelOPLSDA.PLSmodel.Yhat_cal,2);
        nRows = ceil(sqrt(SizeClass));
        nCols = ceil(SizeClass / nRows);

        % SizeClass = size(modelpred.preds,2);
        if Opt(1) == 1
            % Calibration plot
            if optclss > clss % 'all' option selected
                for ki=1:SizeClass                  
                    
                    subplot(nRows, nCols,ki,'Parent', hDiscriminationOPLSDA_Axes);                    
                    GUIData.AxesOPLSDA_c.h = gscatter(1:length(modelOPLSDA.PLSmodel.Yhat_cal),modelOPLSDA.PLSmodel.Yhat_cal(:,ki),Clss,Clr,S,6,'off'); 
                    for n = 1:length(GUIData.AxesOPLSDA_c.h)
                      set(GUIData.AxesOPLSDA_c.h(n,1), 'MarkerFaceColor', Clr(n));
                    end 
    
                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    grid on;hold on;

                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    hold on;

                    xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                    ylabel(sprintf('Class %g',ki),'FontSize',18,'FontName','Times New Woman')
                    
                    set(gca,'YLim',[-0.4 1.2])
                    line([0 (size(Clss,1))*1.02],[modelOPLSDA.threshold.class_thr(ki)   modelOPLSDA.threshold.class_thr(ki)],'color',[1 0 0],'linestyle','--');
                    xlim('tight');     
                    hold off
                    
                end
            else 
                % Recreating the main axis (hAxesDiscPLSDA) if it was deleted before by the subplot construction
                num_axis = get(hDiscriminationOPLSDA_Axes,'Children');
                if size(num_axis,1) > 1
                    delete(num_axis);
                    hAxesDiscOPLSDA = axes(...
                        'Parent',hDiscriminationOPLSDA_Axes,...
                        'Units','normalized',...
                        'Visible','off',...
                        'Box','off',...
                        'tag','axDisc',...
                        'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65
                end

                axes(hAxesDiscOPLSDA);                                
                GUIData.AxesOPLSDA_c.h = gscatter(1:length(modelOPLSDA.PLSmodel.Yhat_cal),modelOPLSDA.PLSmodel.Yhat_cal(:,optclss),Clss,Clr,S,6,'off'); 
                for n = 1:length(GUIData.AxesOPLSDA_c.h)
                    set(GUIData.AxesOPLSDA_c.h(n,1), 'MarkerFaceColor', Clr(n));
                end 

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                grid on;hold on;

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;

                xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Class %g',optclss),'FontSize',18,'FontName','Times New Woman')
                
                set(gca,'YLim',[-0.4 1.2])
                line([0 (size(Clss,1))*1.05],[modelOPLSDA.threshold.class_thr(optclss)   modelOPLSDA.threshold.class_thr(optclss)],'color',[1 0 0],'linestyle','--');
                xlim('tight')

                hold off
            end
        elseif Opt(2) == 1
           % Validation plot
           if optclss > clss % 'all' option selected
                for ki=1:SizeClass
                              
                    subplot(nRows, nCols,ki,'Parent', hDiscriminationOPLSDA_Axes);
    
                    Clss = Classes(GNATData.objetos.teste);
    
                    GUIData.AxesOPLSDA_v.h = gscatter(1:length(modelOPLSDA.Yhat_val),modelOPLSDA.Yhat_val(:,ki),Clss,Clr,S,6,'off');                
                    for n = 1:length(GUIData.AxesOPLSDA_v.h)
                      set(GUIData.AxesOPLSDA_v.h(n,1), 'MarkerFaceColor', Clr(n));
                    end 
    
                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    grid on;hold on;

                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    hold on;

                    xlabel('Sample','FontSize',18,'FontName','Times New Woman')
                    ylabel(sprintf('Classe %g',ki),'FontSize',18,'FontName','Times New Woman')
                    set(gca,'YLim',[-0.4 1.2])
                    line([0 (size(Clss,1))*1.02],[modelOPLSDA.threshold.class_thr(ki)   modelOPLSDA.threshold.class_thr(ki)],'color',[1 0 0],'linestyle','--');
                    xlim('tight')
                    hold off
                end
           else
                % Recreating the main axis (hAxesDiscPLSDA) if it was deleted before by the subplot construction
                num_axis = get(hDiscriminationOPLSDA_Axes,'Children');
                if size(num_axis,1) > 1
                    delete(num_axis);
                    hAxesDiscPLSDA = axes(...
                        'Parent',hDiscriminationOPLSDA_Axes,...
                        'Units','normalized',...
                        'Visible','off',...
                        'Box','off',...
                        'tag','axDisc',...
                        'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65
                end

                axes(hAxesDiscPLSDA);
                Clss = Classes(GNATData.objetos.teste);

                GUIData.AxesOPLSDA_v.h = gscatter(1:length(modelOPLSDA.Yhat_val),modelOPLSDA.Yhat_val(:,optclss),Clss,Clr,S,6,'off');                
                for n = 1:length(GUIData.AxesOPLSDA_v.h)
                  set(GUIData.AxesPLSDA_v.h(n,1), 'MarkerFaceColor', Clr(n));
                end 

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                grid on;hold on;

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;

                xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Classe %g',optclss),'FontSize',18,'FontName','Times New Woman')
                set(gca,'YLim',[-0.4 1.2])
                line([0 (size(Clss,1))*1.02],[modelOPLSDA.threshold.class_thr(optclss)   modelOPLSDA.threshold.class_thr(optclss)],'color',[1 0 0],'linestyle','--');
                xlim('tight')
                hold off
            end
        elseif Opt(3) == 1
           % Calibration & Validation plot
           if optclss > clss % 'all' option selected
                for ki=1:SizeClass
                         
                    subplot(nRows, nCols,ki,'Parent', hDiscriminationOPLSDA_Axes);
                    lngt =  size(modelOPLSDA.PLSmodel.Yhat_cal)+size(modelOPLSDA.Yhat_val);
    
                    ClssC = Classes(GNATData.objetos.treinamento);
                    ClssV = Classes(GNATData.objetos.teste);
                    Clss = [ClssC' ClssV'];
    
                    GUIData.AxesOPLSDA_cv.h = gscatter(1:lngt(1),[modelOPLSDA.PLSmodel.Yhat_cal(:,ki)' modelOPLSDA.Yhat_val(:,ki)'],Clss,Clr,S,6,'off');                 
                    for n = 1:length(GUIData.AxesOPLSDA_cv.h)
                        set(GUIData.AxesOPLSDA_cv.h(n,1), 'MarkerFaceColor', Clr(n));
                    end 
    
                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    grid on;hold on;

                    set(gcf,'Color','black')
                    set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                    set(gca,'xtickMode', 'auto');
                    hold on;

                    xlabel('Sample','FontSize',18,'FontName','Times New Woman')
                    ylabel(sprintf('Classe %g',ki),'FontSize',18,'FontName','Times New Woman')

%                 set(gca,'YLim',[-max(abs(get(gca,'YLim'))).*1.5 max(abs(get(gca,'YLim'))).*1.5]);
                    xlim('tight')

                    
                    line([0 (size(Clss',1))*1.02],[modelOPLSDA.threshold.class_thr(ki)   modelOPLSDA.threshold.class_thr(ki)],'color',[1 0 0],'linestyle','--');
                    line([size(ClssC,1)*1.02 size(ClssC,1)*1.02],[min(ylim)*1.1 max(ylim)*1.1],'color',[0 0 1],'linestyle','--'); 
                    ylim('tight')
                    hold off
                end
           else
                % Recreating the main axis (hAxesDiscPLSDA) if it was deleted before by the subplot construction
                num_axis = get(hDiscriminationOPLSDA_Axes,'Children');
                if size(num_axis,1) > 1
                    delete(num_axis);
                    hAxesDiscOPLSDA = axes(...
                        'Parent',hDiscriminationOPLSDA_Axes,...
                        'Units','normalized',...
                        'Visible','off',...
                        'Box','off',...
                        'tag','axDisc',...
                        'Position',[0.11 0.2 0.85 0.65]); %0.11 0.2 0.85 0.65
                end

                axes(hAxesDiscOPLSDA);
                lngt =  size(modelOPLSDA.PLSmodel.Yhat_cal)+size(modelOPLSDA.Yhat_val);

                ClssC = Classes(GNATData.objetos.treinamento);
                ClssV = Classes(GNATData.objetos.teste);
                Clss = [ClssC' ClssV'];

                GUIData.AxesOPLSDA_cv.h = gscatter(1:lngt(1),[modelOPLSDA.PLSmodel.Yhat_cal(:,optclss)' modelOPLSDA.Yhat_val(:,optclss)'],Clss,Clr,S,6,'off');                 
                for n = 1:length(GUIData.AxesOPLSDA_cv.h)
                  set(GUIData.AxesOPLSDA_cv.h(n,1), 'MarkerFaceColor', Clr(n));
                end 

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                grid on;hold on;

                set(gcf,'Color','black')
                set(gca,'xtick',[],'FontSize',14,'FontName','Times New Roman');
                set(gca,'xtickMode', 'auto');
                hold on;

                xlabel('Samples','FontSize',18,'FontName','Times New Woman')
                ylabel(sprintf('Classe %g',optclss),'FontSize',18,'FontName','Times New Woman')

%                 set(gca,'YLim',[-max(abs(get(gca,'YLim'))).*1.5 max(abs(get(gca,'YLim'))).*1.5]);
                xlim('tight')
                
                line([0 (size(Clss',1))*1.02],[modelOPLSDA.threshold.class_thr(optclss)   modelOPLSDA.threshold.class_thr(optclss)],'color',[1 0 0],'linestyle','--');
                line([size(ClssC,1)*1.02 size(ClssC,1)*1.02],[min(ylim)*1.1 max(ylim)*1.1],'color',[0 0 1],'linestyle','--'); 
                ylim('tight')
                hold off
           end
        end


        
        %% Roc curves Plot (Inspired by the classification toolbox - Create my own version in future releases)
        optclss = get(hRunClasses_OPLSDA,'value');
        clss = size(unique(Classes),1);

        [~,col_default] = visualize_colors;
        num_class = max(Classes);
        cnt = 0;
        delete(findobj(hTabROCOPLSDA , 'type', 'axes'));
        if optclss > clss % 'all' option selected
            for g=1:num_class
                % roc curve
                cnt = cnt + 1;
                GUIData.ROC.area = subplot(num_class,2,cnt,'Parent', hROCOPLSDA);
                TPR = modelOPLSDA.threshold.sn(:,g)';
                FPR = 1 - modelOPLSDA.threshold.sp(:,g)';
                area(FPR,TPR,'FaceColor',col_default(1,:));
                box on
                xlabel('1 - specificity')
                ylabel('sensitivity')
                % area under ROC curve
                FPRarea = [0 FPR 1 0];
                TPRarea = [0 TPR 0 0];
                AUC = polyarea(FPRarea,TPRarea);
                AUC = round(AUC*100,2)/100;
                title(['ROC curve - class ' num2str(g) ' (AUC: ' num2str(AUC) ')'])
                hold on
                plot([0 1],[0 1],'k--'); %
                hold off

                % specificity and sensitivity
                cnt = cnt + 1;
                GUIData.ROC.thr = subplot(num_class,2,cnt,'Parent', hROCOPLSDA);
                hold on
                plot(GUIData.ROC.thr,modelOPLSDA.threshold.thr_val(2:end-1,g),modelOPLSDA.threshold.sn(2:end-1,g)','b')
                plot(GUIData.ROC.thr,modelOPLSDA.threshold.thr_val(2:end-1,g),modelOPLSDA.threshold.sp(2:end-1,g)','r')
                hold off
                xlabel('threshold')
                ylabel('sn and sp ')
                title(['sensitivity (blue) and specificity (red) - class ' num2str(g)])
                xlim('tight')
                box on
            end
        else
           % roc curve
            GUIData.ROC.area = subplot(3,2,3,'Parent', hROCOPLSDA);
            TPR = modelOPLSDA.threshold.sn(:,optclss)';
            FPR = 1 - modelOPLSDA.threshold.sp(:,optclss)';
            area(FPR,TPR,'FaceColor',col_default(1,:));
            box on
            xlabel('1 - specificity')
            ylabel('sensitivity')
            % area under ROC curve
            FPRarea = [0 FPR 1 0];
            TPRarea = [0 TPR 0 0];
            AUC = polyarea(FPRarea,TPRarea);
            AUC = round(AUC*100,2)/100;
            title(['ROC curve - class ' num2str(optclss) ' (AUC: ' num2str(AUC) ')'])
            hold on
            plot([0 1],[0 1],'k--'); %
            hold off

            % specificity and sensitivity
            GUIData.ROC.thr = subplot(3,2,4,'Parent', hROCOPLSDA);
            subplot(GUIData.ROC.thr)
            hold on
            plot(GUIData.ROC.thr,modelOPLSDA.threshold.thr_val(2:end-1,optclss),modelOPLSDA.threshold.sn(2:end-1,optclss)','b')
            plot(GUIData.ROC.thr,modelOPLSDA.threshold.thr_val(2:end-1,optclss),modelOPLSDA.threshold.sp(2:end-1,optclss)','r')
            xlim('tight')
            hold off
            xlabel('threshold')
            ylabel('sn and sp ')
            title(['sensitivity (blue) and specificity (red) - class ' num2str(optclss)])
            box on             
        end
      

        %% Confusion matrix
        ConfusionMatrix()
        guidata(hPLOTfigure,GUIData);
        

        %% S-plot
        cutoff = 0.05; 
        % extract the desired score vector from the model.
        t = modelOPLSDA.PLSmodel.T(:, Factor);
        
        % extract the unscaled data matrix from the model.
        X = GNATData.xcal;
        
        % calculate the s-plot values.
        s1 = (t' * X) ./ (size(GNATData.xcal,1)- 1);
        s2 = s1 ./ (std(t) .* std(X));
        
        % initialize the figure.
%         figure();
%         hold on;
%         title(sprintf('S-plot: cov(%s, X) vs corr(%s, X)', 1, 2));
%         xlabel(sprintf('cov(%s, X)', 1));
%         ylabel(sprintf('corr(%s, X)', 2));
%         
%         % white out the score value points.
%         scatter(s1, s2, [], [1, 1, 1], '^');
%         
%         % loop through the loadings.
%         for k = 1 : length(s1)
%             % print the current variable index.
%             text(s1(k), s2(k), num2str(k), 'color', [0, 0, 0]);
%         end
%         
%         % release the figure for plotting.
%         hold off;
%         
%         % return the generated s-plot data
%         pdata = [[1 : length(s1)]; s1; s2]';

        guidata(hPLOTfigure,GUIData);
    end
    function ChangingScoreOPLS_Callback(source,eventdata)
        Tab = get(hTabGroupOPLSDA,'SelectedTab');
        % Turn on and off Visualization Panel for each Tab
        switch Tab
            case hTabScoreOPLSDA
                children = get(hCalValGroup_oplsda,'Children');
                set(children,'Enable','off');
            case hTabLoadingOPLSDA
                children = get(hCalValGroup_oplsda,'Children');
                set(children,'Enable','off');    
            case hTabVIPOPLSDA
                children = get(hCalValGroup_oplsda,'Children');
                set(children,'Enable','off');                
            case hTabAxesOPLSDA
                children = get(hCalValGroup_oplsda,'Children');
                set(children,'Enable','on');           
            case hTabROCOPLSDA
                children = get(hCalValGroup_oplsda,'Children');
                set(children,'Enable','on');     
            case hTabMeasureOPLSDA
                children = get(hCalValGroup_oplsda,'Children');
                set(children,'Enable','off');                 
        end
     end
%% ----------------- Export Panel
    function ExportInfo(eventdata, handles)
        GUIData = guidata(hPLOTfigure);

        if strcmp(method, 'PCA') 
            % Getting external info 
            opt.prepr{1} = get(hProcessing_PCA,'Value');            
            switch  opt.prepr{1}
                case 1
                    opt.prepr{1} = 'mean';
                case 2 
                    opt.prepr{1} = 'auto';
                case 3
                    opt.prepr{1} = 'pareto';
            end
        
            % Eigenvalue calculated
            export2 = [GNATData.parameters.Eigenvalue,GNATData.parameters.var_exp{1,1},GNATData.parameters.var_cum{1,1}];  

            % Outliers exclued

    
            defname = 'GNAT_PCA_Info.txt';
    
            [filename, pathname] = uiputfile('*.txt','Save analysis',defname);
            if isnumeric(filename) || isnumeric(pathname)
                if filename==0 || pathname==0
                    return
                end
            end
    
            % Data Path
            x=[pathname filename];  
    
            % Print out PCA data to file
            statfil=fopen(x, 'wt');
            fprintf(statfil,'%-s  \n',['Time domain data for: ' Export_Inf.filename]);
            fprintf(statfil,'%-s %s \n','Data type: ', Export_Inf.type);
            fprintf(statfil,'%-s %-f  \n','Spectrometer frequency (MHz): ', Export_Inf.sfrq);
            fprintf(statfil,'%-s %-d  \n','Number of complex points per FID: ', Export_Inf.np);
            fprintf(statfil,'%-s %-f  \n','Spectral width(ppm): ', Export_Inf.sw);
            fprintf(statfil,'%-s %.0f  \n','Numer of Samples: ', GNATData.parameters.samples);
            fprintf(statfil,'%-s %-d  \n','Number of variables used in calculation: ', GNATData.parameters.variables);
            fprintf(statfil,'%-s %s \n','Method: ', method);
            fprintf(statfil,'%-s \n','----------------------------------PCA----------------------------------');
            fprintf(statfil,'%-s %s \n','Pre-processing: ', opt.prepr{1});
            fprintf(statfil,'%-s %s \n','Binning:', Export_Inf.bin.Field);
            fprintf(statfil,'%-s %.3f \n','Bucket: ', Export_Inf.bin.Bucket);
            fprintf(statfil,'%-s %.1f \n','Slackness: ', Export_Inf.bin.Slackness);
            fprintf(statfil,'%-s %.0f \n','Number of Bin Variables: ', Export_Inf.bin.Variables);
            fprintf(statfil,'%-s %.0f \n','Outliers Excluded: ', GNATData.outlier);
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s\t %-s\t %-s\t \n','Eigenvalue: ','Variance (%): ','Cumulative Variance (%): ');
            fprintf(statfil,'%-s\t \n','=======================================================================');
            fprintf(statfil,'%2.2e\t\t\t %.2f\t\t\t %.2f\t\t\t\n',export2.');               
            fclose(statfil);

        elseif strcmp(method, 'PLSDA')
            % Getting external info 
            opt.prepr{1} = get(hProcessing_PLSDA_Model_s,'Value');            
            switch  opt.prepr{1}
                case 1
                    opt.prepr{1} = 'mean';
                case 2 
                    opt.prepr{1} = 'auto';
                case 3
                    opt.prepr{1} = 'pareto';
            end
        
            defname = 'GNAT_PLSDA_Data.txt';
    
            [filename, pathname] = uiputfile('*.txt','Save analysis',defname);
            if isnumeric(filename) || isnumeric(pathname)
                if filename==0 || pathname==0
                    return
                end
            end
    
            % Data Path
            x=[pathname filename];  
    
            % Print out PLSDA data to file
            statfil=fopen(x, 'wt');
            fprintf(statfil,'%-s  \n',['Time domain data for: ' Export_Inf.filename]);
            fprintf(statfil,'%-s %s \n','Data type: ', Export_Inf.type);
            fprintf(statfil,'%-s %-f  \n','Spectrometer frequency (MHz): ', Export_Inf.sfrq);
            fprintf(statfil,'%-s %-d  \n','Number of complex points per FID: ', Export_Inf.np);
            fprintf(statfil,'%-s %.2f  \n','Spectral width(ppm): ', Export_Inf.sw);
            fprintf(statfil,'%-s %.0f  \n','Numer of Samples: ', size(GNATData.Classes,1));
            fprintf(statfil,'%-s %-d  \n','Number of variables used in calculation: ', size(GNATData.ppmscale,2));
            fprintf(statfil,'%-s %s \n','Method: ', method);
            fprintf(statfil,'%-s \n','-----------------------------------------------------------------------');
            fprintf(statfil,'%-s %s \n','Pre-processing:', opt.prepr{1});
            fprintf(statfil,'%-s %s \n','Pre-processing: Binning', Export_Inf.bin.Field);
            fprintf(statfil,'%-s %.3f  \n','Bucket: ', Export_Inf.bin.Bucket);
            fprintf(statfil,'%-s %.3f  \n','Slackness: ', Export_Inf.bin.Slackness);
            fprintf(statfil,'%-s %.0f  \n','Number of Variables: ', Export_Inf.bin.Variables);
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s \n','Training model');
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s %.3f \n','R2: ', GUIData.modelPLSDA.R2);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Precision: ', GUIData.modelPLSDA.class_param.precision);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Sensitivity: ', GUIData.modelPLSDA.class_param.sensitivity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Specificity: ', GUIData.modelPLSDA.class_param.specificity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Correct Classification Rate: ', GUIData.modelPLSDA.classification.CorrClassRate);
            fprintf(statfil,'%-s %.3f \n','Total Correct Classification Rate: ', GUIData.modelPLSDA.classification.CorrClassTot);
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s \n','Testing model');
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s %.3f \n','R2: ', GUIData.modelpred.R2);
            fprintf(statfil,'%-s %.3f \n','R2: ', GUIData.modelpred.Q2);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Precision: ', GUIData.modelpred.class_param.precision);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Sensitivity: ', GUIData.modelpred.class_param.sensitivity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Specificity: ', GUIData.modelpred.class_param.specificity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Correct Classification Rate: ', GUIData.modelpred.classification.CorrClassRate);
            fprintf(statfil,'%-s %.3f \n','Total Correct Classification Rate: ', GUIData.modelpred.classification.CorrClassTot);
            fclose(statfil);
        elseif strcmp(method, 'OPLSDA')
            % Getting external info 
            opt.prepr{1} = get(hProcessing_OPLSDA_Model_s,'Value');            
            switch  opt.prepr{1}
                case 1
                    opt.prepr{1} = 'mean';
                case 2 
                    opt.prepr{1} = 'auto';
                case 3
                    opt.prepr{1} = 'pareto';
            end

            defname = 'GNAT_OPLSDA_Data.txt';
    
            [filename, pathname] = uiputfile('*.txt','Save analysis',defname);
            if isnumeric(filename) || isnumeric(pathname)
                if filename==0 || pathname==0
                    return
                end
            end
    
            % Data Path
            x=[pathname filename];  
    
            % Print out PCA data to file
            statfil=fopen(x, 'wt');
            fprintf(statfil,'%-s  \n',['Time domain data for: ' Export_Inf.filename]);
            fprintf(statfil,'%-s %s \n','Data type: ', Export_Inf.type);
            fprintf(statfil,'%-s %-f  \n','Spectrometer frequency (MHz): ', Export_Inf.sfrq);
            fprintf(statfil,'%-s %-d  \n','Number of complex points per FID: ', Export_Inf.np);
            fprintf(statfil,'%-s %-f  \n','Spectral width(ppm): ', Export_Inf.sw);
            fprintf(statfil,'%-s %.0f  \n','Numer of Samples: ', size(GNATData.Classes,1));
            fprintf(statfil,'%-s %-d  \n','Number of variables used in calculation: ', size(GNATData.ppmscale,2));
            fprintf(statfil,'%-s %s \n','Method: ', method);
            fprintf(statfil,'%-s \n','-----------------------------------------------------------------------');
            fprintf(statfil,'%-s %s \n','Pre-processing:', opt.prepr{1});
            fprintf(statfil,'%-s %s \n','Pre-processing: Binning', Export_Inf.bin.Field);
            fprintf(statfil,'%-s %.3f  \n','Bucket: ', Export_Inf.bin.Bucket);
            fprintf(statfil,'%-s %.3f  \n','Slackness: ', Export_Inf.bin.Slackness);
            fprintf(statfil,'%-s %.0f  \n','Number of Variables: ', Export_Inf.bin.Variables);
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s \n','Training model');
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s %.3f \n','R2: ', GUIData.modelOPLSDA.R2);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Precision: ', GUIData.modelOPLSDA.class_param.precision);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Sensitivity: ', GUIData.modelOPLSDA.class_param.sensitivity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Specificity: ', GUIData.modelOPLSDA.class_param.specificity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Correct Classification Rate: ', GUIData.modelOPLSDA.classification.CorrClassRate);
            fprintf(statfil,'%-s %.3f \n','Total Correct Classification Rate: ', GUIData.modelOPLSDA.classification.CorrClassTot);
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s \n','Testing model');
            fprintf(statfil,'%-s \n','=======================================================================');
            fprintf(statfil,'%-s %.3f \n','R2: ', GUIData.modelpred.R2);
            fprintf(statfil,'%-s %.3f \n','R2: ', GUIData.modelpred.Q2);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Precision: ', GUIData.modelpred.class_param.precision);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Sensitivity: ', GUIData.modelpred.class_param.sensitivity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Specificity: ', GUIData.modelpred.class_param.specificity);
            fprintf(statfil,'%-s %.3f %.3f %.3f \n','Correct Classification Rate: ', GUIData.modelpred.classification.CorrClassRate);
            fprintf(statfil,'%-s %.3f \n','Total Correct Classification Rate: ', GUIData.modelpred.classification.CorrClassTot);
            fclose(statfil);
        end
        guidata(hPLOTfigure,GUIData);
    end 
    function ExportData(eventdata, handles)
        GUIData = guidata(hPLOTfigure);
        if strcmp(method, 'PCA') 
            list = {'Raw dataset';'Processed dataset';'Loadings';'Scores'};
            % Check files from Binning
            if isfield(GNATData, 'BinPCA')
                list(end+1) = {'Bin limits'};
            end
            [indx,tf] = listdlg('PromptString',{'Select a file'},'ListString',list);
            if tf == 0
                return
            end
            if size(GNATData.ppmscale) ~= size(GNATData.parameters.mean_matrix) % Bin was calculated 
                data = {[GNATData.ppmscale' GNATData.raw_matrix'];[GNATData.BinPCA.intervals(:,1) GNATData.BinPCA.normalized_buckets'];...
                         GNATData.parameters.Loadings;GNATData.parameters.Scores};  
            else
                data = {[GNATData.ppmscale' GNATData.raw_matrix'];[GNATData.ppmscale' GNATData.parameters.mean_matrix'];...
                         GNATData.parameters.Loadings;GNATData.parameters.Scores};  
            end
            defname = 'GNAT_PCA_Data.txt';
        elseif strcmp(method, 'PLSDA')
            list = {'Raw dataset';'Processed dataset';'Loadings';'Scores';'Regression Coeficient';'True classes';'Predicted classes'};
            [indx,tf] = listdlg('PromptString',{'Select a file'},'ListString',list);
            if tf == 0
                return
            end
            if size(GNATData.ppmscale) ~= size(GNATData.parameters.mean_matrix) % Bin was calculated 
                data = {[GNATData.ppmscale' GUIData.modelPLSDA.raw_matrix'];[GNATData.BinPCA.intervals(:,1) GNATData.parameters.mean_matrix'];...
                        GUIData.modelPLSDA.loadings{1,1}; GUIData.modelPLSDA.scores{1,1}; GUIData.modelPLSDA.regcoef;...
                        GUIData.modelPLSDA.classes; GUIData.modelPLSDA.preds}; 
            else
                data = {[GNATData.ppmscale' GUIData.modelPLSDA.raw_matrix'];[GNATData.ppmscale' GUIData.modelPLSDA.mean_matrix'];...
                        GUIData.modelPLSDA.loadings{1,1}; GUIData.modelPLSDA.scores{1,1}; GUIData.modelPLSDA.regcoef;...
                        GUIData.modelPLSDA.classes; GUIData.modelPLSDA.preds}; 
            end
            defname = 'GNAT_PLSDA_Data.txt';
        elseif strcmp(method, 'OPLSDA')
            list = {'Raw dataset';'Processed dataset';'Loadings';'Scores'};
            [indx,tf] = listdlg('PromptString',{'Select a file'},'ListString',list);
            if tf == 0
                return
            end
            data = {[GNATData.ppmscale' GNATData.raw_matrix'];[GNATData.ppmscale' GNATData.parameters.mean_matrix'];...
                GNATData.parameters.Loadings;GNATData.parameters.Scores}; 
            
            defname = 'GNAT_OPLSDA_Data.txt';
        end

        [filename, pathname, idx] = uiputfile({'*.txt';'*.xlsx'},'Save analysis',defname);
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end 

        % Data Path
        x=[pathname filename];    
        line = '=======================================================================';
        
        % Print out PCA data to file        
        switch  idx
            case 1 
                statfil=fopen(x, 'wt');
                list_str = string(list);
                try % Special case for bin limits
                    limits = ExportBinBruker(GNATData.BinPCA.intervals,idx);
                    fprintf(statfil,[repmat('%-s\t', 1, size(limits, 2)) '\n'], limits');
                catch ME
                    % do nothing
                end
                
                if find(indx==5)>0
                    indx(indx==5) = [];
                    for i=1:size(indx,2)
                        temp = cell2mat(data(indx(i)));
                        fprintf(statfil,'%-s \n',line);
                        fprintf(statfil,'%-s\t \n',list_str(indx(i),:));
                        fprintf(statfil,'%-s \n',line);
                        fprintf(statfil,[repmat('%2.2f\t', 1, size(temp, 2)) '\n'], temp');
                        fprintf(statfil,'%-s \n',line);
                    end   
                else
                    for i=1:size(indx,2)
                        temp = cell2mat(data(indx(i)));
                        fprintf(statfil,'%-s \n',line);
                        fprintf(statfil,'%-s\t \n',list_str(indx(i),:));
                        fprintf(statfil,'%-s \n',line);
                        fprintf(statfil,[repmat('%2.2f\t', 1, size(temp, 2)) '\n'], temp');
                    end  
                end
                fclose(statfil);
            case 2
                h=waitbar(0,'Writing the data to the Excel file');
                list_str = string(list);
                try % Special case for bin limits
                    limits = ExportBinBruker(GNATData.BinPCA.intervals,idx);
                    limits = table(limits);
                catch ME
                    % do nothing
                end
                if find(indx==5)>0
                    indx(indx==5) = [];
                    for i=1:size(indx,2)
                        h=waitbar(i/size(indx,2));
                        temp = table(cell2mat(data(indx(i))));
                        writetable(temp,x,'Sheet',list_str(indx(i),:),"WriteVariableNames",false);
                    end
                    writetable(limits,x,'Sheet',list_str(5,:),"WriteVariableNames",false);
                else
                    for i=1:size(indx,2)
                        h=waitbar(i/size(indx,2));
                        temp = table(cell2mat(data(indx(i))));
                        writetable(temp,x,'Sheet',list_str(indx(i),:),"WriteVariableNames",false);
                    end
                end
                close(h)
        end
        guidata(hPLOTfigure,GUIData);
    end 


    function ExportFigure (eventdata, handles)
        GUIData = guidata(hPLOTfigure);
        if strcmp(method, 'PCA') 
            if strcmp(get(Axes,'Visible'),'on')
                Fig1 = figure(...
                    'Units','normalized',...
                    'Name',GUIData.version,... 
                    'NumberTitle','Off',...
                    'Toolbar','Figure',...
                    'OuterPosition',[0.0 0.0 0.4 0.6],...
                    'Color','w',...
                    'Visible','off');
                %Clean up the Menu, removing things we don't need
                allhandles = findall(Fig1);
                menuhandles = findobj(allhandles,'type','uimenu');
                edithandle = findobj(menuhandles,'tag','figMenuEdit');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuView');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuHelp');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuOpen');set(edithandle,'Visible','off');           
                edithandle = findobj(menuhandles,'tag','figMenuWindow');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuDesktop');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSave');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileClose');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSaveAs');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuGenerateCode');set(edithandle,'Visible','off');    
                edithandle = findobj(menuhandles,'tag','figMenuUpdateFileNew');set(edithandle,'Visible','off');            
                edithandle = findobj(menuhandles,'tag','figMenuFileImportData');set(edithandle,'Visible','off');           
                edithandle = findobj(menuhandles,'tag','figMenuFilePrintPreview');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSaveWorkspaceAs');set(edithandle,'Visible','off');
                
                %Clean up the Toolbar, removing things we don't need
                tmp = findall(Fig1,'ToolTipString','Open File');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Link Plot');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Rotate 3D');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','New Figure');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Save Figure');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Data Cursor');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Print Figure');set(tmp,'Visible','Off')            
                tmp = findall(Fig1,'ToolTipString','Insert Legend');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Hide Plot Tools');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Insert Colorbar');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Brush/Select Data');set(tmp,'Visible','Off')
                tmp = findall(Fig1,'ToolTipString','Show Plot Tools and Dock Figure');set(tmp,'Visible','Off')
    
                % Organize figures 
                movegui(Fig1,'center')
                axch = copyobj(Axes,hPLOTfigure);
                set(axch,'Position',[0.12 0.12 .8 .86]);
    
                % Coping elements to Export
                copyobj(axch,Fig1);
    
                XL = get(gca,'XLabel');
                xlabel(gca,XL.String, 'FontWeight','bold');
                YL = get(gca,'YLabel');
                ylabel(gca,YL.String, 'FontWeight','bold');
                ZL = get(gca,'ZLabel');
                zlabel(gca,ZL.String, 'FontWeight','bold');

                if get(hCheckLegend,'value') == 1
                    legend(gca, GNATData.legendScore.String,'Location','northwest');
                end
                
                set(Fig1,'Visible','on');     
    
            elseif strcmp(get(Axes21,'Visible'),'on') && strcmp(get(Axes22,'Visible'),'on')
                Fig2 = figure(...
                    'Units','normalized',...
                    'Name',GUIData.version,...
                    'NumberTitle','Off',...
                    'Toolbar','Figure',...
                    'OuterPosition',[0.0 0.0 0.42 0.8],...
                    'Color','w',...
                    'Visible','off');
                %Clean up the Menu, removing things we don't need
                allhandles = findall(Fig2);
                menuhandles = findobj(allhandles,'type','uimenu');
                edithandle = findobj(menuhandles,'tag','figMenuEdit');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuView');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuHelp');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuOpen');set(edithandle,'Visible','off');           
                edithandle = findobj(menuhandles,'tag','figMenuWindow');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuDesktop');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSave');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileClose');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSaveAs');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuGenerateCode');set(edithandle,'Visible','off');    
                edithandle = findobj(menuhandles,'tag','figMenuUpdateFileNew');set(edithandle,'Visible','off');            
                edithandle = findobj(menuhandles,'tag','figMenuFileImportData');set(edithandle,'Visible','off');           
                edithandle = findobj(menuhandles,'tag','figMenuFilePrintPreview');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSaveWorkspaceAs');set(edithandle,'Visible','off');
                
                %Clean up the Toolbar, removing things we don't need
                tmp = findall(Fig2,'ToolTipString','Open File');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Link Plot');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Rotate 3D');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','New Figure');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Save Figure');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Data Cursor');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Print Figure');set(tmp,'Visible','Off')            
                tmp = findall(Fig2,'ToolTipString','Insert Legend');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Hide Plot Tools');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Insert Colorbar');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Brush/Select Data');set(tmp,'Visible','Off')
                tmp = findall(Fig2,'ToolTipString','Show Plot Tools and Dock Figure');set(tmp,'Visible','Off')
    
                movegui(Fig2,'center')
                ax21 = copyobj(Axes21,hPLOTfigure);
                ax22 = copyobj(Axes22,hPLOTfigure);
                set(ax21,'Position',[0.12 0.59 .8 .4]);
                set(ax22,'Position',[0.12 0.085 .8 .4]);
    
                % Adjusting copied elements
                copyobj(ax21,Fig2);
                XL = get(Fig2.Children(1),'XLabel');
                xlabel(Fig2.Children(1),XL.String, 'FontWeight','bold');
                YL = get(Fig2.Children(1),'YLabel');
                ylabel(Fig2.Children(1),YL.String, 'FontWeight','bold');
                ZL = get(Fig2.Children(1),'ZLabel');
                zlabel(Fig2.Children(1),ZL.String, 'FontWeight','bold');
    
                copyobj(ax22,Fig2);   
                XL = get(Fig2.Children(1),'XLabel');
                xlabel(Fig2.Children(1),XL.String, 'FontWeight','bold');
                YL = get(Fig2.Children(1),'YLabel');
                ylabel(Fig2.Children(1),YL.String, 'FontWeight','bold');
                ZL = get(Fig2.Children(1),'ZLabel');
                zlabel(Fig2.Children(1),ZL.String, 'FontWeight','bold');
    
                % Check the label order
                if get(hCheckLegend,'value') == 1
                    Opt=GNATData.PlotOpt; 
                    if Opt (1) == 1
                        legend(Fig2.Children(2),GNATData.ClassesValue);
                        if Opt (2) == 1
                            % Loading plot
                        elseif Opt (3) == 1  
                            legend(Fig2.Children(1),GNATData.ClassesValue);
                        end
                    elseif Opt (1) == 0
                        legend(Fig2.Children(1),GNATData.ClassesValue);
                    end
                end
                            
                set(Fig2,'Visible','on');
            elseif strcmp(get(Axes31,'Visible'),'on') && strcmp(get(Axes32,'Visible'),'on') && strcmp(get(Axes33,'Visible'),'on')
                Fig3 = figure(...
                    'Units','normalized',...
                    'Name',GUIData.version,... 
                    'NumberTitle','Off',...
                    'Toolbar','figure',...
                    'OuterPosition',[0.0 0.0 0.42 0.8],...
                    'Color','w',...
                    'Visible','off');
                %Clean up the Menu, removing things we don't need
                allhandles = findall(Fig3);
                menuhandles = findobj(allhandles,'type','uimenu');
                edithandle = findobj(menuhandles,'tag','figMenuEdit');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuView');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuHelp');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuOpen');set(edithandle,'Visible','off');           
                edithandle = findobj(menuhandles,'tag','figMenuWindow');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuDesktop');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSave');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileClose');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSaveAs');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuGenerateCode');set(edithandle,'Visible','off');    
                edithandle = findobj(menuhandles,'tag','figMenuUpdateFileNew');set(edithandle,'Visible','off');            
                edithandle = findobj(menuhandles,'tag','figMenuFileImportData');set(edithandle,'Visible','off');           
                edithandle = findobj(menuhandles,'tag','figMenuFilePrintPreview');set(edithandle,'Visible','off');
                edithandle = findobj(menuhandles,'tag','figMenuFileSaveWorkspaceAs');set(edithandle,'Visible','off');
                
                %Clean up the Toolbar, removing things we don't need
                tmp = findall(Fig3,'ToolTipString','Open File');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Link Plot');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Rotate 3D');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','New Figure');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Save Figure');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Data Cursor');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Print Figure');set(tmp,'Visible','Off')            
                tmp = findall(Fig3,'ToolTipString','Insert Legend');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Hide Plot Tools');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Insert Colorbar');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Brush/Select Data');set(tmp,'Visible','Off')
                tmp = findall(Fig3,'ToolTipString','Show Plot Tools and Dock Figure');set(tmp,'Visible','Off')
    
                % Organize figures 
                movegui(Fig3,'center')
                ax31 = copyobj(Axes31,hPLOTfigure);
                ax32 = copyobj(Axes32,hPLOTfigure);
                ax33 = copyobj(Axes33,hPLOTfigure);
                set(ax31,'Position',[0.11 0.73 0.85 0.23]);
                set(ax32,'Position',[0.11 0.41 0.85 0.23]);
                set(ax33,'Position',[0.11 0.08 0.85 0.23]);
    
                % Adjusting copied elements
                copyobj(ax31,Fig3);
                XL = get(Fig3.Children(1),'XLabel');
                xlabel(Fig3.Children(1),XL.String, 'FontWeight','bold');
                YL = get(Fig3.Children(1),'YLabel');
                ylabel(Fig3.Children(1),YL.String, 'FontWeight','bold');
                ZL = get(Fig3.Children(1),'ZLabel');
                zlabel(Fig3.Children(1),ZL.String, 'FontWeight','bold');
    
                copyobj(ax32,Fig3);   
                XL = get(Fig3.Children(1),'XLabel');
                xlabel(Fig3.Children(1),XL.String, 'FontWeight','bold');
                YL = get(Fig3.Children(1),'YLabel');
                ylabel(Fig3.Children(1),YL.String, 'FontWeight','bold');
                ZL = get(Fig3.Children(1),'ZLabel');
                zlabel(Fig3.Children(1),ZL.String, 'FontWeight','bold');
    
                copyobj(ax33,Fig3);   
                XL = get(Fig3.Children(1),'XLabel');
                xlabel(Fig3.Children(1),XL.String, 'FontWeight','bold');
                YL = get(Fig3.Children(1),'YLabel');
                ylabel(Fig3.Children(1),YL.String, 'FontWeight','bold');
                ZL = get(Fig3.Children(1),'ZLabel');
                zlabel(Fig3.Children(1),ZL.String, 'FontWeight','bold');
    
                % Check the label order
                if get(hCheckLegend,'value') == 1
                    legend(Fig3.Children(3),GNATData.ClassesValue);
                    legend(Fig3.Children(1),GNATData.ClassesValue);
                end
    
                set(Fig3,'Visible','on'); 
            end     
        elseif strcmp(method, 'PLSDA')
            Tab = get(hTabGroup,'SelectedTab');
            % Choosing the figures for each Tab
            switch Tab
                case hTabModelPLSDA
                    Tab2 = get(hTabGroupPLSDA,'SelectedTab');
                    % Choosing the figures for each Tab
                    switch Tab2
                        case hTabScorePLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hAxesScorePLSDA,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.7 .76]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            XL = get(gca,'XLabel');
                            xlabel(gca,XL.String, 'FontWeight','bold');
                            YL = get(gca,'YLabel');
                            ylabel(gca,YL.String, 'FontWeight','bold');
                            ZL = get(gca,'ZLabel');
                            zlabel(gca,ZL.String, 'FontWeight','bold');
        
                            if get(hCheckLegend,'value') == 1
                                legend(gca, GNATData.legendScore.String,'Location','northwest');
                            end
        
                            set(Fig1,'Visible','on');
                        case hTabLoadingPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hAxesLoadingPLSDA,hPLOTfigure);
                            set(axch,'Position',[0.12 0.12 .8 .86]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            XL = get(gca,'XLabel');
                            xlabel(gca,XL.String, 'FontWeight','bold');
                            YL = get(gca,'YLabel');
                            ylabel(gca,YL.String, 'FontWeight','bold');
                            ZL = get(gca,'ZLabel');
                            zlabel(gca,ZL.String, 'FontWeight','bold');
        
                            set(Fig1,'Visible','on');
        
                        case hTabVIPPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hAxesVIPPLSDA,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.7 .76]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            XL = get(gca,'XLabel');
                            xlabel(gca,XL.String, 'FontWeight','bold');
                            YL = get(gca,'YLabel');
                            ylabel(gca,YL.String, 'FontWeight','bold');
                            ZL = get(gca,'ZLabel');
                            zlabel(gca,ZL.String, 'FontWeight','bold');
        
                            set(Fig1,'Visible','on');
        
                            if get(hCheckLegend,'value') == 1
                                legend(gca, GNATData.legendPLSVIP.String,'Location','northwest');
                            end
        
                            set(Fig1,'Visible','on');
                        case hTabAxesPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Checking tipe of plot
                            optclss = get(hRunClasses_PLSDA,'value');
                            clss = size(unique(Classes),1);
        
                            if optclss > clss % 'all' option selected
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hDiscriminationPLSDA_Axes.Children,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);    
                                for ki=1:size(hDiscriminationPLSDA_Axes.Children,1)
                                    % Coping elements to Export
                                    ax(ki) = copyobj(axch(ki),Fig1);   
                                    set(ax(ki),'position',hDiscriminationPLSDA_Axes.Children(ki).Position);
                                end
            
                                set(Fig1,'Visible','on');                        
                            else
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hAxesDiscPLSDA,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);
            
                                % Coping elements to Export
                                copyobj(axch,Fig1);
                                set(Fig1,'Visible','on');
                            end
        
                            
        
                        case hTabPermutPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hAxesPermPLSDA,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.7 .76]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            if get(hCheckLegend,'value') == 1
                                legend(gca, GNATData.LegendPerm.String,'Location','northwest');
                            end
        
                            set(Fig1,'Visible','on');
                        case hTabROCPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Checking tipe of plot
                            optclss = get(hRunClasses_PLSDA,'value');
                            clss = size(unique(Classes),1);
        
                            if optclss > clss % 'all' option selected
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hROCPLSDA.Children,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);    
                                for ki=1:size(hROCPLSDA.Children,1)
                                    % Coping elements to Export
                                    ax(ki) = copyobj(axch(ki),Fig1);   
                                    set(ax(ki),'position',hROCPLSDA.Children(ki).Position);
                                end
            
                                set(Fig1,'Visible','on');                        
                            else
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hROCPLSDA.Children,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);    
                                for ki=1:size(hROCPLSDA.Children,1)
                                    % Coping elements to Export
                                    ax(ki) = copyobj(axch(ki),Fig1);   
                                    set(ax(ki),'position',hROCPLSDA.Children(ki).Position);
                                end
            
                                set(Fig1,'Visible','on');
                            end
                        case hTabConfMatPLSDA
                    end
                case hTabCrossValidation                    
                    % Creating figure
                    Fig1 = figureExport(GUIData);

                    % Organize figures
                    movegui(Fig1,'center')
                    axch = copyobj(AxesRMSECV,hPLOTfigure);
                    set(axch,'Position',[0.15 0.12 0.7 .76]);

                    % Coping elements to Export
                    copyobj(axch,Fig1);

                    set(Fig1,'Visible','on');

                case hTab_iPLS_PLSDA
                    Tab = get(hTabGroupiPLS_PLSDA,'SelectedTab');
                    % Choosing the figures for each Tab
                    switch Tab
                        case hTabResiduals_Intervals_iPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(AxesiPLS_residual,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.75 .81]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            set(Fig1,'Visible','on');

                        case hResiduals_iPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);

                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hResiduals_iPLS.Children,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.70 .74]);    
                            for ki=1:size(hResiduals_iPLS.Children,1)
                                % Coping elements to Export
                                ax(ki) = copyobj(axch(ki),Fig1);   
                                set(ax(ki),'position',hResiduals_iPLS.Children(ki).Position);
                            end
        
                            set(Fig1,'Visible','on'); 
                    end
                case hTab_biPLS_PLSDA
                    Tab = get(hTabGroupbiPLS_PLSDA,'SelectedTab');
                    % Choosing the figures for each Tab
                    switch Tab
                        case hTabResiduals_Intervals_biPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(AxesbiPLS_RMSE,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.75 .81]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            set(Fig1,'Visible','on');

                        case hTabdMeasure_biPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);

                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hTabPredMeasure_biPLS.Children,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.70 .74]);    
                            for ki=1:size(hResiduals_iPLS.Children,1)
                                % Coping elements to Export
                                ax(ki) = copyobj(axch(ki),Fig1);   
                                set(ax(ki),'position',hResiduals_iPLS.Children(ki).Position);
                            end
        
                            set(Fig1,'Visible','on'); 
                    end
            end

        elseif strcmp(method, 'OPLSDA')
            Tab = get(hTabGroup,'SelectedTab');
            % Choosing the figures for each Tab
            switch Tab
                case hTabModelOPLSDA
                    Tab2 = get(hTabGroupOPLSDA,'SelectedTab');
                    % Choosing the figures for each Tab
                    switch Tab2
                        case hTabScoreOPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hAxesScoreOPLSDA,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.7 .76]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            XL = get(gca,'XLabel');
                            xlabel(gca,XL.String, 'FontWeight','bold');
                            YL = get(gca,'YLabel');
                            ylabel(gca,YL.String, 'FontWeight','bold');
                            ZL = get(gca,'ZLabel');
                            zlabel(gca,ZL.String, 'FontWeight','bold');
        
                            if get(hCheckLegend,'value') == 1
                                legend(gca, GNATData.legendScore.String,'Location','northwest');
                            end
        
                            set(Fig1,'Visible','on');
                        case hTabLoadingOPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hAxesLoadingOPLSDA,hPLOTfigure);
                            set(axch,'Position',[0.12 0.12 .8 .86]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            XL = get(gca,'XLabel');
                            xlabel(gca,XL.String, 'FontWeight','bold');
                            YL = get(gca,'YLabel');
                            ylabel(gca,YL.String, 'FontWeight','bold');
                            ZL = get(gca,'ZLabel');
                            zlabel(gca,ZL.String, 'FontWeight','bold');
        
                            set(Fig1,'Visible','on');
        
                        case hTabVIPOPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hAxesVIPOPLSDA,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.7 .76]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            XL = get(gca,'XLabel');
                            xlabel(gca,XL.String, 'FontWeight','bold');
                            YL = get(gca,'YLabel');
                            ylabel(gca,YL.String, 'FontWeight','bold');
                            ZL = get(gca,'ZLabel');
                            zlabel(gca,ZL.String, 'FontWeight','bold');
        
                            set(Fig1,'Visible','on');
        
                            if get(hCheckLegend,'value') == 1
                                legend(gca, GNATData.legendOPLSVIP.String,'Location','northwest');
                            end
        
                            set(Fig1,'Visible','on');
                        case hTabAxesOPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Checking tipe of plot
                            optclss = get(hRunClasses_OPLSDA,'value');
                            clss = size(unique(Classes),1);
        
                            if optclss > clss % 'all' option selected
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hDiscriminationOPLSDA_Axes.Children,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);    
                                for ki=1:size(hDiscriminationOPLSDA_Axes.Children,1)
                                    % Coping elements to Export
                                    ax(ki) = copyobj(axch(ki),Fig1);   
                                    set(ax(ki),'position',hDiscriminationOPLSDA_Axes.Children(ki).Position);
                                end
            
                                set(Fig1,'Visible','on');                        
                            else
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hAxesDiscOPLSDA,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);
            
                                % Coping elements to Export
                                copyobj(axch,Fig1);
                                set(Fig1,'Visible','on');
                            end
        
                            
        
                        case hTabROCOPLSDA
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Checking tipe of plot
                            optclss = get(hRunClasses_OPLSDA,'value');
                            clss = size(unique(Classes),1);
        
                            if optclss > clss % 'all' option selected
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hROCOPLSDA.Children,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);    
                                for ki=1:size(hROCOPLSDA.Children,1)
                                    % Coping elements to Export
                                    ax(ki) = copyobj(axch(ki),Fig1);   
                                    set(ax(ki),'position',hROCOPLSDA.Children(ki).Position);
                                end
            
                                set(Fig1,'Visible','on');                        
                            else
                                % Organize figures
                                movegui(Fig1,'center')
                                axch = copyobj(hROCOPLSDA.Children,hPLOTfigure);
                                set(axch,'Position',[0.12 0.12 .8 .86]);    
                                for ki=1:size(hROCOPLSDA.Children,1)
                                    % Coping elements to Export
                                    ax(ki) = copyobj(axch(ki),Fig1);   
                                    set(ax(ki),'position',hROCOPLSDA.Children(ki).Position);
                                end
            
                                set(Fig1,'Visible','on');
                            end
                        
                    end
                case hTabCrossValidation_oplsda                    
                    % Creating figure
                    Fig1 = figureExport(GUIData);

                    % Organize figures
                    movegui(Fig1,'center')
                    axch = copyobj(AxesRMSECVOPLSDA,hPLOTfigure);
                    set(axch,'Position',[0.15 0.12 0.7 .76]);

                    % Coping elements to Export
                    copyobj(axch,Fig1);

                    set(Fig1,'Visible','on');

                case hTab_iPLS_PLSDA
                    Tab = get(hTabGroupiPLS_PLSDA,'SelectedTab');
                    % Choosing the figures for each Tab
                    switch Tab
                        case hTabResiduals_Intervals_iPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(AxesiPLS_residual,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.75 .81]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            set(Fig1,'Visible','on');

                        case hResiduals_iPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);

                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hResiduals_iPLS.Children,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.70 .74]);    
                            for ki=1:size(hResiduals_iPLS.Children,1)
                                % Coping elements to Export
                                ax(ki) = copyobj(axch(ki),Fig1);   
                                set(ax(ki),'position',hResiduals_iPLS.Children(ki).Position);
                            end
        
                            set(Fig1,'Visible','on'); 
                    end
                case hTab_biPLS_PLSDA
                    Tab = get(hTabGroupbiPLS_PLSDA,'SelectedTab');
                    % Choosing the figures for each Tab
                    switch Tab
                        case hTabResiduals_Intervals_biPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);
        
                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(AxesbiPLS_RMSE,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.75 .81]);
        
                            % Coping elements to Export
                            copyobj(axch,Fig1);
        
                            set(Fig1,'Visible','on');

                        case hTabPredMeasure_biPLS
                            % Creating figure
                            Fig1 = figureExport(GUIData);

                            % Organize figures
                            movegui(Fig1,'center')
                            axch = copyobj(hTabPredMeasure_biPLS.Children,hPLOTfigure);
                            set(axch,'Position',[0.15 0.12 0.70 .74]);    
                            for ki=1:size(hResiduals_iPLS.Children,1)
                                % Coping elements to Export
                                ax(ki) = copyobj(axch(ki),Fig1);   
                                set(ax(ki),'position',hResiduals_iPLS.Children(ki).Position);
                            end
        
                            set(Fig1,'Visible','on'); 
                    end
            end
        end
        guidata(hPLOTfigure,GUIData);
    end
    function ExportModel (eventdata, handles)  
        GUIData = guidata(hPLOTfigure);
        [filename, pathname] = uiputfile('*.mat','Save PCA Model','GNAT_PCA_Model.txt');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end

        % Print out PCA Model to file
        filepath=[pathname filename];
        GNATData.TypeModel = 1;
        GNATData.ExportInf = Export_Inf;
%         save(filepath,'pca','-v7.3');
        guidata(hPLOTfigure,GUIData);       

    end
    function SaveLogfile_Callback(eventdata, handles)
        LogFileName = 'GNAT_PCALog.txt';      
        [filename, pathname] = uiputfile('*.txt','Save  logfile',LogFileName);
        if filename==0
        else
            copyfile(LogFileName,[pathname filename],'f')
        end
    end
toc

end