%% 
function GNAT()
%   GNAT() - The General NMR Analysis Toolbox GUI for processing NMR data
%   Please consult the manual for more information%
%
%   Example:  Start the graphical user interface by typing "GNAT"
%             in the command window
%
%   See also: dosy_mn, score_mn, decra_mn, varianimport,
%             brukerimport, jeolimport, peakpick_mn, dosyplot_mn,
%             dosyresidual, dosyplot_gui, scoreplot_mn, decraplot_mn,
%         testing
%
%   Copyright  2021  <Mathias Nilsson>%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU Gen eral 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
%   mathias.nilsson@manchester.ac.uk

%% Changes
%MN  10     Nov 2017   Fixed plotting issue in locodosy
%MN  4      Jan 2018   Removing unused handles, but keeping the names as
%                      comments
%MN  12      Jan 2018  Implementting DSP correction (Bruker) as a phase
%                      shift  rather than rotating points
%                      comments
%MN  15      Jan 2018  Fixed a 1 point problem in FT zerofilling
%Turning certain things on for local (University of Manchester) use.
%MN  19     Jan  2018  Added zeroth order autophase
%MN  2     Feb  2018   Fixed problem with pure shift
%MN  26     Feb  2018  Added a module for Macros
%MN  26     Feb  2018  Fixed a problem with phases changing between Global
%                      and Individual scope
%MN  13     Mar  2018  Sorted sizes for axes and splash figures
%                      Updates array numbers when recalling data
%MN  14     Mar  2018  Disabled logfile for compiled versions
%GDP 25     Oct  2018  Making import 4D data available
%GDP 30     Oct  2018  Mouse right-click on peak deletes integral
%                      (when SET is being used)
%GDP 31     Oct  2018  Changed function of relaxation and diffusion to
%                      correct fitted I(0)
%GDP 1      Nov  2018  Added function to measure SNR (Noise uses similar
%                      function as the exclude regions)
%GDP 1      Nov  2018  Importing NUSLIST
%MN  19     Dec  2018  Fixed Varian data using bigtau for relaxation experiments  
%MN  16     Jan  2019  Fixed pure shift module
%MN  16     Jan  2019  open/save in GNAT format for 1D, diffusion and
%MN  21     Jan  2019  click_msgbo. New utility funtion added
%GDP 26     Apr  2019  Import and export of pure array added
%MJS 24     Nov  2020  Fixed issue with the chemical shift axis - 10322
%MJS 27     Nov  2020  T1 resolution in ROSY plot fixed 3798 and 4139
%MJS 27     Nov  2020  Fixed Error editing Dmax for DOSY plot 3003
%GDP 03     Mar  2021  Importing gpnam from acqus (Bruker)
%MJS 29     Sept 2021  Bug fix when importing 2D interferrogram data
%MJS 15     Feb  2022  Implementing the COSCORE code devlopment by MJS and AH
%MJS 28     Jul  2022  Implemting the PCA developed by Hugo into most recent version of GNAT
%MN  28     Apr  2023  Added an import function for a Matlab structure
%MN  10     May  2023  Starting a tidy-up
%MN  15     May  2023  Removed the TrapErrors system.
%MN  15     May  2023  Removed GNATlog.txt function
%MN  15     May  2023  fixed 
%MN  15     May  2023  further clean up of log messages 
%MN  15     May  2023  Removed PARALIND 
%MN  15     May  2023  fixed an error in the Bin export and binning routine 
%MN  15     May  2023  Fixed the auto integrals - better defaults still needed  
%MN  01     Nov  2023  Tidy up import menu 
%MJS 31     Jan  2024  Implement linear prediction
%MJS 01 .   Feb  2024  Implemented potential fix to parsing error see LP control tab and LPestimate.m 
%MN  19     Apr  2024  Added DSS for reference deconvolution 

    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    % Debug mode handling, run this file as a script if 'debug'      %
    % is passed                                                      %
    %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    switch nargin
        case 1
        % parse 
        case 0
        otherwise
            error('GNAT() takes either 0 or 1 arguments.')
    end
%NmrData.local='no';
NmrData.local='yes';
%set the version
NmrData.version='General NMR Analysis Toolbox (GNAT) 2.1';
%Initiate logfile


NmrData.MessageText={string(datetime)};
NmrData.MessageText{end +1}=NmrData.version;
%% Splash screen if not compiled
mpath= mfilename('fullpath');
mname=mfilename;
mlength=numel(mname);
mpath((end-mlength+1):end)=[];
if isdeployed
    %do nothing
else
    hSplashFig=figure(...
        'Units','pixels',...
        'MenuBar','none',...
        'NumberTitle','Off',...
        'Tag','MainFigure',...
        'Toolbar','None',...
        'OuterPosition',[0.0 0.0 600 750 ],...
        'Visible','Off');
    movegui(hSplashFig,'center')
    hSplashAx=axes('Parent',hSplashFig,...
        'Box','Off',...
        'Visible','On');
    set(hSplashAx, 'Position', [0 0 1 1])


    impath=[mpath 'splash_small.png'];
    if exist(impath,'file')
        splashim=imread(impath);
        image(hSplashAx,splashim);
    end
    set(hSplashAx, 'Box', 'Off','XTick',[],'YTick',[],'Color','None');
    movegui(hSplashFig,'center')
    
    set(hSplashFig,'Visible','On')
end
%% Main Figure

% Main figure
hMainFigure = figure(...
    'Units','pixels',...
    'MenuBar','none',...
    'Name',NmrData.version,...
    'NumberTitle','Off',...
    'Tag','MainFigure',...
    'DeleteFcn',@hMainFigure_DeleteFcn,...
    'Toolbar','Figure',...
    'OuterPosition',[0.0 0.0 1280 1024 ],...
    'Visible','off');
hAxes = axes('Parent',hMainFigure,...
    'Units','normalized',...
    'Tag','Axes',...
    'Position',[0.03 0.42 0.88 0.55],...
    'ButtonDownFcn',{@Axes_ButtonDownFcn});
guidata(hMainFigure,NmrData);

%Clean up the Toolbar, removing things we don't need
tmp = findall(hMainFigure,'ToolTipString','Save Figure');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Print Figure');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','New Figure');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Open File');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Link Plot');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Insert Legend');
set(tmp,'Visible','Off')
% tmp = findall(hMainFigure,'ToolTipString','Edit Plot');
% set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Rotate 3D');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Brush/Select Data');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Hide Plot Tools');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Data Cursor');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Insert Colorbar');
set(tmp,'Visible','Off')
tmp = findall(hMainFigure,'ToolTipString','Show Plot Tools and Dock Figure');
set(tmp,'Visible','Off')
%% Menus

% File menu
hMenuFile=uimenu(...
    'Parent',hMainFigure,...
    'Label','File');
hOpenMenu=uimenu(hMenuFile,'Label','Open',...
    'Enable','On');
uimenu(hOpenMenu,'Label','GNAT format (ASCII or binary)',...
    'Enable','On',...
    'Callback',{@Import_ToolboxASCII});
uimenu(hOpenMenu,'Label','Matlab format',...
    'Enable','On',...
    'Callback',{@Open_data});
hImportMenu=uimenu(hMenuFile,'Label','Import',...
    'Enable','On');

hImportMenuBruker=uimenu(hImportMenu,'Label','Bruker',...
    'Enable','On');
uimenu(hImportMenuBruker,'Label','Bruker',...
    'Enable','On',...
    'Callback',{@Import_Bruker});
uimenu(hImportMenuBruker,'Label','Bruker array',...
    'Enable','On',...
    'Callback',{@Import_Bruker_array});
uimenu(hImportMenuBruker,'Label','Bruker 2D array',...
    'Enable','On',...
    'Callback',{@Import_Bruker_2Darray});
uimenu(hImportMenuBruker,'Label','Bruker (Processed)',...
    'Enable','On',...
    'Callback',{@Import_Bruker_Processed});
uimenu(hImportMenuBruker,'Label','Bruker array (Processed)',...
    'Enable','On',...
    'Callback',{@Import_Bruker_array_Processed});
uimenu(hImportMenuBruker,'Label','Bruker 2D array (Processed)',...
    'Enable','On',...
    'Callback',{@Import_Bruker_2Darray_Processed});
uimenu(hImportMenuBruker,'Label','Bruker pure acquisition order',...
    'Enable','On',...
    'Callback',{@Import_Bruker_pureacq});

hImportMenuVarian=uimenu(hImportMenu,'Label','Varian',...
    'Enable','On');
uimenu(hImportMenuVarian,'Label','Varian',...
    'Enable','On',...
    'Callback',{@Import_Varian});
uimenu(hImportMenuVarian,'Label','Varian array',...
    'Enable','On',...
    'Callback',{@Import_Varian_Array})

hImportMenuJEOL=uimenu(hImportMenu,'Label','JEOL',...
    'Enable','On');
uimenu(hImportMenuJEOL,'Label','Jeol (*.jdf)',...
    'Enable','On',...
    'Visible','On',...
    'Callback',{@Import_Jeol});
uimenu(hImportMenuJEOL,'Label','JEOL Generic',...
    'Enable','On',...
    'Callback',{@Import_JeolGeneric});
hImportMenuJASON=uimenu(hImportMenu,'Label','JASON',...
    'Enable','On');
uimenu(hImportMenuJASON,'Label','JASON',...
    'Enable','On',...
    'Callback',{@Import_JASON});
uimenu(hImportMenuJASON,'Label','JASON array',...
    'Enable','On',...
    'Callback',{@Import_JASON_array});
uimenu(hImportMenuJASON,'Label','JASON (Processed)',...
    'Enable','On',...
    'Callback',{@Import_JASON_Processed});
uimenu(hImportMenuJASON,'Label','JASON array (Processed)',...
    'Enable','On',...
    'Callback',{@Import_JASON_array_Processed});


if strcmp(NmrData.local,'yes')
    hImportMenuXpulse=uimenu(hImportMenu,'Label','X-pulse',...
        'Enable','On');
    uimenu(hImportMenuXpulse,'Label','X-pulse',...
        'Enable','On',...
        'Callback',{@Import_X_pulse});
    uimenu(hImportMenuXpulse,'Label','X-pulse array',...
        'Enable','On',...
        'Callback',{@Import_X_pulse_array});

   hImportMenuMisc=uimenu(hImportMenu,'Label','Misc',...
        'Enable','On');
    uimenu(hImportMenuMisc,'Label','Matlab structure',...
        'Enable','On',...
        'Callback',{@Import_Matlab_structure});
    
hImportMenuMagritek=uimenu(hImportMenu,'Label','Magritek',...
        'Enable','On');
    uimenu(hImportMenuMagritek,'Label','Magritek',...
        'Enable','On',...
        'Callback',{@Import_Magritek});
    uimenu(hImportMenuMagritek,'Label','Magritek_2D',...
        'Enable','On',...
        'Callback',{@Import_Magritek_2D});
hImportMenuMestrenova=uimenu(hImportMenu,'Label','MestReNova',...
        'Enable','On');
    uimenu(hImportMenuMestrenova,'Label','JCAMP',...
        'Enable','On',...
        'Callback',{@Import_mestrenova});
end
hSaveMenu=uimenu(hMenuFile,'Label','Save',...
    'Enable','On');
uimenu(hSaveMenu,'Label','Matlab format',...
    'Enable','On',...
    'Callback',{@SaveDataMatlab});
hExportMenu=uimenu(hMenuFile,'Label','Export',...
    'Enable','On');
hToolboxBin=uimenu(hSaveMenu,'Label','GNAT binary format',...
    'Enable','On');
hToolboxAsc=uimenu(hSaveMenu,'Label','GNAT ASCII format',...
    'Enable','On');
uimenu(hToolboxAsc,'Label','Raw data',...
    'Enable','On',...
    'Callback',{@SaveFIDDataToolboxASCII});
uimenu(hToolboxAsc,'Label','Inverse FT of complex spectrum',...
    'Enable','On',...
    'Callback',{@SaveComplexSpecDataToolboxASCII});
uimenu(hToolboxAsc,'Label','Inverse FT of real spectrum',...
    'Enable','On',...
    'Callback',{@SaveRealSpecDataToolboxASCII});
uimenu(hToolboxBin,'Label','Raw data',...
    'Enable','On',...
    'Callback',{@SaveFIDDataToolboxBinary});
uimenu(hToolboxBin,'Label','Inverse FT of complex spectrum',...
    'Enable','On',...
    'Callback',{@SaveComplexSpecDataToolboxBinary});
uimenu(hToolboxBin,'Label','Inverse FT of real spectrum',...
    'Enable','On',...
    'Callback',{@SaveRealSpecDataToolboxBinary});
uimenu(hExportMenu,'Label','DOSY prepared data',...
    'Enable','On',...
    'Callback',{@ExportDOSY});
uimenu(hExportMenu,'Label','PARAFAC prepared data',...
    'Enable','On',...
    'Callback',{@ExportPARAFAC});
uimenu(hExportMenu,'Label','Time domain NMR data (ASCII)',...
    'Enable','On',...
    'Callback',{@ExportTDData});
uimenu(hExportMenu,'Label','Bruker data',...
    'Enable','On',...
    'Callback',{@ExportBruker});
uimenu(hExportMenu,'Label','Convolution GUI',...
    'Enable','On',...
    'Callback',{@ExportConvolData});
uimenu(hMenuFile,'Label','Import Bruker',...
    'Enable','On',...
    'Separator','On',...
    'Callback',{@Import_Bruker});
uimenu(hMenuFile,'Label','Import Bruker (Processed)',...
    'Enable','On',...
    'Callback',{@Import_Bruker_Processed});
uimenu(hMenuFile,'Label','Import Varian',...
    'Enable','On',...
    'Callback',{@Import_Varian});
uimenu(hMenuFile,'Label','Quit',...
    'Enable','On',...
    'Separator','On',...
    'Callback',{@QuitToolbox});

% Edit menu
hEditFile=uimenu(...
    'Parent',hMainFigure,...
    'Label','Edit');
uimenu(hEditFile,'Label','Settings',...
    'Enable','On',...
    'Callback',{@Edit_Settings});
% if isdeployed
%     %do nothing. Macros only supported for Matlab version
% else
%     if strcmp(NmrData.local,'yes')
%         %Local for now
%         uimenu(hEditFile,'Label','Macros',...
%             'Enable','On',...
%             'Callback',{@Edit_Macros});
%     end
% end

% Help menu
hMenuHelp=uimenu(...
    'Parent',hMainFigure,...
    'Label','Help');
uimenu(hMenuHelp,'Label','About the NMR Analysis Toolbox',...
    'Enable','On',...
    'Callback',{@Help_About});

uimenu(hMenuHelp,'Label','More information about GNAT',...
    'Enable','On',...
    'Callback',{@HelpMenu});

%% Panel for shortcuts
hShortcutsPanel=uipanel(...
    'Parent',hMainFigure,...
    'Title','',...
    'FontWeight','bold',...
    'Bordertype','none',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.925 0.37 0.07 0.61 ]);
hScalePanelShort=uipanel(...
    'Parent',hShortcutsPanel,...
    'Title','Scale',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.73,1.0,0.25]);
%hButtonMult2Short = 
uicontrol(...
    'Parent',hScalePanelShort,...
    'Style','PushButton',...
    'String',[char(hex2dec('D7')) ' 2'],...
    'Units','Normalized',...
    'TooltipString','Increase the vertical scale by a factor 2',...
    'Position',[0.05 0.7 0.40 0.25],...
    'Callback',{ @ButtonMult2_Callback});
%hButtonDiv2Short = 
uicontrol(...
    'Parent',hScalePanelShort,...
    'Style','PushButton',...
    'String',[char(hex2dec('F7')) ' 2'],...
    'Units','Normalized',...
    'TooltipString','Decrease the vertical scale by a factor 2',...
    'Position',[0.55 0.7 0.4 0.25],...
    'Callback',{ @ButtonDiv2_Callback});
%hButtonMult11Short = 
uicontrol(...
    'Parent',hScalePanelShort,...
    'Style','PushButton',...
    'String',[char(hex2dec('D7')) ' 1.1'],...
    'Units','Normalized',...
    'Position',[0.05 0.38 0.4 0.25],...
    'TooltipString','Increase the vertical scale by a factor 1.1',...
    'Callback',{ @ButtonMult11_Callback});
%hButtonDiv11Short = 
uicontrol(...
    'Parent',hScalePanelShort,...
    'Style','PushButton',...
    'String',[char(hex2dec('F7')) ' 1.1'],...
    'Units','Normalized',...
    'TooltipString','Decrease the vertical scale by a factor 1.1',...
    'Position',[0.55 0.38 0.4 0.25],...
    'Callback',{ @ButtonDiv11_Callback});
%hButtonAutoscaleShort = 
uicontrol(...
    'Parent',hScalePanelShort,...
    'Style','Pushbutton',...
    'String','Auto',...
    'Units','Normalized',...
    'TooltipString','Automatic setting of the vertical scale',...
    'Position',[0.05 0.05 0.40 0.25],...
    'Callback',{@ButtonAutoscale_Callback});
%hButtonFullShort = 
uicontrol(...
    'Parent',hScalePanelShort,...
    'Style','Pushbutton',...
    'String','Full',...
    'Units','Normalized',...
    'TooltipString','Display the whole FID/spectrum with autoscale',...
    'Position',[0.55 0.05 0.4 0.25],...
    'Callback',{@ButtonFull_Callback});

% Zoom
hZoomPanelShort=uipanel(...
    'Parent',hShortcutsPanel,...
    'Title','Zoom',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.62,1.0,0.1]);
%hpanXButtonShort = 
uicontrol(...
    'Parent',hZoomPanelShort,...
    'Style','PushButton',...
    'String','X',...
    'Units','normalized',...
    'TooltipString','Interactive zoom in the x-direction',...
    'Position',[0.05 0.05 0.40 0.9],...
    'Callback', { @panXButton_Callback});
%hpanXYButtonShort = 
uicontrol(...
    'Parent',hZoomPanelShort,...
    'Style','PushButton',...
    'String','XY',...
    'Units','normalized',...
    'TooltipString','Interactive zoom in the x- and y-direction',...
    'Position',[0.55 0.05 0.4 0.9],...
    'Callback', { @panXYButton_Callback});


% Threshold
hThresPanelShort=uipanel(...
    'Parent',hShortcutsPanel,...
    'Title','',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.5,1.0,0.1]);
hThreshButton = uicontrol(...
    'Parent',hThresPanelShort,...
    'Style','ToggleButton',...
    'String','Thresh',...
    'Units','normalized',...
    'TooltipString','Set threshold',...
    'Position',[0.05 0.05 0.9 0.9],...
    'Callback', { @ThresholdButton_Callback});

% Spectrum
hArrayPanelShort=uipanel(...
    'Parent',hShortcutsPanel,...
    'Title','Spectrum',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.38,1.0,0.1]);
hEditFlipSpecShort=uicontrol(...
    'Parent',hArrayPanelShort,...
    'Style','edit',...
    'Units','Normalized',...
    'BackgroundColor','w',...
    'String',1,...
    'Position',[0.36 0.05 0.3 0.9 ],...
    'CallBack', { @EditFlipSpecShort_Callback});

hButtonFlipPlusSpec = uicontrol(...
    'Parent',hArrayPanelShort,...
    'Style','PushButton',...
    'String','+1',...
    'Units','normalized',...
    'TooltipString','Next spectrum in the array',...
    'Position',[0.69 0.05 0.3 0.9],...
    'Callback',{ @ButtonFlipPlusSpec_Callback});
hButtonFlipMinusSpec = uicontrol(...
    'Parent',hArrayPanelShort,...
    'Style','PushButton',...
    'String','-1',...
    'Units','normalized',...
    'TooltipString','Previous spectrum in the array',...
    'Position',[0.02 0.05 0.3 0.9],...
    'Callback',{ @ButtonFlipMinusSpec_Callback});

% FT
hFTPanelShort=uipanel(...
    'Parent',hShortcutsPanel,...
    'Title','',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.28,1.0,0.1]);
hFTButtonShort = uicontrol(...
    'Parent',hFTPanelShort,...
    'Style','ToggleButton',...
    'String','FT',...
    'Units','normalized',...
    'TooltipString','Fourier transform the FID',...
    'Position',[0.05 0.05 0.9 0.9],...
    'Callback', { @FTButton_Callback});

% Data state
hStatePanelShort=uipanel(...
    'Parent',hShortcutsPanel,...
    'Title','Data state',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.10,1.0,0.15]);
%hSaveButtonShort = 
uicontrol(...
    'Parent',hStatePanelShort,...
    'Style','PushButton',...
    'String','Save',...
    'Units','normalized',...
    'TooltipString','Save data with current processing parameters',...
    'Position',[0.05 0.52 0.9 0.44],...
    'Callback', { @SaveButton_Callback});
%hSaveButtonShort = 
uicontrol(...
    'Parent',hStatePanelShort,...
    'Style','PushButton',...
    'String','Recall',...
    'Units','normalized',...
    'TooltipString','Recall previosly saved data',...
    'Position',[0.05 0.04 0.9 0.44],...
    'Callback', { @RecallButton_Callback});
%% Tabgroup for Standard Processing
hTabGroupStandard=uitabgroup(...
    'Parent',hMainFigure,...
    'Units','Normalized',...
    'Position',[0.0,0.0,0.4,0.35]);
hTabPlotControl=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Plot',...
    'TooltipString','Controls for plot display',...
    'Units','Normalized');
hTabPhase=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Phase',...
    'TooltipString','Controls for phase correction',...
    'Units','Normalized');
hTabFT=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','FT',...
    'TooltipString','Basic processing for Fourier transformation, apodization and spectra reference',...
    'Units','Normalized');
hTabCorrections=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Correct',...
    'TooltipString','Baseline correction and reference deconvolution',...
    'Units','Normalized');
hTabArray=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Array',...
    'TooltipString','Select displayed spectrum from the array',...
    'Units','Normalized');
hTabPrune=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Prune',...
    'TooltipString','Exclude region(s) or array element(s) from data',...
    'Units','Normalized');
hLP=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Linear prediction',...
    'TooltipString','forward and backward linear prediction',...
    'Units','Normalized');
hTabPureshift=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Pure shift',...
    'TooltipString','Process interferogram pure shift NMR data',...
    'Units','Normalized');
hTabMiscLeft=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Misc',...
    'TooltipString','Miscellaneous',...
    'Units','Normalized');
hTabMessages=uitab(...
    'Parent',hTabGroupStandard,...
    'Title','Info',...
    'TooltipString','Information log',...
    'Units','Normalized');
%% ---------Plot control tab

% Scale
hScalePanel=uipanel(...
    'Parent',hTabPlotControl,...
    'Title','Scale',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.5,0.35,0.5]);
%hButtonMult2 = 
uicontrol(...
    'Parent',hScalePanel,...
    'Style','PushButton',...
    'String',[char(hex2dec('D7')) ' 2'],...
    'Units','Normalized',...
    'TooltipString','Increase the vertical scale by a factor 2',...
    'Position',[0.05 0.5 0.3 0.45],...
    'Callback',{ @ButtonMult2_Callback});
%hButtonDiv2 = 
uicontrol(...
    'Parent',hScalePanel,...
    'Style','PushButton',...
    'String',[char(hex2dec('F7')) ' 2'],...
    'Units','Normalized',...
    'TooltipString','Decrease the vertical scale by a factor 2',...
    'Position',[0.05 0.05 0.3 0.45],...
    'Callback',{ @ButtonDiv2_Callback});
%hButtonMult11 = 
uicontrol(...
    'Parent',hScalePanel,...
    'Style','PushButton',...
    'String',[char(hex2dec('D7')) ' 1.1'],...
    'Units','Normalized',...
    'Position',[0.35 0.5 0.3 0.45],...
    'TooltipString','Increase the vertical scale by a factor 1.1',...
    'Callback',{ @ButtonMult11_Callback});
%hButtonDiv11 = 
uicontrol(...
    'Parent',hScalePanel,...
    'Style','PushButton',...
    'String',[char(hex2dec('F7')) ' 1.1'],...
    'Units','Normalized',...
    'TooltipString','Decrease the vertical scale by a factor 1.1',...
    'Position',[0.35 0.05 0.3 0.45],...
    'Callback',{ @ButtonDiv11_Callback});
%hButtonAutoscale = 
uicontrol(...
    'Parent',hScalePanel,...
    'Style','Pushbutton',...
    'String','Auto',...
    'Units','Normalized',...
    'TooltipString','Automatic setting of the vertical scale',...
    'Position',[0.65 0.5 0.3 0.45],...
    'Callback',{ @ButtonAutoscale_Callback});
hButtonFull = uicontrol(...
    'Parent',hScalePanel,...
    'Style','Pushbutton',...
    'String','Full',...
    'Units','Normalized',...
    'TooltipString','Display the whole FID/spectrum with autoscale',...
    'Position',[0.65 0.05 0.3 0.45],...
    'Callback',{ @ButtonFull_Callback});

% Display
hDisplayPanel=uipanel(...
    'Parent',hTabPlotControl,...
    'Title','Display',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35,0.5,0.3,0.5]);
hButtonFid = uicontrol(...
    'Parent',hDisplayPanel,...
    'Style','ToggleButton',...
    'String','FID',...
    'Units','Normalized',...
    'TooltipString','Display the FID',...
    'Position',[0.05 0.5 0.35 0.45],...
    'Callback',{ @ButtonFid_Callback});
hButtonSpec = uicontrol(...
    'Parent',hDisplayPanel,...
    'Style','ToggleButton',...
    'String','Spectrum',...
    'Units','Normalized',...
    'TooltipString','Display the spectrum',...
    'Position',[0.05 0.05 0.35 0.45],...
    'Callback', { @ButtonSpec_Callback});
hAbsPhaseGroup = uibuttongroup(...
    'Parent',hDisplayPanel,...
    'Units','normalized',...
    'Visible','On',...
    'Title','',...
    'Bordertype','none',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'SelectionChangeFcn', { @GroupAbsPhase_Callback},...
    'Position',[0.45 0.0 0.6 1.0]);
hRadioPhase = uicontrol(...
    'Parent',hAbsPhaseGroup,...
    'Style','RadioButton',...
    'String','Phase',...
    'TooltipString','Display FID/spectrum in phase-sensitive mode',...
    'Units','normalized',...
    'Position',[0.05 0.6 0.9 0.4]);
hRadioAbs = uicontrol(...
    'Parent',hAbsPhaseGroup,...
    'Style','RadioButton',...
    'String','Abs.',...
    'TooltipString','Display FID/spectrum in absolute value mode',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.4]);

% Zoom/Pan
hZoomPanel=uipanel(...
    'Parent',hTabPlotControl,...
    'Title','Zoom / Pan',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.65,0.5,0.35,0.5]);
%hpanXButton = 
uicontrol(...
    'Parent',hZoomPanel,...
    'Style','PushButton',...
    'String','X',...
    'Units','normalized',...
    'TooltipString','Interactive zoom/pan in the x-direction',...
    'Position',[0.0 0.5 0.25 0.45],...
    'Callback', { @panXButton_Callback});
%hpanXYButton = 
uicontrol(...
    'Parent',hZoomPanel,...
    'Style','PushButton',...
    'String','XY',...
    'Units','normalized',...
    'TooltipString','Interactive zoom/pan in the x- and y-direction',...
    'Position',[0.0 0.05 0.25 0.45],...
    'Callback', { @panXYButton_Callback});
%hpanYButton = 
uicontrol(...
    'Parent',hZoomPanel,...
    'Style','PushButton',...
    'String','Y',...
    'Units','normalized',...
    'TooltipString','Interactive zoom/pan in the y-direction',...
    'Position',[0.25 0.5 0.25 0.45],...
    'Callback', { @panYButton_Callback});
%hpanOffButton = 
uicontrol(...
    'Parent',hZoomPanel,...
    'Style','PushButton',...
    'String','off',...
    'Units','normalized',...
    'TooltipString','Turn off the interactive zoom/pan',...
    'Position',[0.25 0.05 0.25 0.45],...
    'Callback', { @panOffButton_Callback});
hZoomPanGroup = uibuttongroup(...
    'Parent',hZoomPanel,...
    'Units','normalized',...
    'Title','',...
    'Bordertype','none',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'SelectionChangeFcn', { @GroupZoomPan_Callback},...
    'Position',[0.5 0.0 0.5 1.0]);
hRadioZoom = uicontrol(...
    'Parent',hZoomPanGroup,...
    'Style','RadioButton',...
    'String','Zoom',...
    'Units','normalized',...
    'Position',[0.05 0.6 0.9 0.4]);
hRadioPan = uicontrol(...
    'Parent',hZoomPanGroup,...
    'Style','RadioButton',...
    'String','Pan',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.4]);

% Separate plot
hSeparatePlotPanel=uipanel(...
    'Parent',hTabPlotControl,...
    'Title','Separate plot',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.0,0.35,0.5]);
%hButtonPlotCurrent = 
uicontrol(...
    'Parent',hSeparatePlotPanel,...
    'Style','PushButton',...
    'String','Standard plot',...
    'Units','Normalized',...
    'TooltipString','Plot FID/spectrum in a separate window',...
    'Position',[0.2 0.7 0.6 0.2],...
    'Callback',{ @ButtonPlotCurrent_Callback});
%hButtonPlotCurrent = 
uicontrol(...
    'Parent',hSeparatePlotPanel,...
    'Style','PushButton',...
    'String','Publication plot',...
    'Units','Normalized',...
    'TooltipString','Plot FID/spectrum for publication',...
    'Position',[0.2 0.4 0.6 0.2],...
    'Callback',{ @ButtonPlotCurrentPubl_Callback});
%hButtonPlotCurrent = 
uicontrol(...
    'Parent',hSeparatePlotPanel,...
    'Style','PushButton',...
    'String','Close all',...
    'Units','Normalized',...
    'TooltipString','Close all plots (not closes GNAT)',...
    'Position',[0.2 0.1 0.6 0.2],...
    'Callback',{ @ButtonPlotCloseall_Callback});

% Shift range
hScaleGroup=uibuttongroup(...
    'Parent',hTabPlotControl,...
    'Title','',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Title','Shift range',...
    'Units','Normalized',...
    'Position',[0.35,0.0,0.3,0.5]);
hEditScaleUp=uicontrol(...
    'Parent',hScaleGroup,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Highest chemical shift value displayed',...
    'Max',1,...
    'Position',[0.1 0.6 0.4 0.2 ],...
    'CallBack', { @EditScaleUp_Callback});
%hTextUp=
uicontrol(...
    'Parent',hScaleGroup,...
    'Style','text',...
    'Units','Normalized',...
    'horizontalalignment','left',...
    'Position',[0.55 0.48 0.3 0.3 ],...
    'String','High' );
hEditScaleDown=uicontrol(...
    'Parent',hScaleGroup,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Lower chemical shift value displayed',...
    'Max',1,...
    'Position',[0.1 0.1 0.4 0.2 ],...
    'CallBack', { @EditScaleDown_Callback});
%hTextDown=
uicontrol(...
    'Parent',hScaleGroup,...
    'Style','text',...
    'Units','Normalized',...
    'horizontalalignment','left',...
    'Position',[0.55 0.00 0.3 0.3 ],...
    'String','Low' );

% Horizontal scale
hUnitsGroup=uibuttongroup(...
    'Parent',hTabPlotControl,...
    'Title','',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Title','Horizontal scale',...
    'Units','Normalized',...
    'SelectionChangeFcn', { @Units_Callback},...
    'Visible','On',...
    'Position',[0.65,0.0,0.35,0.5]);
hRadioPPM = uicontrol(...
    'Parent',hUnitsGroup,...
    'Style','RadioButton',...
    'String','ppm',...
    'Units','normalized',...
    'Position',[0.1 0.6 0.5 0.25]);
hRadioHz = uicontrol(...
    'Parent',hUnitsGroup,...
    'Style','RadioButton',...
    'String','Hz',...
    'Units','normalized',...
    'Position',[0.1 0.2 0.5 0.25]);
%% ---------Phase control tab

%   Zero order phasing
hPh0Panel=uipanel(...
    'Parent',hTabPhase,...
    'Title','Zero order',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.5,0.4,0.5]);
hSliderPh0=uicontrol(...
    'Parent',hPh0Panel,...
    'Style','slider',...
    'Units','Normalized',...
    'Min' ,-360,'Max',360, ...
    'Position',[0.05,0.7,0.9,0.2], ...
    'Value', 0,...
    'SliderStep',[1/720 10/720], ...
    'CallBack', { @SliderPh0_Callback});
hEditPh0=uicontrol(...
    'Parent',hPh0Panel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Zero-order phase correction (degrees)',...
    'Position',[0.4 0.4 0.2 0.2 ],...
    'CallBack', { @EditPh0_Callback});
%hButtonPlusPh0 = 
uicontrol(...
    'Parent',hPh0Panel,...
    'Style','PushButton',...
    'String','+0.1',...
    'Units','normalized',...
    'Position',[0.52 0.05 0.2 0.2],...
    'Callback',{ @ButtonPlusPh0_Callback});
%hButtonMinusPh0 = 
uicontrol(...
    'Parent',hPh0Panel,...
    'Style','PushButton',...
    'String','-0.1',...
    'Units','normalized',...
    'Position',[0.28 0.05 0.2 0.2],...
    'Callback',{ @ButtonMinusPh0_Callback});
hTextMaxPh0=uicontrol(...
    'Parent',hPh0Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.7 0.39 0.2 0.2 ],...
    'horizontalalignment','c');
hTextMinPh0=uicontrol(...
    'Parent',hPh0Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.39 0.2 0.2 ],...
    'horizontalalignment','c');

% Pivot
hPivotPanel=uipanel(...
    'Parent',hTabPhase,...
    'Title','Pivot',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'BorderType','None',...
    'Units','Normalized',...
    'Position',[0.4,0.50,0.2,0.50]);
%hPivotButton = 
uicontrol(...
    'Parent',hPivotPanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Set the pivot point',...
    'Position',[0.1 0.72 0.8 0.25],...
    'Callback',{ @PivotButton_Callback});
hPivotCheck = uicontrol(...
    'Parent',hPivotPanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Units','normalized',...
    'Position',[0.1 0.5 0.8 0.2],...
    'Callback',{ @PivotCheck_Callback});
%hAutoButton = 
uicontrol(...
    'Parent',hPivotPanel,...
    'Style','PushButton',...
    'String','Auto',...
    'TooltipString','Automatic phase correction of zero and first order',...
    'Units','normalized',...
    'Position',[0.1 0.28 0.8 0.2],...
    'Callback',{ @ButtonAutophase_Callback});
uicontrol(...
    'Parent',hPivotPanel,...
    'Style','PushButton',...
    'String','Auto 0',...
    'TooltipString','Automatic phase correction of zero order only',...
    'Units','normalized',...
    'Position',[0.1 0.04 0.8 0.2],...
    'Callback',{ @ButtonAutophase0_Callback});

% First order phasing
hPh1Panel=uipanel(...
    'Parent',hTabPhase,...
    'Title','First order',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.6,0.5,0.4,0.5]);
hSliderPh1=uicontrol(...
    'Parent',hPh1Panel,...
    'Style','slider',...
    'Units','Normalized',...
    'Min' ,-36000,'Max',36000, ...
    'Position',[0.05,0.7,0.9,0.2], ...
    'Value', 0,...
    'SliderStep',[1/7200 10/7200], ...
    'CallBack', { @SliderPh1_Callback});
hEditPh1=uicontrol(...
    'Parent',hPh1Panel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','First-order phase correction (degrees)',...
    'Position',[0.4 0.4 0.2 0.2 ],...
    'CallBack', { @EditPh1_Callback});
%hButtonPlusPh1 = 
uicontrol(...
    'Parent',hPh1Panel,...
    'Style','PushButton',...
    'String','+0.5',...
    'Units','normalized',...
    'Position',[0.52 0.05 0.2 0.2],...
    'Callback',{ @ButtonPlusPh1_Callback});
%hButtonMinusPh1 = 
uicontrol(...
    'Parent',hPh1Panel,...
    'Style','PushButton',...
    'String','-0.5',...
    'Units','normalized',...
    'Position',[0.28 0.05 0.2 0.2],...
    'Callback',{ @ButtonMinusPh1_Callback});
hTextMaxPh1=uicontrol(...
    'Parent',hPh1Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.7 0.39 0.3 0.2 ],...
    'horizontalalignment','c');
hTextMinPh1=uicontrol(...
    'Parent',hPh1Panel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.0 0.39 0.3 0.2 ],...
    'horizontalalignment','c');


% Scope
hScopeGroup = uibuttongroup(...
    'Parent',hTabPhase,...
    'Units','normalized',...
    'Visible','On',...
    'Title','Scope',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'SelectionChangeFcn', { @GroupScope_Callback},...
    'Position',[0.3 0.05 0.4 0.4]);
hRadioScopeGlobal = uicontrol(...
    'Parent',hScopeGroup,...
    'Style','RadioButton',...
    'String','Global',...
    'TooltipString','Phase correction is applied to all spectra',...
    'Units','normalized',...
    'Position',[0.0 0.65 0.5 0.3]);
hRadioScopeIndividual = uicontrol(...
    'Parent',hScopeGroup,...
    'Style','RadioButton',...
    'String','Individual',...
    'TooltipString','Phase correction is applied to current spectrum',...
    'Units','normalized',...
    'Position',[0.0 0.15 0.5 0.3]);
hPushCopyGtoI = uicontrol(...
    'Parent',hScopeGroup,...
    'Style','PushButton',...
    'String','G to I',...
    'Enable','On',...
    'TooltipString','Copy current global phase parameters to all individual phase parameters',...
    'Units','normalized',...
    'Position',[0.55 0.65 0.35 0.3],...
    'Callback',{ @GtoIButton_Callback});
hPushAutoAll=uicontrol(...
    'Parent',hScopeGroup,...
    'Style','PushButton',...
    'String','Auto all',...
    'TooltipString','Automatic phase correction of zero and first order',...
    'Units','normalized',...
    'Position',[0.55 0.30 0.4 0.21],...
    'Callback',{ @ButtonAutophaseAll_Callback});
hPushAuto0All=uicontrol(...
    'Parent',hScopeGroup,...
    'Style','PushButton',...
    'String','Auto 0 all',...
    'TooltipString','Automatic phase correction of zero order only',...
    'Units','normalized',...
    'Position',[0.55 0.04 0.4 0.21],...
    'Callback',{ @ButtonAutophase0All_Callback});



    uicontrol(...
    'Parent',hTabPhase,...
    'Style','PushButton',...
    'String','Phase Table',...
    'TooltipString','Display the phase for each increment individually',...
    'Units','normalized',...
    'Position',[0.75 0.2 0.2 0.1],...
    'Callback',{@ButtonphaseTable_Callback});
%% ---------Fourier transform tab

% Fourier transform
hFourierPanel=uipanel(...
    'Parent',hTabFT,...
    'Title','Fourier transform',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.7,1.0,0.3]);
%hFTButton = 
uicontrol(...
    'Parent',hFourierPanel,...
    'Style','PushButton',...
    'String','FT',...
    'Units','normalized',...
    'TooltipString','Fourier transform the FID',...
    'Position',[0.05 0.2 0.15 0.6],...
    'Callback',{ @FTButton_Callback});
hEditFn=uicontrol(...
    'Parent',hFourierPanel,...
    'Style','edit',...
    'Visible','On',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString',...
    'Number of (complex) points used in the Fourier transform',...
    'Max',1,...
    'Position',[0.35 0.3 0.2 0.4 ],...
    'CallBack', { @EditFn_Callback});
%hTextFn=
uicontrol(...
    'Parent',hFourierPanel,...
    'Style','text',...
    'Units','Normalized',...
    'horizontalalignment','Left',...
    'FontWeight','bold',...
    'Position',[0.29 0.28 0.05 0.4 ],...
    'String','fn:' );
%hFnButtonPlus = 
uicontrol(...
    'Parent',hFourierPanel,...
    'Style','PushButton',...
    'String','+',...
    'Units','normalized',...
    'TooltipString','Multiply current fn a factor 2',...
    'Position',[0.61 0.3 0.05 0.4],...
    'Callback',{ @FnButtonPlus_Callback});
%hFnButtonMinus = 
uicontrol(...
    'Parent',hFourierPanel,...
    'Style','PushButton',...
    'String','-',...
    'Units','normalized',...
    'TooltipString','Divide current fn a factor 2',...
    'Position',[0.56 0.3 0.05 0.4],...
    'Callback',{ @FnButtonMinus_Callback});
hEditNp=uicontrol(...
    'Parent',hFourierPanel,...
    'Style','edit',...
    'Visible','On',...
    'Units','Normalized',...
    'Enable','Off',...
    'TooltipString','Number of (complex) points in the FID',...
    'Position',[0.78 0.3 0.2 0.4 ],...
    'CallBack', { @EditNp_Callback});
%hTextNp=
uicontrol(...
    'Parent',hFourierPanel,...
    'Style','text',...
    'Units','Normalized',...
    'horizontalalignment','Left',...
    'FontWeight','bold',...
    'Position',[0.72 0.28 0.05 0.4 ],...
    'String','np:' );

% Window function
hWindowFunctionPanel=uipanel(...
    'Parent',hTabFT,...
    'Title','Window function',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0.3 1.0 0.4]);
hEditLb=uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','edit',...
    'Visible','On',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'Enable','Off',...
    'TooltipString','Enter the line broadening function value',...
    'Max',1,...
    'Position',[0.05 0.2 0.05 0.3 ],...
    'CallBack', { @EditLb_Callback});
hCheckLb=uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','checkbox',...
    'Units','Normalized',...
    'Value',0,...
    'TooltipString','Use the line broadening function',...
    'Position',[0.11 0.275 0.05 0.2 ],...
    'CallBack', { @CheckLb_Callback} );
%hTextLb=
uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Horizontalalignment','left',...
    'Position',[0.025 0.6 0.2 0.3 ],...
    'String','Lorentzian (Lw)' );
hEditGw=uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','edit',...
    'Visible','On',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'Enable','Off',...
    'TooltipString','Enter the gaussian function value',...
    'Max',1,...
    'Position',[0.25 0.20 0.05 0.3 ],...
    'CallBack', { @EditGw_Callback});
%hTextGw=
uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Horizontalalignment','left',...
    'Position',[0.22 0.6 0.2 0.3 ],...
    'String','Gaussian (Gw)' );
hCheckGw=uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','checkbox',...
    'Units','Normalized',...
    'Value',0,...
    'TooltipString','Use the gaussian function',...
    'Position',[0.31 0.275 0.05 0.2 ],...
    'CallBack', { @CheckGw_Callback} );
%hTextPlot=
uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','Show in plot',...
    'TooltipString','Will activate when FID display is chosen',...
    'FontWeight','bold',...
    'Position',[0.60 0.6 0.3 0.3 ],...
    'horizontalalignment','c');
hPlotFID = uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','Checkbox',...
    'String','FID',...
    'TooltipString','Will activate when FID display is chosen',...
    'Value',1,...
    'Enable','off',...
    'Units','normalized',...
    'Position',[0.6 0.4 0.2 0.25],...
    'Callback',{ @PlotFID_Callback});
hPlotWinfunc = uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','Checkbox',...
    'String','Window Function (WF)',...
    'TooltipString','Will activate when FID display is chosen',...
    'Enable','off',...
    'Units','normalized',...
    'Position',[0.6 0.1 0.2 0.25],...
    'Callback',{ @PlotWinfunc_Callback});
hPlotFIDWinfunc = uicontrol(...
    'Parent',hWindowFunctionPanel,...
    'Style','Checkbox',...
    'String','FID*WF',...
    'TooltipString','Will activate when FID display is chosen',...
    'Enable','off',...
    'Units','normalized',...
    'Position',[0.75 0.4 0.2 0.25],...
    'Callback',{ @PlotFIDWinfunc_Callback});

% Reference
hReferencePanel=uipanel(...
    'Parent',hTabFT,...
    'Title','Reference',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.0,1.0,0.3]);
%hReferenceButton = 
uicontrol(...
    'Parent',hReferencePanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Set the reference line',...
    'Position',[0.05 0.1 0.1 0.8],...
    'Callback',{ @ReferenceButton_Callback});
%hFindButton = 
uicontrol(...
    'Parent',hReferencePanel,...
    'Style','PushButton',...
    'String','Find',...
    'Units','normalized',...
    'TooltipString','Find the peak maximum',...
    'Position',[0.15 0.1 0.1 0.8],...
    'Callback',{ @FindButton_Callback});

hReferenceCheck = uicontrol(...
    'Parent',hReferencePanel,...
    'Style','CheckBox',...
    'String','Show',...
    'Units','normalized',...
    'TooltipString','Show the reference line',...
    'Position',[0.26 0.53 0.2 0.5],...
    'Callback',{ @ReferenceCheck_Callback});
hReferenceAutoCheck = uicontrol(...
    'Parent',hReferencePanel,...
    'Style','CheckBox',...
    'String','Auto',...
    'Units','normalized',...
    'TooltipString','Auto correction of chemical shift for the ref signal in the time domain',...
    'Position',[0.42 0.07 0.11 0.5]);
hReferenceFIDCheck = uicontrol(...
    'Parent',hReferencePanel,...
    'Style','CheckBox',...
    'String','FID',...
    'Units','normalized',...
    'TooltipString','Use the chemical shift offset as a correction factor in the time domain',...
    'Position',[0.26 0.07 0.11 0.5]);
%hChangeButton = 
uicontrol(...
    'Parent',hReferencePanel,...
    'Style','PushButton',...
    'String','Ref',...
    'Units','normalized',...
    'TooltipString','Apply the new reference value',...
    'Position',[0.68 0.1 0.1 0.8],...
    'Callback',{@ChangeButton_Callback});
hChangeEdit=uicontrol(...
    'Parent',hReferencePanel,...
    'Style','edit',...
    'Visible','On',...
    'Units','Normalized',...
    'TooltipString','Current reference value',...
    'Enable','Off',...
    'Max',1,...
    'Position',[0.80 0.1 0.1 0.8 ],...
    'CallBack', {@ChangeEdit_Callback});

%% ---------Corrections tab

% Baseline correction
hBaselinePanel=uipanel(...
    'Parent',hTabCorrections,...
    'Title','Baseline correction',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0.7 1 0.3]);
%hSetRegionsButton = 
uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Mark the regions with signal',...
    'Position',[0.16 0.2 0.12 0.6],...
    'Callback',{ @SetRegionsButton_Callback});
%hAutoBaselineButton = 
uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','PushButton',...
    'String','Auto',...
    'Units','normalized',...
    'Visible', 'On',...
    'TooltipString','Automatic baseline correction',...
    'Position',[0.03 0.2 0.12 0.6],...
    'Callback',{ @AutoBaselineButton_Callback});
%hClearRegionsButton = 
uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','PushButton',...
    'String','Clear',...
    'Units','normalized',...
    'TooltipString','Clear the marked regions',...
    'Position',[0.28 0.2 0.12 0.6],...
    'Callback',{ @ClearRegionsButton_Callback});
%hBaselineCorrectButton = 
uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','PushButton',...
    'String','Apply',...
    'Units','normalized',...
    'TooltipString','Apply baseline correction',...
    'Position',[0.4 0.2 0.12 0.6],...
    'Callback',{ @BaselineCorrectButton_Callback});
hBaselineShow = uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Units','normalized',...
    'TooltipString','Display the marked regions',...
    'Position',[0.64 0.2 0.2 0.6],...
    'Callback',{ @BaselineShow_Callback});
hBaselineShow = uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','PushButton',...
    'String','whsm',...
    'Units','normalized',...
    'TooltipString','Perform whittaker smoother baseline correction',...
    'Position',[0.52 0.2 0.12 0.6],...
    'Callback',{@whsm_Callback});
%hTextOrder=
uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'Position',[0.75 0.15 0.17 0.5 ],...
    'String','Order:' );
hEditOrder=uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','edit',...
    'Visible','On',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'Enable','On',...
    'TooltipString','Enter polynomial order for baseline correction',...
    'Max',1,...
    'Position',[0.82 0.2 0.06 0.6 ],...
    'CallBack', { @EditOrder_Callback});
%hOrderButtonPlus = 
uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','PushButton',...
    'String','+',...
    'Units','normalized',...
    'TooltipString','Increase polynomial order for baseline correction',...
    'Position',[0.89 0.2 0.05 0.6],...
    'Callback',{ @OrderButtonPlus_Callback});
%hOrderButtonMinus = 
uicontrol(...
    'Parent',hBaselinePanel,...
    'Style','PushButton',...
    'String','-',...
    'Units','normalized',...
    'TooltipString','Decrease polynomial order for baseline correction',...
    'Position',[0.94 0.2 0.05 0.6],...
    'Callback',{ @OrderButtonMinus_Callback});

% Reference deconvolution
hReferencePanel=uipanel(...
    'Parent',hTabCorrections,...
    'Title','Reference deconvolution',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0.0 1 0.7]);
%hRDLimitsText = 
uicontrol(...
    'Parent',hReferencePanel,...
    'Style','Text',...
    'String','Limits',...
    'FontWeight','bold',...
    'Units','normalized',...
    'horizontalalignment','c',...
    'Position',[0 0.82 0.16 0.1]);
hRDshowLRCheck = uicontrol(...
    'Parent',hReferencePanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Units','normalized',...
    'Value',0,...
    'TooltipString','Show the reference deconvolution limit lines',...
    'Position',[0.15 0.83 0.2 0.1],...
    'Callback',{ @RDshowLRCheck_Callback});
%hRDButtonLeft = 
uicontrol(...
    'Parent',hReferencePanel,...
    'Style','PushButton',...
    'String','Left',...
    'Units','normalized',...
    'TooltipString','Set left limit',...
    'Position',[0.02 0.6 0.12 0.15],...
    'Callback',{ @RDButtonLeft_Callback});
%hRDButtonRight = 
uicontrol(...
    'Parent',hReferencePanel,...
    'Style','PushButton',...
    'String','Right',...
    'Units','normalized',...
    'TooltipString','Set right limit',...
    'Position',[0.14 0.6 0.12 0.15],...
    'Callback',{ @RDButtonRight_Callback});
%hRDCentreText = 
uicontrol(...
    'Parent',hReferencePanel,...
    'Style','Text',...
    'String','Centre',...
    'FontWeight','bold',...
    'Units','normalized',...
    'horizontalalignment','c',...
    'Position',[0 0.35 0.16 0.1]);
hRDshowCheck = uicontrol(...
    'Parent',hReferencePanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Units','normalized',...
    'Value',0,...
    'TooltipString','Show the reference deconvolution center line',...
    'Position',[0.15 0.35 0.2 0.1],...
    'Callback',{ @RDshowCheck_Callback});
%hRDButtonSet = 
uicontrol(...
    'Parent',hTabCorrections,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Set the center of the peak',...
    'Position',[0.02 0.10 0.12 0.1],...
    'Callback',{ @RDButtonCentre_Callback});
%hRDButtonFind = 
uicontrol(...
    'Parent',hTabCorrections,...
    'Style','PushButton',...
    'String','Find',...
    'Units','normalized',...
    'TooltipString','Find the max. of the closest peak',...
    'Position',[0.14 0.10 0.12 0.1],...
    'Callback',{ @RDButtonFind_Callback});
%hRDTargetText = 
uicontrol(...
    'Parent',hTabCorrections,...
    'Style','Text',...
    'String','Lineshape',...
    'FontWeight','bold',...
    'Units','normalized',...
    'horizontalalignment','c',...
    'Position',[0.28 0.5 0.30 0.1]);
%hTextLbRD=
uicontrol(...
    'Parent',hTabCorrections,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.3 0.38 0.06 0.1 ],...
    'String','Lw:' );
hEditLbRD=uicontrol(...
    'Parent',hTabCorrections,...
    'Style','edit',...
    'Visible','On',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'Enable','Off',...
    'TooltipString','Enter the lorentzian width (Hz)',...
    'Max',1,...
    'Position',[0.38 0.4 0.1 0.1 ],...
    'CallBack', { @EditLbRD_Callback});
hCheckLbRD=uicontrol(...
    'Parent',hTabCorrections,...
    'Style','checkbox',...
    'Units','Normalized',...
    'Value',0,...
    'TooltipString','Use the lorentzian function',...
    'Position',[0.5 0.4 0.05 0.1 ],...
    'CallBack', { @CheckLbRD_Callback} );
%hTextGwRD=
uicontrol(...
    'Parent',hTabCorrections,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.3 0.22 0.07 0.1 ],...
    'String','Gw:' );
hEditGwRD=uicontrol(...
    'Parent',hTabCorrections,...
    'Style','edit',...
    'Visible','On',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'Enable','Off',...
    'TooltipString','Enter the gaussian width (Hz)',...
    'Max',1,...
    'Position',[0.38 0.25 0.1 0.1 ],...
    'CallBack', { @EditGwRD_Callback});
hCheckGwRD=uicontrol(...
    'Parent',hTabCorrections,...
    'Style','checkbox',...
    'Units','Normalized',...
    'Value',0,...
    'Enable','on',...
    'TooltipString','Use the gaussian function',...
    'Position',[0.5 0.25 0.05 0.1 ],...
    'CallBack', { @CheckGwRD_Callback} );
%hRDButtonFiddle = 
uicontrol(...
    'Parent',hTabCorrections,...
    'Style','PushButton',...
    'String','FIDDLE',...
    'Units','normalized',...
    'TooltipString','Apply the reference deconvolution',...
    'Position',[0.33 0.02 0.2 0.15],...
    'Callback',{ @RDButtonFiddle_Callback});
hBGroupPeak=uibuttongroup(...
    'Parent',hTabCorrections,...
    'Visible','On',...
    'Title','Peak',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.65 0.05 0.3 0.40 ]);
hRadio1Peak1 = uicontrol(...
    'Parent',hBGroupPeak,...
    'Style','RadioButton',...
    'String','Singlet',...
    'TooltipString','Use a singlet as reference signal',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.2]);
hRadio2Peak2 = uicontrol(...
    'Parent',hBGroupPeak,...
    'Style','RadioButton',...
    'String','TSP',...
    'TooltipString','Use trimethylsilylpropanoate (TSP-d4) as reference signal',...
    'Units','normalized',...
    'Position',[0.05 0.5 0.9 0.2]);
hRadio2Peak3 = uicontrol(...
    'Parent',hBGroupPeak,...
    'Style','RadioButton',...
    'String','TMS',...
    'TooltipString','Use tetramethylsilane (TMS) as reference signal',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.2]);
hRadio2Peak4 = uicontrol(...
    'Parent',hBGroupPeak,...
    'Style','RadioButton',...
    'String','DSS',...
    'TooltipString','Use trimethylsilylpropanesulfonate (DSS-d6) as reference signal',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.2]);
%% ---------Array tab

% Spectrum
hFlipPanelSpec=uipanel(...
    'Parent',hTabArray,...
    'Title','Spectrum',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'ForegroundColor','Black',...
    'Units','Normalized',...
    'Position',[0.2,0.77,0.5,0.22]);
hTextFlipSpec=uicontrol(...
    'Parent',hFlipPanelSpec,...
    'Style','Text',...
    'Units','Normalized',...
    'horizontalalignment','left',...
    'String','/ 0',...
    'Position',[0.55 0.05 0.4 0.6 ]);
hEditFlipSpec=uicontrol(...
    'Parent',hFlipPanelSpec,...
    'Style','edit',...
    'Units','Normalized',...
    'BackgroundColor','w',...
    'String',1,...
    'Position',[0.4 0.25 0.13 0.5 ],...
    'CallBack', { @EditFlipSpec_Callback});
%hButtonFlipPlusSpec = 
uicontrol(...
    'Parent',hFlipPanelSpec,...
    'Style','PushButton',...
    'String','+1',...
    'Units','normalized',...
    'TooltipString','Next spectrum in the array',...
    'Position',[0.75 0.25 0.15 0.5],...
    'Callback',{ @ButtonFlipPlusSpec_Callback});
%hButtonFlipMinusSpec = 
uicontrol(...
    'Parent',hFlipPanelSpec,...
    'Style','PushButton',...
    'String','-1',...
    'Units','normalized',...
    'TooltipString','Previous spectrum in the array',...
    'Position',[0.05 0.25 0.15 0.5],...
    'Callback',{ @ButtonFlipMinusSpec_Callback});

% Array 1
hFlipPanel=uipanel(...
    'Parent',hTabArray,...
    'Title','Array 1 (e.g. gradients)',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'ForegroundColor','Black',...
    'Units','Normalized',...
    'Position',[0.2,0.52,0.5,0.22]);
hTextFlip=uicontrol(...
    'Parent',hFlipPanel,...
    'Style','Text',...
    'Units','Normalized',...
    'String','/ 0',...
    'horizontalalignment','left',...
    'Position',[0.55 0.05 0.4 0.6 ]);
hEditFlip=uicontrol(...
    'Parent',hFlipPanel,...
    'Style','edit',...
    'Units','Normalized',...
    'BackgroundColor','w',...
    'String',1,...
    'Position',[0.4 0.25 0.13 0.5  ],...
    'CallBack', { @EditFlip_Callback});
%hButtonFlipPlus = 
uicontrol(...
    'Parent',hFlipPanel,...
    'Style','PushButton',...
    'String','+1',...
    'Units','normalized',...
    'TooltipString','Next spectrum in the array',...
    'Position',[0.75 0.2 0.15 0.5],...
    'Callback',{ @ButtonFlipPlus_Callback});
%hButtonFlipMinus = 
uicontrol(...
    'Parent',hFlipPanel,...
    'Style','PushButton',...
    'String','-1',...
    'Units','normalized',...
    'TooltipString','Previous spectrum in the array',...
    'Position',[0.05 0.25 0.15 0.5],...
    'Callback',{ @ButtonFlipMinus_Callback});

% Array 2
hFlipPanel2=uipanel(...
    'Parent',hTabArray,...
    'Title','Array 2 (e.g. vdlist)',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'ForegroundColor','Black',...
    'Units','Normalized',...
    'Position',[0.2,0.27,0.5,0.22]);
hTextFlip2=uicontrol(...
    'Parent',hFlipPanel2,...
    'Style','Text',...
    'Units','Normalized',...
    'horizontalalignment','left',...
    'String','/ 0',...
    'Position',[0.55 0.05 0.4 0.6 ]);
hEditFlip2=uicontrol(...
    'Parent',hFlipPanel2,...
    'Style','edit',...
    'Units','Normalized',...
    'BackgroundColor','w',...
    'String',1,...
    'Position',[0.4 0.15 0.13 0.5 ],...
    'CallBack', { @EditFlip2_Callback});
%hButtonFlipPlus2 = 
uicontrol(...
    'Parent',hFlipPanel2,...
    'Style','PushButton',...
    'String','+1',...
    'Units','normalized',...
    'TooltipString','Next spectrum in the array',...
    'Position',[0.75 0.25 0.15 0.5],...
    'Callback',{ @ButtonFlipPlus2_Callback});
%hButtonFlipMinus2 = 
uicontrol(...
    'Parent',hFlipPanel2,...
    'Style','PushButton',...
    'String','-1',...
    'Units','normalized',...
    'TooltipString','Previous spectrum in the array',...
    'Position',[0.05 0.25 0.15 0.5],...
    'Callback',{ @ButtonFlipMinus2_Callback});

% Array 3
hFlipPanel3=uipanel(...
    'Parent',hTabArray,...
    'Title','Array 3 (e.g. vclist)',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'ForegroundColor','Black',...
    'Units','Normalized',...
    'Position',[0.2,0.02,0.5,0.22]);
hTextFlip3=uicontrol(...
    'Parent',hFlipPanel3,...
    'Style','Text',...
    'Units','Normalized',...
    'horizontalalignment','left',...
    'String','/ 0',...
    'Position',[0.55 0.05 0.4 0.6 ]);
hEditFlip3=uicontrol(...
    'Parent',hFlipPanel3,...
    'Style','edit',...
    'Units','Normalized',...
    'BackgroundColor','w',...
    'String',1,...
    'Position',[0.4 0.25 0.13 0.5 ],...
    'CallBack', { @EditFlip3_Callback});
%hButtonFlipPlus3 = 
uicontrol(...
    'Parent',hFlipPanel3,...
    'Style','PushButton',...
    'String','+1',...
    'Units','normalized',...
    'TooltipString','Next spectrum in the array',...
    'Position',[0.75 0.25 0.15 0.5],...
    'Callback',{ @ButtonFlipPlus3_Callback});
%hButtonFlipMinus3 = 
uicontrol(...
    'Parent',hFlipPanel3,...
    'Style','PushButton',...
    'String','-1',...
    'Units','normalized',...
    'TooltipString','Previous spectrum in the array',...
    'Position',[0.05 0.25 0.15 0.5],...
    'Callback',{ @ButtonFlipMinus3_Callback});
%% ---------Prune tab

% Exclude regions
hExcludePanel=uipanel(...
    'Parent',hTabPrune,...
    'Title','Exclude regions',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.5 0.3 0.45 ]); 
hExcludeShow = uicontrol(...
    'Parent',hExcludePanel,...
    'Style','Checkbox',...
    'String','Use',...
    'Units','normalized',...
    'Position',[0.3 0.2 0.4 0.3],...
    'Callback',{ @ExcludeShow_Callback});
%hClearExcludeButton = 
uicontrol(...
    'Parent',hExcludePanel,...
    'Style','PushButton',...
    'String','Clear',...
    'Units','normalized',...
    'TooltipString','Clear the marked regions',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback',{ @ClearExcludeButton_Callback});
%hSetExcludeButton = 
uicontrol(...
    'Parent',hExcludePanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Mark the regions to exclude from analysis',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback',{ @SetExcludeButton_Callback});

% Pure arrays
hPrunePanel=uipanel(...
    'Parent',hTabPrune,...
    'Title','Prune arrays',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.15 0.6 0.8 ]);

%hTextNgrad=
uicontrol(...
    'Parent',hPrunePanel,...
    'Style','text',...
    'String','Array 1',...
    'Units','Normalized',...
    'Position',[0.35 0.8 0.8 0.11 ],...
    'horizontalalignment','l');
hEditNgrad=uicontrol(...
    'Parent',hPrunePanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString',...
    'List (semicolon or space separated) array element(s) to exclude from further analysis',...
    'Units','Normalized',...
    'Position',[0.2 0.7 0.4 0.13 ],...
    'CallBack', { @EditNgrad_Callback});
hNgradUse = uicontrol(...
    'Parent',hPrunePanel,...
    'Style','Checkbox',...
    'String','Use',...
    'TooltipString','Turn on/off pruning',...
    'Units','normalized',...
    'Position',[0.7 0.7 0.15 0.15]);%,...
%   'Callback',{ @NgradUse_Callback});

%hTextArray2=
uicontrol(...
    'Parent',hPrunePanel,...
    'Style','text',...
    'String','Array 2',...
    'Units','Normalized',...
    'Position',[0.35 0.5 0.8 0.11 ],...
    'horizontalalignment','l');
hEditArray2=uicontrol(...
    'Parent',hPrunePanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString',...
    'List (semicolon or space separated) array element(s) to exclude from further analysis',...
    'Units','Normalized',...
    'Position',[0.2 0.4 0.4 0.13 ],...
    'CallBack', { @EditArray2_Callback});
hArray2Use = uicontrol(...
    'Parent',hPrunePanel,...
    'Style','Checkbox',...
    'String','Use',...
    'TooltipString','Turn on/off pruning',...
    'Units','normalized',...
    'Position',[0.7 0.4 0.15 0.15]);

%hTextArray3=
uicontrol(...
    'Parent',hPrunePanel,...
    'Style','text',...
    'String','Array 3',...
    'Units','Normalized',...
    'Position',[0.35 0.2 0.8 0.11 ],...
    'horizontalalignment','l');
hEditArray3=uicontrol(...
    'Parent',hPrunePanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString',...
    'List (semicolon or space separated) array element(s) to exclude from further analysis',...
    'Units','Normalized',...
    'Position',[0.2 0.1 0.4 0.13 ],...
    'CallBack', { @EditArray3_Callback});
hArray3Use = uicontrol(...
    'Parent',hPrunePanel,...
    'Style','Checkbox',...
    'String','Use',...
    'TooltipString','Turn on/off pruning',...
    'Units','normalized',...
    'Position',[0.7 0.1 0.15 0.15]);
%% ---------Linear Prediction tab
% forward or backwards linear prediction
global LP

LP.hBGroupLPOpt1=uibuttongroup(...
    'Parent',hLP,...
    'Title','Linear Prediction type',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.05,0.45,0.25,0.5]);
LP.hRadio1LPOpt1 = uicontrol(...
    'Parent',LP.hBGroupLPOpt1,...
    'Style','RadioButton',...
    'String','forward',...
    'Units','normalized',...
    'TooltipString','forward linear prediction',...
    'Position',[0.05 0.7 0.9 0.3]);
LP.hRadio2LPOpt1 = uicontrol(...
    'Parent',LP.hBGroupLPOpt1,...
    'Style','RadioButton',...
    'String','backwards',...
    'TooltipString','Backwards linear prediction',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);


% forward or backwards linear prediction
LP.hBGroupLPOpt2=uibuttongroup(...
    'Parent',hLP,...
    'Title','Method',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.4,0.45,0.25,0.5]);
LP.hRadio1LPOpt2 = uicontrol(...
    'Parent',LP.hBGroupLPOpt2,...
    'Style','RadioButton',...
    'String','LPSVD',...
    'TooltipString','Linear prediction using single value decompostion',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
LP.hRadio2LPOpt2 = uicontrol(...
    'Parent',LP.hBGroupLPOpt2,...
    'Style','RadioButton',...
    'String','Matrix Pencil',...
    'TooltipString','Linear prediction using matrix pencil method',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);

% Parameters
LP.hGroupLPOpt3=uipanel(...
    'Parent',hLP,...
    'Title','Parameters',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.7 0.05 0.3 0.9 ]);

uicontrol(...
    'Parent',LP.hGroupLPOpt3,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','Black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.75 0.3 0.15 ],...
    'String','NCOEF' );

uicontrol(...
    'Parent',LP.hGroupLPOpt3,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','Black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.55 0.4 0.15 ],...
    'String','NPP' );

uicontrol(...
    'Parent',LP.hGroupLPOpt3,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','Black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.35 0.4 0.15 ],...
    'String','Basis points' );


LP.hEditNCOEF=uicontrol(...
    'Parent',LP.hGroupLPOpt3,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of LP coeffiecents / number of peaks ',...
    'Position',[0.65 0.82 0.3 0.13 ]);

LP.hEditNPP=uicontrol(...
    'Parent',LP.hGroupLPOpt3,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of points to predict',...
    'Position',[0.65 0.62 0.3 0.13 ]);

LP.hEditNPU=uicontrol(...
    'Parent',LP.hGroupLPOpt3,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of points of FID to use for prediction typically 0.75*N',...
    'Position',[0.65 0.42 0.3 0.13 ]);

uicontrol(...
    'Parent',hLP,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Apply linear prediction based on current parameters',...
    'Position',[0.05 0.05 0.4 0.3],...
    'Callback', {@linpredict});

uicontrol(...
    'Parent',hLP,...
    'Style','PushButton',...
    'String','Estimate',...
    'Units','normalized',...
    'TooltipString','Estimate parameters',...
    'Position',[0.7 0.05 0.3 0.3],...
    'Callback', {@(eventdata,handles) LPestimate});
%% ---------Pure shift tab

% Process
hPureshiftProcessPanel=uipanel(...
    'Parent',hTabPureshift,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.02 0.05 0.4 0.9 ]);
%hButtonPureshiftConvert=
uicontrol(...
    'Parent',hPureshiftProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Convert to pure shift spectrum',...
    'Position',[0.2 0.7 0.6 0.15 ],...
    'String','Convert',...
    'CallBack', { @PureshiftConvert_Callback});
%hButtonUnConvertPureshift=
uicontrol(...
    'Parent',hPureshiftProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Retrieve original data',...
    'Position',[0.2 0.5 0.6 0.15 ],...
    'String','UnConvert',...
    'CallBack', { @UnConvertPureshift_Callback});
%hButtonEstimatePureshift=
uicontrol(...
    'Parent',hPureshiftProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Estimate pure shift parameters',...
    'Position',[0.2 0.1 0.6 0.15 ],...
    'String','Estim. Param.',...
    'CallBack', { @EstimatePureshift_Callback});

% Parameters
hPureshiftSetupPanel=uipanel(...
    'Parent',hTabPureshift,...
    'Title','Parameters',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.45 0.05 0.52 0.9 ]);
%hTextnfid=
uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','Black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.75 0.3 0.15 ],...
    'String','Chunks' );
hEditnfid=uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number if increments (FIDs) to use for the pure shift FID',...
    'Max',1,...
    'Position',[0.6 0.82 0.3 0.13 ],...
    'CallBack', { @Editnfid_Callback});
%hTextnfid=
uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','Black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.58 0.3 0.15 ],...
    'String','Chunk duration (ms)' );
hEditfiddur=uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Incrementing time (ms)',...
    'Max',1,...
    'Position',[0.6 0.62 0.3 0.13 ],...
    'CallBack', { @Editfiddur_Callback});
%hTextfiddur=
uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.35 0.35 0.15  ],...
    'String','Chunk points' );
hEditnpoints=uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of points to use for each increment',...
    'Max',1,...
    'Position',[0.6 0.42 0.3 0.13 ],...
    'CallBack', { @Editnpoints_Callback});
%hTextnfirstfidpoints=
uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.15 0.3 0.15  ],...
    'String','First Chunk' );
hEditnfirstfidpoints=uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of points to use for the first increment',...
    'Max',1,...
    'Position',[0.6 0.22 0.3 0.13 ],...
    'CallBack', { @Editfirstfidpoints_Callback});
%hTextDropPoints=
uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','black',...
    'horizontalalignment','left',...
    'Position',[0.1 0.0 0.3 0.1  ],...
    'String','Drop points' );
hEditDropPoints=uicontrol(...
    'Parent',hPureshiftSetupPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of initial points to remove from each increment',...
    'Max',1,...
    'Position',[0.6 0.02 0.3 0.13  ],...
    'CallBack', { @EditDropPoints_Callback});
%% ---------Misc tab

% Play FID
hPlayFIDPanel=uipanel(...
    'Parent',hTabMiscLeft,...
    'Title','Play FID',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.05,0.45,0.25,0.5]);
%hButtonPlayCurrentFid = 
uicontrol(...
    'Parent',hPlayFIDPanel,...
    'Style','PushButton',...
    'String','One',...
    'Units','Normalized',...
    'TooltipString','Listen to the displayed FID',...
    'Position',[0.2 0.5 0.6 0.4],...
    'Callback',{ @ButtonPlayCurrentFid_Callback});
%hButtonPlayAllFid = 
uicontrol(...
    'Parent',hPlayFIDPanel,...
    'Style','PushButton',...
    'String','All',...
    'Units','Normalized',...
    'TooltipString','Listen to the all the FIDs in the experiment',...
    'Position',[0.2 0.1 0.6 0.4],...
    'Callback',{ @ButtonPlayAllFid_Callback});

% Data state
hStatePanel=uipanel(...
    'Parent',hTabMiscLeft,...
    'Title','Data state',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35,0.45,0.35,0.5]);
%hSaveButton = 
uicontrol(...
    'Parent',hStatePanel,...
    'Style','ToggleButton',...
    'String','Save',...
    'Units','normalized',...
    'TooltipString','Save data with current processing parameters',...
    'Position',[0.05 0.52 0.9 0.44],...
    'Callback', { @SaveButton_Callback});
%hSaveButton = 
uicontrol(...
    'Parent',hStatePanel,...
    'Style','ToggleButton',...
    'String','Recall',...
    'Units','normalized',...
    'TooltipString','Recall previosly saved data',...
    'Position',[0.05 0.04 0.9 0.44],...
    'Callback', { @RecallButton_Callback});
%% ---------Info tab
hMessagesPanel=uipanel(...
    'Parent',hTabMessages,...
    'Title','',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.0,1.0,1.0]);
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',NmrData.MessageText)


%%  Tab group Advanced Processing
hTabGroupAdvanced=uitabgroup(...
    'Parent',hMainFigure,...
    'Units','Normalized',...
    'Position',[0.4,0.0,0.6,0.35]);
hTabAnalysis=uitab(...
    'Parent',hTabGroupAdvanced,...
    'Title','Analysis',...
    'TooltipString','Basic spectral analysis, alignment, integration and estimation tools',...
    'Units','Normalized');
hTabDiffusion=uitab(...
    'Parent',hTabGroupAdvanced,...
    'Title','Diffusion',...
    'TooltipString','Methods to analyse diffusion NMR data',...
    'Units','Normalized');
hTabRealaxation=uitab(...
    'Parent',hTabGroupAdvanced,...
    'Title','Relaxation',...
    'TooltipString','Methods to analyse relaxation NMR data',...
    'Units','Normalized');
hTabMultiway=uitab(...
    'Parent',hTabGroupAdvanced,...
    'Title','Multiway',...
    'TooltipString','Methods to analyse multiway NMR data',...
    'Units','Normalized');
hTabMiscRight=uitab(...
    'Parent',hTabGroupAdvanced,...
    'Title','Misc',...
    'TooltipString','Miscellaneous analysis tools',...
    'Units','Normalized');
hTabChemometrics=uitab(...
    'Parent',hTabGroupAdvanced,...
    'Title','Chemometrics',...
    'TooltipString','Chemometrics tools for data analysis',...
    'Units','Normalized');

hTabGrouPDiffusion=uitabgroup(...
    'Parent',hTabDiffusion,...
    'Units','Normalized',...
    'Position',[0.0,0.0,1,1]);
hTabDOSY=uitab(...
    'Parent',hTabGrouPDiffusion,...
    'Title','DOSY',...
    'TooltipString','Diffusion-Ordered SpectroscopY method',...
    'Units','Normalized');
hTabSCORE=uitab(...
    'Parent',hTabGrouPDiffusion,...
    'Title','SCORE',...
    'TooltipString','Speedy COmponent REsolution method',...
    'Units','Normalized');
hTabLOCODOSY=uitab(...
    'Parent',hTabGrouPDiffusion,...
    'Title','LOCODOSY',...
    'TooltipString','LOcal COvariance DOSY method',...
    'Units','Normalized');
hTabILT=uitab(...
    'Parent',hTabGrouPDiffusion,...
    'Title','ILT',...
    'TooltipString','Inverse Laplace Transformation method',...
    'Units','Normalized');
hTabDECRA=uitab(...
    'Parent',hTabGrouPDiffusion,...
    'Title','DECRA',...
    'TooltipString','Direct Exponential Curve Resolution Algorithm method',...
    'Units','Normalized');


hTabGrouPRealaxation=uitabgroup(...
    'Parent',hTabRealaxation,...
    'Units','Normalized',...
    'Position',[0.0,0.0,1,1]);
hTabT1=uitab(...
    'Parent',hTabGrouPRealaxation,...
    'Title','ROSY',...
    'TooltipString','Relaxation-Ordered SpectroscopY method',...
    'Units','Normalized');
hTabRSCORE=uitab(...
    'Parent',hTabGrouPRealaxation,...
    'Title','RSCORE',...
    'TooltipString','Relaxation Speedy COmponent REsolution method',...
    'Units','Normalized');
% hTabRILT=uitab(...
%     'Parent',hTabGrouPRealaxation,...
%     'Title','RILT',...
%     'TooltipString','Relaxation Inverse Laplace Transformation method',...
%     'Units','Normalized');

hTabGrouPAnalysis=uitabgroup(...
    'Parent',hTabAnalysis,...
    'Units','Normalized',...
    'Position',[0.0,0.0,1,1]);
hTabAnal=uitab(...
    'Parent',hTabGrouPAnalysis,...
    'Title','Analyse',...
    'TooltipString','Basic spectral analysis tools',...
    'Units','Normalized');
hTabAlign=uitab(...
    'Parent',hTabGrouPAnalysis,...
    'Title','Align',...
    'TooltipString','Align spectral array',...
    'Units','Normalized');
hTabIntegrate=uitab(...
    'Parent',hTabGrouPAnalysis,...
    'Title','Integrate',...
    'TooltipString','Define, correct and normalise integrals',...
    'Units','Normalized');
hTabSNR=uitab(...
    'Parent',hTabGrouPAnalysis,...
    'Title','Measure SNR',...
    'TooltipString','Measure signal-to-noise ratio',...
    'Units','Normalized');
hTabSEGWE=uitab(...
    'Parent',hTabGrouPAnalysis,...
    'Title','Diffusion estimation',...
    'TooltipString','Estimation for D to MW and rH (and vice versa)',...
    'Units','Normalized');

hTabGrouPMultiway=uitabgroup(...
    'Parent',hTabMultiway,...
    'Units','Normalized',...
    'Position',[0.0,0.0,1,1]);
hTabPARAFAC=uitab(...
    'Parent',hTabGrouPMultiway,...
    'Title','PARAFAC',...
    'TooltipString','PARAllel FACtorial method',...
    'Units','Normalized');
hTabSLICING=uitab(...
    'Parent',hTabGrouPMultiway,...
    'Title','Slicing',...
    'TooltipString','Slicing method',...
    'Units','Normalized');

hTabGrouPMisc=uitabgroup(...
    'Parent',hTabMiscRight,...
    'Units','Normalized',...
    'Position',[0.0,0.0,1,1]);
hTabMacros=uitab(...
    'Parent',hTabGrouPMisc,...
    'Title','Macros',...
    'TooltipString','Run arbitrary Matlab scripts inside the GNAT environment',...
    'Units','Normalized');

hTabGroupChemometrics=uitabgroup(...
    'Parent',hTabChemometrics,...
    'Units','Normalized',...
    'Position',[0.0,0.0,1,1]);

hTabPCA=uitab(...
    'Parent',hTabGroupChemometrics,...
    'Title','PCA',...
    'TooltipString','Principal Component Analysis',...
    'Units','Normalized');
hTabGroupPCA=uitabgroup(...
    'Parent',hTabPCA,...
    'Units','Normalized',...
    'Position',[0.38 0 1 1]);

hTabPLSDA=uitab(...
    'Parent',hTabGroupChemometrics,...
    'Title','PLS-DA',...
    'TooltipString','Partial Least Squares - Discrimination Analysis',...
    'Units','Normalized');
hTabGroupPLSDA=uitabgroup(...
    'Parent',hTabPLSDA,...
    'Units','Normalized',...
    'Position',[0.32 0 1 1]);

hTabOPLSDA=uitab(...
    'Parent',hTabGroupChemometrics,...
    'Title','OPLS-DA',...
    'TooltipString','Orthogonal projections to latent structures',...
    'Units','Normalized');
hTabGroupOPLSDA=uitabgroup(...
    'Parent',hTabOPLSDA,...
    'Units','Normalized',...
    'Position',[0.38 0 1 1]);

hTabIcoshift=uitab(...
    'Parent',hTabGroupChemometrics,...
    'Title','ICOSHIFT',...
    'TooltipString','Interval Correlation Optimized SHIFTing method',...
    'Units','Normalized');

hTabSTOCSY=uitab(...
    'Parent',hTabGroupChemometrics,...
    'Title','STOCSY',...
    'TooltipString','Statistical Total Correlation Spectroscopy',...
    'Units','Normalized');

hTabNeuralNetwork=uitab(...
    'Parent',hTabGroupAdvanced,...
    'Title','Neural Network',...
    'TooltipString','Neural Network training and Pure shift Processing',...
    'Units','Normalized');

%% ---------DOSY

% Process
hDOSYProcessPanel=uipanel(...
    'Parent',hTabDOSY,...
    'Title','Process',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessDOSYButton = 
uicontrol(...
    'Parent',hDOSYProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @dodosy});
%hReplotDOSYButton = 
uicontrol(...
    'Parent',hDOSYProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @plotdosy});

% Peal pick
hBGroupDOSYOpt1=uibuttongroup(...
    'Parent',hTabDOSY,...
    'Title','Peak pick',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.5 0.3 0.45 ]);
hRadio1DOSYOpt1 = uicontrol(...
    'Parent',hBGroupDOSYOpt1,...
    'Style','RadioButton',...
    'String','Peak pick',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2DOSYOpt1 = uicontrol(...
    'Parent',hBGroupDOSYOpt1,...
    'Style','RadioButton',...
    'String','All frequencies',...
    'Units','normalized',...
    'Position',[0.05 0.35 0.9 0.3]);
hRadio3DOSYOpt1 = uicontrol(...
    'Parent',hBGroupDOSYOpt1,...
    'Style','RadioButton',...
    'String','Integrals',...
    'Units','normalized',...
    'Position',[0.05 0.0 0.9 0.3]);

% Fit equation
hBGroupDOSYOpt2=uibuttongroup(...
    'Parent',hTabDOSY,...
    'Visible','On',...
    'Title','Fit equation',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.68 0.05 0.3 0.45 ]);
hRadio1DOSYOpt2 = uicontrol(...
    'Parent',hBGroupDOSYOpt2,...
    'Style','RadioButton',...
    'String','Exponential',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2DOSYOpt2 = uicontrol(...
    'Parent',hBGroupDOSYOpt2,...
    'Style','RadioButton',...
    'String','NUG',...
    'Units','normalized',...
    'Position',[0.05 0.25 0.9 0.3]);

% Fit type
hBGroupDOSYOpt3=uibuttongroup(...
    'Parent',hTabDOSY,...
    'Title','Fit type',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.05 0.3 0.45 ],...
    'SelectionChangeFcn', { @FitType_Callback});
hRadio1DOSYOpt3 = uicontrol(...
    'Parent',hBGroupDOSYOpt3,...
    'Style','RadioButton',...
    'String','Monoexponential',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
%hRadio2DOSYOpt3 = 
uicontrol(...
    'Parent',hBGroupDOSYOpt3,...
    'Style','RadioButton',...
    'String','Multiexponential',...
    'Units','normalized',...
    'Position',[0.05 0.25 0.9 0.3]);

% Multiexponential
hBMultiexpPanel=uipanel(...
    'Parent',hTabDOSY,...
    'Title','Multiexponential',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.05 0.3 0.45 ]);
hEditMultexp=uicontrol(...
    'Parent',hBMultiexpPanel,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Maximun number of components per peak',...
    'Max',1,...
    'Position',[0.1 0.6 0.2 0.25 ],...
    'CallBack', { @EditMultexp_Callback});
%hTextMultexp=
uicontrol(...
    'Parent',hBMultiexpPanel,...
    'Style','text',...
    'String','Exponentials',...
    'Units','Normalized',...
    'Position',[0.37 0.57 0.55 0.25 ],...
    'horizontalalignment','l');
hEditTries=uicontrol(...
    'Parent',hBMultiexpPanel,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of randomised starting guesses per peak',...
    'Max',1,...
    'Position',[0.1 0.2 0.2 0.25 ],...
    'CallBack', { @EditTries_Callback});
%hTextTries=
uicontrol(...
    'Parent',hBMultiexpPanel,...
    'Style','text',...
    'String','Random repeats',...
    'Units','Normalized',...
    'Position',[0.37 0.15 0.55 0.25 ],...
    'horizontalalignment','l');

% DOSY plot
hBPlotPanel=uipanel(...
    'Parent',hTabDOSY,...
    'Visible','On',...
    'Title','DOSY plot',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.68 0.5 0.3 0.45 ]);
hEditDmin=uicontrol(...
    'Parent',hBPlotPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Minimum value of diffusion coefficient displayed',...
    'Max',1,...
    'Position',[0.1 0.7 0.2 0.25 ]);%,...
    %'CallBack', { @EditDmin_Callback});
%hTextDmin=
uicontrol(...
    'Parent',hBPlotPanel,...
    'Style','text',...
    'String','D Min.',...
    'Units','Normalized',...
    'Position',[0.37 0.66 0.2 0.25 ],...
    'horizontalalignment','l');
hEditDmax=uicontrol(...
    'Parent',hBPlotPanel,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Maximum value of diffusion coefficient displayed',...
    'Max',1,...
    'Position',[0.1 0.4 0.2 0.25 ]);%,...
   % 'CallBack', { @EditDmax_Callback});
hCheckDmax=uicontrol(...
    'Parent',hBPlotPanel,...
    'Style','checkbox',...
    'Visible','On',...
    'Enable','On',...
    'String','Auto',...
    'Units','Normalized',...
    'TooltipString','Automatically set D max.',...
    'Value',1,...
    'Position',[0.7 0.42 0.35 0.25 ],...
    'CallBack', { @CheckDmax_Callback});
%hTextDmax=
uicontrol(...
    'Parent',hBPlotPanel,...
    'Style','text',...
    'String','D Max.',...
    'Units','Normalized',...
    'Position',[0.37 0.35 0.2 0.25 ],...
    'horizontalalignment','l');
hEditDres=uicontrol(...
    'Parent',hBPlotPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'Max',1,...
    'TooltipString','Number of data points in the diffusion dimension',...
    'Position',[0.1 0.05 0.2 0.25 ]);%,...
   % 'CallBack', { @EditDres_Callback});
%hTextDres=
uicontrol(...
    'Parent',hBPlotPanel,...
    'Style','text',...
    'String','Digitization',...
    'Units','Normalized',...
    'Position',[0.37 0.02 0.5 0.25 ],...
    'horizontalalignment','l');
%% ---------SCORE (diffusion)

% Process
hSCOREProcessPanel=uipanel(...
    'Parent',hTabSCORE,...
    'Title','Process',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessSCOREButton = 
uicontrol(...
    'Parent',hSCOREProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @doscore});
%hReplotSCOREButton = 
uicontrol(...
    'Parent',hSCOREProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @plotscore});
%hPubplotButton = 
uicontrol(...
    'Parent',hSCOREProcessPanel,...
    'Style','PushButton',...
    'String','Publ. plot',...
    'Enable','On',...
    'Units','normalized',...
    'TooltipString','Plot the data from the last fit in publication format',...
    'Position',[0.05 0.1 0.4 0.3],...
    'Callback', { @pubplotscore});

%Components
hSCORENcompPanel=uipanel(...
    'Parent',hTabSCORE,...
    'Title','Components',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.5 0.3 0.45 ]);
hEditNcompSCORE=uicontrol(...
    'Parent',hSCORENcompPanel,...
    'Style','edit',...
    'String',2,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of (estimated) components to search for in the mixture spectrum',...
    'Units','Normalized',...
    'Position',[0.4 0.3 0.15 0.3 ]);%,...
    %'CallBack', { @EditNcompSCORE_Callback});
%hTextNcompSCORE=
uicontrol(...
    'Parent',hSCORENcompPanel,...
    'Style','text',...
    'String',2,...
    'String','Fitted components:',...
    'Units','Normalized',...
    'Position',[0.2 0.7 0.6 0.2 ],...
    'horizontalalignment','c');

% Plots
hBpanelSCOREplot=uipanel(...
    'Parent',hTabSCORE,...
    'Title','Plots',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.78 0.05 0.2 0.45 ]);
hPlotDiag = uicontrol(...
    'Parent',hBpanelSCOREplot,...
    'Style','Checkbox',...
    'String','Diagnostics',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);

% Fit equation
hBGroupSCOREOpt1=uibuttongroup(...
    'Parent',hTabSCORE,...
    'Title','Fit equation',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.523 0.05 0.2 0.45 ]);
hRadio1SCOREOpt1 = uicontrol(...
    'Parent',hBGroupSCOREOpt1,...
    'Style','RadioButton',...
    'String','Exponential',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2SCOREOpt1 = uicontrol(...
    'Parent',hBGroupSCOREOpt1,...
    'Style','RadioButton',...
    'String','NUG',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);

%D guess
hBGroupSCOREOpt2=uibuttongroup(...
    'Parent',hTabSCORE,...
    'Title','D guess',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.245840630472855,0.05,0.250437828371278,0.45],...
    'SelectionChangeFcn', {@Dguess_Callback,});
hRadio1SCOREOpt2 = uicontrol(...
    'Parent',hBGroupSCOREOpt2,...
    'Style','RadioButton',...
    'String','Fit',...
    'Units','normalized',...
    'Position',[0.05 0.71 0.9 0.3]);
hRadio2SCOREOpt2 = uicontrol(...
    'Parent',hBGroupSCOREOpt2,...
    'Style','RadioButton',...
    'String','Random',...
    'Units','normalized',...
    'Position',[0.05 0.34 0.9 0.3]);
hRadio3SCOREOpt2 = uicontrol(...                                            % Added 'value input' option in the GNAT interface for the number of guesses
    'Parent',hBGroupSCOREOpt2,...
    'Style','edit',...
    'Enable','Off',...
    'String',100,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of repeats',...
    'Units','Normalized',...
    'Position',[0.763299138176299,0.35721649484536,0.202127659574467,0.240515463917525]);
% hRadio4SCOREOpt2 = uicontrol(...                                            % Added 'value input' option in the GNAT interface of the fixed diffusion coefficient
%     'Parent',hBGroupSCOREOpt2,...
%     'Style','edit',...
%     'String',0,...
%     'BackgroundColor','w',...
%     'TooltipString',...
%     'Fixed diffusion coefficient',...
%     'Units','Normalized',...
%     'Position',[0.759751773049645,0.671649484536081,0.201063829787234,0.229175257731958]);
% 
% uicontrol(...
%     'Parent',hBGroupSCOREOpt2,...
%     'Style','text',...
%     'FontSize',6.5,...
%     'String','Fixed D-value(s)',...
%     'Units','Normalized',...
%     'Position',[0.399242652233878,0.719958800640879,0.360525550756838,0.153518108261574]);

uicontrol(...
    'Parent',hBGroupSCOREOpt2,...
    'Style','text',...
    'FontSize',8,...
    'String','Repeats',...
    'Units','Normalized',...
    'Position',[0.5,0.266765850308995,0.3,0.29451250020646]);

hRadio5SCOREOpt2 = uicontrol(...                                            % Added 'value input' option in the GNAT interface of the fixed diffusion coefficient
    'Parent',hBGroupSCOREOpt2,...
    'Style','edit',...
    'Enable','Off',...
    'String',0.1,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Standard deviation',...
    'Units','Normalized',...
    'Position',[0.766845996968601,0.053092783505152,0.201063829787234,0.229175257731958]);
uicontrol(...
    'Parent',hBGroupSCOREOpt2,...
    'Style','text',...
    'FontSize',8,...
    'String','STD',...
    'Units','Normalized',...
    'Position',[0.531684471107739,0.122568093385214,0.233380974231055,0.139741184965296]);

% Constraint
hBGroupSCOREOpt3=uibuttongroup(...
    'Parent',hTabSCORE,...
    'Visible','On',...
    'Title','Constraint',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.05 0.2 0.45]);
hRadio1SCOREOpt3 = uicontrol(...
    'Parent',hBGroupSCOREOpt3,...
    'Style','RadioButton',...
    'String','None',...
    'Units','normalized',...
    'Position',[0.05 0.6 0.9 0.3]);
hRadio2SCOREOpt3 = uicontrol(...
    'Parent',hBGroupSCOREOpt3,...
    'Style','RadioButton',...
    'String','Non-negative',...
    'Units','normalized',...
    'Position',[0.05 0.2 0.9 0.3]);

% Method
hBGroupSCOREOpt6=uibuttongroup(...
    'Parent',hTabSCORE,...
    'Visible','On',...
    'Title','Method',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.6591,0.5,0.3208,0.45],...
    'SelectionChangeFcn', {@Alfa_Callback,});
hRadio1SCOREOpt6 = uicontrol(...
    'Parent',hBGroupSCOREOpt6,...
    'Style','RadioButton',...
    'String','SCORE',...
    'Units','normalized',...
    'Position',[0.047235522420191,0.722086235583286,0.2759,0.3]);
hRadio2SCOREOpt6 = uicontrol(...
    'Parent',hBGroupSCOREOpt6,...
    'Style','RadioButton',...
    'String','OUTSCORE',...
    'Units','normalized',...
    'Position',[0.05,0.062129529211571,0.3754,0.3]);
%% COSCORE GUI CONTROL

    hRadio3SCOREOpt6 = uicontrol(...
    'Parent',hBGroupSCOREOpt6,...
    'Style','RadioButton',...
    'String','COSCORE',...
    'TooltipString',...
    'Combined OUTSCORE-SCORE method',...
    'Units','normalized',...
    'Position',[0.048180824405865,0.388322234826999,0.3403,0.3]);
hRadio4SCOREOpt6 = uicontrol(...                                            
    'Parent',hBGroupSCOREOpt6,...
    'Style','slider',...
    'Enable','Off',...
    'Value',50,...
    'Min',0,...
    'Max',100,...
    'SliderStep',[0.01 0.1],...
    'BackgroundColor','w',...
    'TooltipString',...
    '',...
    'Units','Normalized',...
    'Position',[0.624042025416089,0.320751314048024,0.2661,0.2],...
    'CallBack', {@SliderSCORE_Callback});
uicontrol(...
    'Parent',hBGroupSCOREOpt6,...
    'Style','text',...
    'String','weighting',...
    'FontSize',7,...
    'Units','Normalized',...
    'Position',[0.557987839925112,0.530308735110606,0.154076601434278,0.19]);
hRadio5SCOREOpt6 = uicontrol(...                                            
    'Parent',hBGroupSCOREOpt6,...
    'Style','edit',...
    'Enable','Off',...
    'String',50,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Weighting value for SCORE',...
    'Units','Normalized',...
    'Position',[0.700945275799815,0.53306956891662,0.123028829787377,0.1978],...
    'CallBack', {@EditSCORE_Callback});

uicontrol(...
    'Parent',hBGroupSCOREOpt6,...
    'Style','text',...
    'String','SCORE',...
    'FontName','Calibri Light',...
    'FontSize',6,...
    'Units','Normalized',...
    'Position',[0.887615346267947,0.337549725846096,0.11,0.15]);

uicontrol(...
    'Parent',hBGroupSCOREOpt6,...
    'Style','text',...
    'String','OUTSCORE',...
    'FontName','Calibri Light',...
    'FontSize',6,...
    'Units','Normalized',...
    'Position',[0.460646942967816,0.290214274910192,0.163614565878774,0.2]);

uicontrol(...
    'Parent',hBGroupSCOREOpt6,...
    'Style','text',...
    'String','(%)',...
    'FontSize',7,...
    'Units','Normalized',...
    'Position',[0.828128201256294,0.530308735110606,0.07643113410528,0.19]);
%% ---------LOCODOSY

%Process
hLOCODOSYProcessPanel=uipanel(...
    'Parent',hTabLOCODOSY,...
    'Visible','On',...
    'Title','Process',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessLOCODOSYButton = 
uicontrol(...
    'Parent',hLOCODOSYProcessPanel,...
    'Style','PushButton',...
    'Visible','On',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @LRRun_Callback});
%hReplotLOCODOSYButton = 
uicontrol(...
    'Parent',hLOCODOSYProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Visible','On',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @plotlocodosy});

% Segments
hPanelSelect=uipanel(...
    'Parent',hTabLOCODOSY,...
    'Units','Normalized',...
    'Visible','On',...
    'Position',[0.35 0.5 0.3 0.45 ],...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Title','Segment' );
%hLRInclude=
uicontrol(...
    'Parent',hPanelSelect,...
    'Style','pushbutton',...
    'Visible','On',...
    'String','Manual',...
    'Units','Normalized',...
    'TooltipString','Manually select processing windows',...
    'Position',[0.05 0.6 0.4 0.3],...
    'CallBack', { @LRInclude_Callback});
%hLRClear=
uicontrol(...
    'Parent',hPanelSelect,...
    'Style','pushbutton',...
    'Visible','On',...
    'String','Clear',...
    'Units','Normalized',...
    'Position',[0.05 0.1 0.4 0.3 ],...
    'CallBack', { @LRClear_Callback});
%hAutoInclude=
uicontrol(...
    'Parent',hPanelSelect,...
    'Style','pushbutton',...
    'String','Auto',...
    'Units','Normalized',...
    'TooltipString','Automatically select processing windows',...
    'Position',[0.55 0.6 0.4 0.3],...
    'CallBack', { @fpeakclusters});
hLRWindowsShow = uicontrol(...
    'Parent',hPanelSelect,...
    'Style','Checkbox',...
    'String','Show',...
    'Units','normalized',...
    'TooltipString','Display the marked regions',...
    'Position',[0.55 0.1 0.4 0.3],...
    'Callback',{ @LRWindowsShow_Callback});

% Settings
hPanelSettings=uipanel(...
    'Parent',hTabLOCODOSY,...
    'Units','Normalized',...
    'Position',[0.66 0 0.18 0.95 ],...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Title','Settings' );
%hTextDlimit=
uicontrol(...
    'Parent',hPanelSettings,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
     'Position',[0.1 0.84 0.3 0.1 ],...
    'horizontalalignment','l',...
    'String','Max. D' );
hEditDlimit=uicontrol(...
    'Parent',hPanelSettings,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The upper limit to D before a component is dismissed',...
    'Position',[0.6 0.86 0.3 0.1 ]);
%hTextDiffRes=
uicontrol(...
    'Parent',hPanelSettings,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.71 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String','Digitisation' );
hEditDiffRes=uicontrol(...
    'Parent',hPanelSettings,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The number of points plotted in the diffusion domain',...
    'Position',[0.6 0.73 0.3 0.1 ]);
%hTextVlimit=
uicontrol(...
    'Parent',hPanelSettings,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.58 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String','Win min %' );
hEditVlimit=uicontrol(...
    'Parent',hPanelSettings,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The minimum % of a window a component can represent',...
    'Position',[0.6 0.6 0.3 0.1 ]);
%hTextsderrmultiplier=
uicontrol(...
    'Parent',hPanelSettings,...
    'Style','text',...
    'String','Fuzz fact',...
    'Units','Normalized',...
    'Position',[0.1 0.46 0.5 0.1 ],...
    'horizontalalignment','l');
hEditsderrmultiplier=uicontrol(...
    'Parent',hPanelSettings,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Clustering fuzziness factor',...
    'Position',[0.6 0.47 0.3 0.1 ]);
%hTextSVDcutoff=
uicontrol(...
    'Parent',hPanelSettings,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.35 0.5 0.1],...
    'horizontalalignment','l',...
    'String','SVD cut' );
hEditSVDcutoff=uicontrol(...
    'Parent',hPanelSettings,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The required amount of variance explained by SVD components',...
    'Position',[0.6 0.35 0.3 0.1 ]);
%hTextmethodplots=
uicontrol(...
    'Parent',hPanelSettings,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.19 0.5 0.1],...
    'horizontalalignment','l',...
    'String','Seg. plots' );
hLRmethodplots = uicontrol(...
    'Parent',hPanelSettings,...
    'Style','Checkbox',...
    'Units','normalized',...
    'TooltipString','Display the processing results for each segment',...
    'Position',[0.6 0.2 0.3 0.1]);
%hTextUseClustering=
uicontrol(...
    'Parent',hPanelSettings,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.04 0.5 0.1],...
    'horizontalalignment','l',...
    'String','Clustering' );
% hUseClustering = uicontrol(...
%     'Parent',hPanelSettings,...
%     'Style','Checkbox',...
%     'Units','normalized',...
%     'TooltipString','Whether to use clustering or not after processing',...
%     'Position',[0.6 0.05 0.3 0.1]);

% Fit equation
hBGrouplocodosyOpt1=uibuttongroup(...
    'Parent',hTabLOCODOSY,...
    'Title','Fit equation',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.45 0.0 0.2 0.45 ]);
hRadio1locodosyOpt1 = uicontrol(...
    'Parent',hBGrouplocodosyOpt1,...
    'Style','RadioButton',...
    'String','Exponential',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2locodosyOpt1 = uicontrol(...
    'Parent',hBGrouplocodosyOpt1,...
    'Style','RadioButton',...
    'String','NUG',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);

% Method
hBGrouplocodosyalg=uibuttongroup(...
    'Parent',hTabLOCODOSY,...
    'Title','Method',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.235 0.0 0.2 0.45 ],...
    'SelectionChangeFcn',@LRAlgorithmChange_Callback);
hRadio1locodosyalg = uicontrol(...
    'Parent',hBGrouplocodosyalg,...
    'Style','RadioButton',...
    'String','SCORE',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3 ]);
hRadio2locodosyalg = uicontrol(...
    'Parent',hBGrouplocodosyalg,...
    'Style','RadioButton',...
    'String','DECRA',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.3]);
hRadio3locodosyalg = uicontrol(...
    'Parent',hBGrouplocodosyalg,...
    'Style','RadioButton',...
    'String','OUTSCORE',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);

% Processing
hBGroupRunType=uibuttongroup(...
    'Parent',hTabLOCODOSY,...
    'Title','Processing',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.0 0.2 0.45 ]);
hRadio2RunType = uicontrol(...
    'Parent',hBGroupRunType,...
    'Style','RadioButton',...
    'String','Automatic',...
    'TooltipString','Automatically determine number of components & process',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);
hRadio1RunType = uicontrol(...
    'Parent',hBGroupRunType,...
    'Style','RadioButton',...
    'String','Manual',...
    'TooltipString','Process with current parameters, manually change N.Comp. table',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
%hDoSVDButton = 
uicontrol(...
    'Parent',hBGroupRunType,...
    'Style','PushButton',...
    'String','Estimate N',...
    'Units','normalized',...
    'TooltipString','Estimate the rank of each window',...
    'Position',[0.05 0.01 0.9 0.22],...
    'Callback', { @LRDoSVDButton_Callback});

% Table
hRegionsTable=uitable(...
    'parent',hTabLOCODOSY,...
    'units','normalized',...
    'columneditable',true(1,100),...
    'columnname',{'N'},...
    'columnformat',{[],'char'},...
    'rowname',{'numbered'},...
    'columnformat',{'numeric'},...
    'ColumnWidth',{54 54},...
    'position',[0.86 0.02 0.12 0.78 ],...
    'Visible','On',...
    'celleditcallback', { @LRRegionsTable_Callback});
%hRegionsText=
uicontrol(...
    'Parent',hTabLOCODOSY,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','bold',...
    'Position',[0.87 0.8 0.18 0.12 ],...
    'horizontalalignment','l',...
    'String',{'Max (N) spectra','per segment'} );
%% ---------ILT (diffusion)

% Process
hILTProcessPanel=uipanel(...
    'Parent',hTabILT,...
    'Visible','On',...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessLOCODOSYButton = 
uicontrol(...
    'Parent',hILTProcessPanel,...
    'Style','PushButton',...
    'Visible','On',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @DoILT});
%hReplotLOCODOSYButton = 
uicontrol(...
    'Parent',hILTProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Visible','On',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @plotILT});

% Peak pick
hBGroupILTOpt1=uibuttongroup(...
    'Parent',hTabILT,...
    'Title','Peak pick',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.35 0.5 0.3 0.45 ]);
hRadio1ILTOpt1 = uicontrol(...
    'Parent',hBGroupILTOpt1,...
    'Style','RadioButton',...
    'String','Peak pick',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2ILTOpt1 = uicontrol(...
    'Parent',hBGroupILTOpt1,...
    'Style','RadioButton',...
    'String','All frequencies',...
    'Units','normalized',...
    'Position',[0.05 0.35 0.9 0.3]);
hRadio3ILTOpt1 = uicontrol(...
    'Parent',hBGroupILTOpt1,...
    'Style','RadioButton',...
    'String','Integrals',...
    'Units','normalized',...
    'Position',[0.05 0.0 0.9 0.3]);

% ILT plot
hDPlotPanel=uipanel(...
    'Parent',hTabILT,...
    'Title','ILT plot',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.68 0.5 0.3 0.45 ]);
hEditDminILT=uicontrol(...
    'Parent',hDPlotPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'string',num2str(0),...
    'Units','Normalized',...
    'TooltipString','Minimum value of diffusion coefficient displayed',...
    'Max',1,...
    'Position',[0.1 0.68 0.2 0.25 ]);%,...
   % 'CallBack', { @EditDmin_Callback});
uicontrol(...
    'Parent',hDPlotPanel,...
    'Style','text',...
    'String','D Min.',...
    'Units','Normalized',...
    'Position',[0.37 0.65 0.2 0.25 ],...
    'horizontalalignment','l');
hEditDmaxILT=uicontrol(...
    'Parent',hDPlotPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'string',num2str(20),...
    'Units','Normalized',...
    'TooltipString','Maximum value of diffusion coefficient displayed',...
    'Max',1,...
    'Position',[0.1 0.4 0.2 0.25 ]);%,...
    %'CallBack', { @EditDmax_Callback});
hCheckDmaxILT=uicontrol(...
    'Parent',hDPlotPanel,...
    'Style','checkbox',...
    'Enable','On',...
    'String','Auto',...
    'Units','Normalized',...
    'TooltipString','Automatically set D max.',...
    'Value',1,...
    'Position',[0.7 0.42 0.35 0.25 ]);%,...
   % 'CallBack', { @CheckDmaxILT_Callback});
uicontrol(...
    'Parent',hDPlotPanel,...
    'Style','text',...
    'Visible','On',...
    'String','D Max.',...
    'Units','Normalized',...
    'Position',[0.37 0.35 0.2 0.25 ],...
    'horizontalalignment','l');
hEditDresILT=uicontrol(...
    'Parent',hDPlotPanel,...
    'Style','edit',...
    'Visible','On',...
    'BackgroundColor','w',...
    'string',num2str(512),...
    'Units','Normalized',...
    'Max',1,...
    'TooltipString','Number of data points in the diffusion dimension',...
    'Position',[0.1 0.05 0.2 0.25 ]);%,...
   % 'CallBack', { @EditDres_Callback});
uicontrol(...
    'Parent',hDPlotPanel,...
    'Style','text',...
    'Visible','On',...
    'String','Digitization',...
    'Units','Normalized',...
    'Position',[0.37 0.02 0.5 0.25 ],...
    'horizontalalignment','l');

% Regularisation
hBGroupILTRegMet=uibuttongroup(...
    'Parent',hTabILT,...
    'Title','Regularisation',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.18 0.0 0.15 0.45 ]);
hRadio2ILTRegMet = uicontrol(...
    'Parent',hBGroupILTRegMet,...
    'Style','RadioButton',...
    'String','Tikhonov',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);
hRadio1ILTRegMet = uicontrol(...
    'Parent',hBGroupILTRegMet,...
    'Style','RadioButton',...
    'String','None',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);

% OPtimun Lambda
hBGroupILTOptimLambda=uibuttongroup(...
    'Parent',hTabILT,...
    'Title','Optim Lambda',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.5 0.0 0.15 0.45 ]);
hRadio2ILTILTOptimLambd = uicontrol(...
    'Parent',hBGroupILTOptimLambda,...
    'Style','RadioButton',...
    'String','L-Curve',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);
hRadio1ILTILTOptimLambd = uicontrol(...
    'Parent',hBGroupILTOptimLambda,...
    'Style','RadioButton',...
    'String','Manual',...
    'Units','normalized',...
    'Position',[0.05 0.75 0.9 0.3]);
hRadio3ILTILTOptimLambd = uicontrol(...
    'Parent',hBGroupILTOptimLambda,...
    'Style','RadioButton',...
    'String','GCV',...
    'Units','normalized',...
    'Position',[0.05 0.05 0.9 0.3]);

% Smooth
hBGroupILTSmooth=uibuttongroup(...
    'Parent',hTabILT,...
    'Title','Smooth',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.34 0.0 0.15 0.45 ]);
hRadio3ILTILTOptimSmooth = uicontrol(...
    'Parent',hBGroupILTSmooth,...
    'Style','RadioButton',...
    'String','2nd derivative',...
    'Units','normalized',...
    'Position',[0.05 0.05 0.9 0.3]);
hRadio1ILTILTSmooth = uicontrol(...
    'Parent',hBGroupILTSmooth,...
    'Style','RadioButton',...
    'String','None',...
    'Units','normalized',...
    'Position',[0.05 0.75 0.9 0.3]);
hRadio2ILTILTOptiSmooth = uicontrol(...
    'Parent',hBGroupILTSmooth,...
    'Style','RadioButton',...
    'String','1st derivative',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);

% Constrain
hBGroupILTConstrain=uibuttongroup(...
    'Parent',hTabILT,...
    'Title','Constraint',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.0 0.15 0.45 ]);
hRadio2ILTConstrain = uicontrol(...
    'Parent',hBGroupILTConstrain,...
    'Style','RadioButton',...
    'String','Non-negativity',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);
hRadio1ILTConstrain = uicontrol(...
    'Parent',hBGroupILTConstrain,...
    'Style','RadioButton',...
    'String','None',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);

% Manual Lambda
%hTextLamda=
uicontrol(...
    'Parent',hTabILT,...
    'Style','text',...
    'String','Manual Lamda',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.7 0.3 0.24 0.1 ],...
    'horizontalalignment','l');
hEditLamda=uicontrol(...
    'Parent',hTabILT,...
    'Style','edit',...
    'BackgroundColor','w',...
    'String','1',...
    'Units','Normalized',...
    'Position',[0.72 0.2 0.05 0.1 ]);
%% ---------DECRA

% Process
hDECRAProcessPanel=uipanel(...
    'Parent',hTabDECRA,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessDECRAButton = 
uicontrol(...
    'Parent',hDECRAProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @dodecra});
%hReplotDECRAButton = 
uicontrol(...
    'Parent',hDECRAProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @plotdecra});

% Components
hDECRANcompPanel=uipanel(...
    'Parent',hTabDECRA,...
    'Visible','On',...
    'Title','Components',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.35 0.5 0.3 0.45 ]);
hEditNcompDECRA=uicontrol(...
    'Parent',hDECRANcompPanel,...
    'Style','edit',...
    'Visible','On',...
    'String',2,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of (estimated) components to search for in the mixture spectrum',...
    'Units','Normalized',...
    'Position',[0.4 0.3 0.15 0.3 ],...
    'CallBack', '');
%hTextNcompDECRA=
uicontrol(...
    'Parent',hDECRANcompPanel,...
    'Style','text',...
    'Visible','On',...
    'String',2,...
    'String','Fitted componets:',...
    'Units','Normalized',...
    'Position',[0.2 0.7 0.6 0.2 ],...
    'horizontalalignment','c');

%% ---------ROSY(T1/T2)

% Process
hT1ProcessPanel=uipanel(...
    'Parent',hTabT1,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessT1Button = 
uicontrol(...
    'Parent',hT1ProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @doT1});
%hReplotT1Button = 
uicontrol(...
    'Parent',hT1ProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @plotT1});

% Peak pick
hBGroupT1Opt1=uibuttongroup(...
    'Parent',hTabT1,...
    'Title','Peak pick',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.35 0.5 0.3 0.45 ]);
hRadio1T1Opt1 = uicontrol(...
    'Parent',hBGroupT1Opt1,...
    'Style','RadioButton',...
    'String','Peak pick',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2T1Opt1 = uicontrol(...
    'Parent',hBGroupT1Opt1,...
    'Style','RadioButton',...
    'String','All frequencies',...
    'Units','normalized',...
    'Position',[0.05 0.35 0.9 0.3]);
hRadio3T1Opt1 = uicontrol(...
    'Parent',hBGroupT1Opt1,...
    'Style','RadioButton',...
    'String','Integrals',...
    'Units','normalized',...
    'Position',[0.05 0.0 0.9 0.3]);

% Fit type
hBGroupT1Opt2=uibuttongroup(...
    'Parent',hTabT1,...
    'Title','Fit type',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.68 0.05 0.3 0.45 ]);
hRadio1T1Opt2 = uicontrol(...
    'Parent',hBGroupT1Opt2,...
    'Style','RadioButton',...
    'String','T1 Inversion recovery',...
    'Units','normalized',...
    'TooltipString','Inversion recovery 3 parameter fit',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2T1Opt2 = uicontrol(...
    'Parent',hBGroupT1Opt2,...
    'Style','RadioButton',...
    'String','T1 Saturation recovery',...
    'TooltipString','Saturation recovery 3 parameter fit',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);
hRadio3T1Opt2 = uicontrol(...
    'Parent',hBGroupT1Opt2,...
    'Style','RadioButton',...
    'String','T2 CPMG/PROJECT ',...
    'TooltipString','CPMG/PROJECT 2 parameter fit',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.3]);

% ROSY plot
hPanelT1plotting = uipanel(...
    'Parent',hTabT1,...
    'Title','ROSY plot',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'ForegroundColor','Black',...
    'Units','Normalized',...
    'Position',[0.68,0.5,0.3,0.45]);
hCheckT1limits=uicontrol(...
    'Parent',hPanelT1plotting,...
    'Style','checkbox',...
    'Units','Normalized',...
    'String','Auto',...
    'Value',1,...
    'TooltipString','Automatic setting of plot limits from fitted T1/T2 values',...
    'Position',[0.7 0.42 0.3 0.25 ],...
    'CallBack', { @CheckT1limits_Callback} );
hEditT1min=uicontrol(...
    'Parent',hPanelT1plotting,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Minimum value of T1/T2 coefficient displayed',...
    'Max',1,...
    'Position',[0.1 0.7 0.2 0.25 ],...
    'CallBack', { @EditT1min_Callback});
%hTextT1min=
uicontrol(...
    'Parent',hPanelT1plotting,...
    'Style','text',...
    'String','Min.',...
    'Units','Normalized',...
    'Position',[0.37 0.65 0.2 0.25 ],...
    'horizontalalignment','l');
hEditT1max=uicontrol(...
    'Parent',hPanelT1plotting,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Maximum value of T1/T2 coefficient displayed',...
    'Max',1,...
    'Position',[0.1 0.35 0.2 0.25 ],...
    'CallBack', { @EditT1max_Callback});
%hTextT1max=
uicontrol(...
    'Parent',hPanelT1plotting,...
    'Style','text',...
    'Visible','On',...
    'String','Max.',...
    'Units','Normalized',...
    'Position',[0.37 0.35 0.2 0.25 ],...
    'horizontalalignment','l');
%hTextT1res=
uicontrol(...
    'Parent',hPanelT1plotting,...
    'Style','text',...
    'String','Digitization',...
    'Units','Normalized',...
    'Position',[0.37 0.0 0.5 0.25 ],...
    'horizontalalignment','l');
hEditT1res=uicontrol(...
    'Parent',hPanelT1plotting,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'Max',1,...
    'TooltipString','Number of data points in the T1/T2 dimension',...
    'Position',[0.1 0.05 0.2 0.25 ]);%,...
    %'CallBack', { @EditT1res_Callback});

% Fit type
hBGroupT1Opt3=uibuttongroup(...
    'Parent',hTabT1,...
    'Title','Fit type',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.05 0.3 0.45 ],...
    'SelectionChangeFcn', { @FitTypeROSY_Callback});

hRadio1T1Opt3 = uicontrol(...
    'Parent',hBGroupT1Opt3,...
    'Style','RadioButton',...
    'String','Monoexponential',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
%hRadio2DOSYOpt3 = 
uicontrol(...
    'Parent',hBGroupT1Opt3,...
    'Style','RadioButton',...
    'String','Multiexponential',...
    'Units','normalized',...
    'Position',[0.05 0.25 0.9 0.3]);



hBMultiexpPanelR=uipanel(...
    'Parent',hTabT1,...
    'Title','Multiexponential',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.05 0.3 0.45 ]);
hEditMultexpR=uicontrol(...
    'Parent',hBMultiexpPanelR,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Maximun number of components per peak',...
    'Max',1,...
    'Position',[0.01 0.6 0.15 0.25 ]);
%hTextMultexp=
uicontrol(...
    'Parent',hBMultiexpPanelR,...
    'Style','text',...
    'String','Exponentials',...
    'Units','Normalized',...
    'Position',[0.17 0.57 0.4 0.25 ],...
    'horizontalalignment','l');
hEditTriesR=uicontrol(...
    'Parent',hBMultiexpPanelR,...
    'Style','edit',...
    'Enable','Off',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Number of randomised starting guesses per peak',...
    'Max',1,...
    'Position',[0.01 0.2 0.15 0.25 ]);
%hTextTries=
uicontrol(...
    'Parent',hBMultiexpPanelR,...
    'Style','text',...
    'String','Random repeats',...
    'Units','Normalized',...
    'Position',[0.17 0.15 0.4 0.25 ],...
    'horizontalalignment','l');
%% ---------RSCORE (relaxation)

% Process
hRSCOREProcessPanel=uipanel(...
    'Parent',hTabRSCORE,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessRSCOREButton = 
uicontrol(...
    'Parent',hRSCOREProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @dorscore});
%hReplotRSCOREButton = 
uicontrol(...
    'Parent',hRSCOREProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @plotrscore});
%hPubplotRSCOREButton = 
uicontrol(...
    'Parent',hRSCOREProcessPanel,...
    'Style','PushButton',...
    'String','Pub. plot',...
    'Enable','On',...
    'Units','normalized',...
    'TooltipString','Plot the data from the last fit in publication format',...
    'Position',[0.05 0.1 0.4 0.3],...
    'Callback', { @pubplotrscore});

% Components
hRSCORENcompPanel=uipanel(...
    'Parent',hTabRSCORE,...
    'Title','Components',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.35 0.5 0.3 0.45 ]);
hEditNcompRSCORE=uicontrol(...
    'Parent',hRSCORENcompPanel,...
    'Style','edit',...
    'String',2,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of (estimated) components to search for in the mixture spectrum',...
    'Units','Normalized',...
    'Position',[0.4 0.3 0.15 0.3 ]);%,...
   % 'CallBack', { @EditNcompSCORE_Callback});
%hTextNcompRSCORE=
uicontrol(...
    'Parent',hRSCORENcompPanel,...
    'Style','text',...
    'String',2,...
    'String','Fitted componets:',...
    'Units','Normalized',...
    'Position',[0.2 0.7 0.6 0.2 ],...
    'horizontalalignment','c');

% Fit equation
hBGroupRSCOREOpt1=uibuttongroup(...
    'Parent',hTabRSCORE,...
    'Title','Fit equation',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.68 0.05 0.3 0.45 ]);
hRadio1RSCOREOpt1 = uicontrol(...
    'Parent',hBGroupRSCOREOpt1,...
    'Style','RadioButton',...
    'String','T2 (2 parameter)',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2RSCOREOpt1 = uicontrol(...
    'Parent',hBGroupRSCOREOpt1,...
    'Style','RadioButton',...
    'String','T1 (3 parameter)',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);

% T guess
hBGroupRSCOREOpt2=uibuttongroup(...
    'Parent',hTabRSCORE,...
    'Title','T guess',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.35 0.05 0.3 0.45]);
hRadio1RSCOREOpt2 = uicontrol(...
    'Parent',hBGroupRSCOREOpt2,...
    'Style','RadioButton',...
    'String','Fit',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2RSCOREOpt2 = uicontrol(...
    'Parent',hBGroupRSCOREOpt2,...
    'Style','RadioButton',...
    'String','Random',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);

% Constrain
hBGroupRSCOREOpt3=uibuttongroup(...
    'Parent',hTabRSCORE,...
    'Visible','On',...
    'Title','Constraint',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.05 0.3 0.45]);
hRadio1RSCOREOpt3 = uicontrol(...
    'Parent',hBGroupRSCOREOpt3,...
    'Style','RadioButton',...
    'String','None',...
    'Units','normalized',...
    'Position',[0.05 0.6 0.9 0.3]);
hRadio2RSCOREOpt3 = uicontrol(...
    'Parent',hBGroupRSCOREOpt3,...
    'Style','RadioButton',...
    'String','Non-negative',...
    'Units','normalized',...
    'Position',[0.05 0.2 0.9 0.3]);

% Method
hBGroupRSCOREOpt6=uibuttongroup(...
    'Parent',hTabRSCORE,...
    'Visible','On',...
    'Title','Method',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.68 0.5 0.3 0.45]);
hRadio1RSCOREOpt6 = uicontrol(...
    'Parent',hBGroupRSCOREOpt6,...
    'Style','RadioButton',...
    'String','SCORE',...
    'Units','normalized',...
    'Position',[0.05 0.6 0.9 0.3]);
hRadio2RSCOREOpt6 = uicontrol(...
    'Parent',hBGroupRSCOREOpt6,...
    'Style','RadioButton',...
    'String','OUTSCORE',...
    'Units','normalized',...
    'Position',[0.05 0.2 0.9 0.3]);
%% ---------Analyse

% Measure
hAnalyzeMeasurePanel=uipanel(...
    'Parent',hTabAnal,...
    'Title','Measure',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.02 0.005 0.3 0.95 ]);
%hShapeButton = 
uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','PushButton',...
    'String','Shape',...
    'Units','normalized',...
    'TooltipString','Check the peak width at half height',...
    'Position',[0.05 0.65 0.3 0.25],...
    'Callback',{ @ShapeButton_Callback});
hMeasureCheck = uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','CheckBox',...
    'String','Show',...
    'Units','normalized',...
    'TooltipString','Show selected line',...
    'Position',[0.55 0.72 0.3 0.3],...
    'Callback',{ @MeasureCheck_Callback});
%hShapesetButton = 
uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Set line for measuring peak width',...
    'Position',[0.55 0.65 0.25 0.15],...
    'Callback',{ @MeasureButton_Callback});
%hDeltaButton = 
uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','PushButton',...
    'String','Delta',...
    'Units','normalized',...
    'TooltipString','Check distance between right and left limit',...
    'Position',[0.05 0.15 0.3 0.25],...
    'Callback',{ @DeltaButton_Callback});
%hDeltaLimitsText = 
uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','Text',...
    'String','Limits',...
    'FontWeight','bold',...
    'Units','normalized',...
    'horizontalalignment','c',...
    'Position',[0.45 0.08 0.2 0.3]);
hDeltashowLRCheck = uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Units','normalized',...
    'Value',0,...
    'TooltipString','Show limits',...
    'Position',[0.65 0.20 0.3 0.3],...
    'Callback',{ @DeltashowLRCheck_Callback});
%hDeltaleftButton = 
uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','PushButton',...
    'String','Left',...
    'Units','normalized',...
    'TooltipString','Set left limit',...
    'Position',[0.42 0.10 0.25 0.15],...
    'Callback',{ @DeltaleftButton_Callback});
%hDeltarigthButton = 
uicontrol(...
    'Parent',hAnalyzeMeasurePanel,...
    'Style','PushButton',...
    'String','Right',...
    'Units','normalized',...
    'TooltipString','Set right limit',...
    'Position',[0.72 0.10 0.25 0.15],...
    'Callback',{ @DeltarigthButton_Callback});

% Method
hAnalyzeMethProcessPanel=uibuttongroup(...
    'Parent',hTabAnal,...
    'Title','Method',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.5 0.3 0.45]);
%hAnalyzeFreqButton = 
uicontrol(...
    'Parent',hAnalyzeMethProcessPanel,...
    'Style','PushButton',...
    'String','Freq.',...
    'Units','normalized',...
    'TooltipString','Analyse frequency shift',...
    'Position',[0.015 0.6 0.32 0.3],...
    'Callback',{ @AnalyzeFreqButton_Callback});
%hAnalyzeResButton = 
uicontrol(...
    'Parent',hAnalyzeMethProcessPanel,...
    'Style','PushButton',...
    'String','Resol.',...
    'Units','normalized',...
    'TooltipString','Analyse resolution changes',...
    'Position',[0.345 0.6 0.32 0.3],...
    'Callback',{ @AnalyzeResButton_Callback});
%hAnalyzeAmpButton = 
uicontrol(...
    'Parent',hAnalyzeMethProcessPanel,...
    'Style','PushButton',...
    'String','Ampl.',...
    'Units','normalized',...
    'TooltipString','Analyse amplitude changes',...
    'Position',[0.67 0.6 0.32 0.3],...
    'Callback',{ @AnalyzeAmpButton_Callback});
%hAnalyzeTempButton = 
uicontrol(...
    'Parent',hAnalyzeMethProcessPanel,...
    'Style','PushButton',...
    'String','Temp.',...
    'Units','normalized',...
    'TooltipString','Analyse temperature changes',...
    'Position',[0.015 0.1 0.32 0.3],...
    'Callback',{ @AnalyzeTempButton_Callback});
%hAnalyzePhaseButton = 
uicontrol(...
    'Parent',hAnalyzeMethProcessPanel,...
    'Style','PushButton',...
    'String','Phase',...
    'Units','normalized',...
    'TooltipString','Analyse phase changes',...
    'Position',[0.345 0.1 0.32 0.3],...
    'Callback',{ @AnalyzePhaseButton_Callback});
%hAnalyzeIntButton = 
uicontrol(...
    'Parent',hAnalyzeMethProcessPanel,...
    'Style','PushButton',...
    'String','Int.',...
    'Units','normalized',...
    'TooltipString','Analyse integral changes',...
    'Position',[0.67 0.1 0.32 0.3],...
    'Callback',{ @AnalyzeIntButton_Callback});

% Temperature calibration
hAnalyzeTempPanel=uipanel(...
    'Parent',hTabAnal,...
    'Title','Temperature calibration',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.005 0.3 0.5 ]);
%hTextTempCoeff=
uicontrol(...
    'Parent',hAnalyzeTempPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.7 0.5 0.3 0.3 ],...
    'horizontalalignment','left',...
    'String','K/ppm' );
hEditTempCoeff=uicontrol(...
    'Parent',hAnalyzeTempPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString',...
    'Coefficient used in the analysis of temperature changes',...
    'String',-0.0102,...
    'Units','Normalized',...
    'Position',[0.35 0.60 0.3 0.3 ],...
    'CallBack', { @EditTempCoeff_Callback});
%hTextDefCoeff=

%hTempTSP = 
uicontrol(...
    'Parent',hAnalyzeTempPanel,...
    'Style','PushButton',...
    'String','Default (TSP in D2O)',...
    'TooltipString',...
    'Use TSP coefficient for the analysis of temperature changes',...
    'Units','normalized',...
    'Position',[0.2 0.15 0.6 0.3],...
    'Callback',{ @TempTSPButton_Callback});

% Plot spectra array
hPanelSettingsAnalyze=uipanel(...
    'Parent',hTabAnal,...
    'Units','Normalized',...
    'Position',[0.68 0.005 0.3 0.95 ],...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Title','Spectra array' );
%hDSSButton = 
uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','PushButton',...
    'String','Plot',...
    'Units','normalized',...
    'TooltipString','Plot spectra array with current parameters',...
    'Position',[0.3 0.80 0.4 0.15],...
    'Callback', { @DSSButton_Callback});
%hTextStart=
uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.65 0.3 0.1 ],...
    'horizontalalignment','left',...
    'String','Start:' );
hEditStart=uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','First spectrum',...
    'String',1,...
    'Units','Normalized',...
    'Position',[0.5 0.65 0.3 0.1 ],...
    'CallBack', { @EditStart_Callback});
%hTextStop=
uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.50 0.3 0.1 ],...
    'horizontalalignment','left',...
    'String','Stop:' );
hEditStop=uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Last spectrum',...
    'String',1,...
    'Units','Normalized',...
    'Position',[0.5 0.50 0.3 0.1],...
    'CallBack', { @EditStop_Callback});
%hTextStep=
uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.35 0.3 0.1 ],...
    'horizontalalignment','left',...
    'String','Step:' );
hEditStep=uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Spectrum step',...
    'String',1,...
    'Units','Normalized',...
    'Position',[0.5 0.35 0.3 0.1 ],...
    'CallBack', { @EditStep_Callback});
%hTextHorizontalOffset=
uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.20 0.3 0.1 ],...
    'horizontalalignment','left',...
    'String','Horiz. offset (%):' );
hEditHorizontalOffset=uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString',...
    'Horizontal offset (%)',...
    'String',1,...
    'Units','Normalized',...
    'Position',[0.5 0.20 0.3 0.1 ],...
    'CallBack', { @EditHorizontalOffset_Callback});
%hTextVerticalOffset=
uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.05 0.3 0.1  ],...
    'horizontalalignment','left',...
    'String','Vert. offset (%):' );
hEditVerticalOffset=uicontrol(...
    'Parent',hPanelSettingsAnalyze,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString',...
    'Verticla offset (%)',...
    'String',1,...
    'Units','Normalized',...
    'Position',[0.5 0.05 0.3 0.1 ],...
    'CallBack', { @EditVerticalOffset_Callback});
%% ---------PCA

% ------Proces
hPCAProcessPanel=uipanel(...
    'Parent',hTabPCA,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01 0.5 0.2 0.45 ]);
% hProcessPCAButton = 
uicontrol(...
    'Parent',hPCAProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', {@doPCA});
%hReplotPCAButton = 
uicontrol(...
    'Parent',hPCAProcessPanel,...
    'Style','PushButton',...
    'String','Normalise',...
    'Units','normalized',...
    'TooltipString','Normalize current data',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', @normalize_GUI);
%hBinPCAButton = 
uicontrol(...
    'Parent',hPCAProcessPanel,...
    'Style','PushButton',...
    'String','Bin',...
    'Units','normalized',...
    'TooltipString','Calculate the Bin preprocessing',...
    'Position',[0.05 0.2 0.4 0.3],...
    'Tag','PCA analysis v 1.0',...
    'Callback', {@doBin});
    uicontrol(...
    'Parent',hPCAProcessPanel,...
    'Style','PushButton',...
    'String','Help',...
    'Units','normalized',...
    'TooltipString','Open the GNAT pdf Manual',...
    'Position',[0.55 0.2 0.4 0.3],...
    'Tag','PCA',...
    'Callback', @HelpButton); 

% ------Components
hPCANcompPanel=uipanel(...
    'Parent',hTabPCA,...
    'Title','Components',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.22 0.5 0.15 0.45 ]);
hEditNcompPCA=uicontrol(...
    'Parent',hPCANcompPanel,...
    'Style','edit',...
    'String',num2str(5),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components used in the PCA model',...
    'Units','Normalized',...
    'Position',[0.35 0.3 0.3 0.3 ],...
    'CallBack', {@EditComponent_Callback});
%hButtonPlusComp = 
uicontrol(...
    'Parent',hPCANcompPanel,...
    'Style','PushButton',...
    'String','+1',...
    'Units','normalized',...
    'Position',[0.65 0.3 0.3 0.3],...
    'Tag','PlusComp',...
    'Callback',{@EditComponent_Callback});
%hButtonMinusComp = 
uicontrol(...
    'Parent',hPCANcompPanel,...
    'Style','PushButton',...
    'String','-1',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.3 0.3],...
    'Tag','MinusComp',...
    'Callback',{@EditComponent_Callback});

% ------Confidence
hPCAConfPanel=uipanel(...
    'Parent',hTabPCA,...
    'Title','Confidence value',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.22 0.05 0.15 0.45 ]);
hEditConfPCA=uicontrol(...
    'Parent',hPCAConfPanel,...
    'Style','edit',...
    'String',num2str(0.95),...
    'BackgroundColor','w',...
    'TooltipString',...
    'Confidence value to build the model',...
    'Units','Normalized',...
    'Position',[0.35 0.3 0.3 0.3 ],...
    'CallBack',{@EditConfidence_Callback});
%hButtonFlipPlusPeak = 
uicontrol(...
    'Parent',hPCAConfPanel,...
    'Style','PushButton',...
    'String','+0.01',...
    'Units','normalized',...
    'Position',[0.65 0.3 0.3 0.3],...
    'Tag','PlusConf',...
    'Callback',{@EditConfidence_Callback});
%hButtonFlipMinusPeak = 
uicontrol(...
    'Parent',hPCAConfPanel,...
    'Style','PushButton',...
    'String','-0.01',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.3 0.3],...
    'Tag','MinusConf',...
    'Callback',{@EditConfidence_Callback});

% ------Plots
hPanelPCAPlots=uipanel(...
    'Parent',hTabPCA,...
    'Title','Plots',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.01 0.05 0.2 0.45 ]);
hPCAScoresPlotUse = uicontrol(...
    'Parent',hPanelPCAPlots,...
    'Style','Checkbox',...
    'String','Scores',...
    'Value',1,...
    'TooltipString','Turn on/off Score Plot',...
    'Units','normalized',...
    'Position',[0.05 0.65 0.9 0.3]);
hPCALoadingsPlotUse = uicontrol(...
    'Parent',hPanelPCAPlots,...
    'Style','Checkbox',...
    'String','Loadings',...
    'Value',1,...
    'TooltipString','Turn on/off Loadings Plot',...
    'Units','normalized',...
    'Position',[0.05 0.35 0.9 0.3]);
hPCAResidualPlotUse = uicontrol(...
    'Parent',hPanelPCAPlots,...
    'Style','Checkbox',...
    'String','Residual',...
    'Value',1,...
    'TooltipString','Turn on/off Residual Plot',...
    'Units','normalized',...
    'Position',[0.05 0.05 0.9 0.3]);

% ------Variance Captured by PCA Tab
hTabTableVarianceCaptured=uitab(...
    'Parent',hTabGroupPCA,...
    'Title','Variance Captured by PCA',...
    'TooltipString','PCA results',...
    'Units','Normalized');
hTableEigenvalues = uitable(...
    'parent',hTabTableVarianceCaptured,...
    'units','normalized',...
    'columneditable',[true true true],...
    'columnname',{' Eigenvalue ','   Explained Variance (%)   ','   Cumulative Variance (%)   '},...
    'columnformat',{'numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.01 0.048 0.6 0.95],...
    'Data',zeros(6,4));

% ------Class Tab
hTabClassConstruction=uitab(...
    'Parent',hTabGroupPCA,...
    'Title','Class (Optional)',...
    'TooltipString','Class construction options',...
    'Units','Normalized');

hPCAClassInfo=uipanel(...
    'Parent',hTabClassConstruction,...
    'Title','Information',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01,0.01,0.22,0.97]);
%hButtonAddClass = 
uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','PushButton',...
    'String','Add',...    
    'TooltipString','Add a new class with current parameters',...
    'Units','normalized',...
    'Position',[0.025,0.70,0.3,0.24],...
    'Callback',{@addClass});
%hButtonDeleteClass = 
uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','PushButton',...
    'String','Delete',...
    'TooltipString','Remove current class',...
    'Units','normalized',...
    'Position',[0.35,0.70,0.3,0.24],...
    'Callback',{@deleteClass});
%hButtonLabelClass = 
uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','PushButton',...
    'String','Labels',...
    'TooltipString','Open a new window to define labels',...
    'Units','normalized',...
    'Position',[0.675,0.70,0.3,0.24],...
    'Callback',{@labelClass});

%hTextClass=
uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.4975 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','Class:' );
hEditClassPCA=uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'tag','PCA',...
    'Position',[0.40 0.49 0.47,0.15]); 
%hTextBegining=
uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.25 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','Begining:' );
hEditBeginningClassPCA=uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.40 0.25 0.47 0.15]); 
%hTextEnd=
uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.025 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','End:' );
hEditEndClassPCA=uicontrol(...
    'Parent',hPCAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.40 0.03 0.47 0.15]); 

hPCAClassTable=uipanel(...
    'Parent',hTabClassConstruction,...
    'Title','Class Table',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.24,0.017,0.38,0.97]);
hClassTable = uitable(... 
    'parent',hPCAClassTable,...
    'units','normalized',...
    'columneditable',[true true true],...
    'columnname',{'Class','Beginning','End'},...
    'columnformat',{'numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.01 0.048 0.98 0.95]);
%% ---------PLSDA 

% ------Proces
hPLSDAProcessPanel=uipanel(...
    'Parent',hTabPLSDA,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01 0.5 0.3 0.45 ]);
hProcessPLSDAButton = uicontrol(...
    'Parent',hPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Enable','off',...
    'Callback', {@doPLSDA});
%hLoadPLSDAButton = 
uicontrol(...
    'Parent',hPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Normalise',...
    'Units','normalized',...
    'TooltipString','Normalize current data',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', {@normalize_GUI});
%hHelpPLSDAButton = 
uicontrol(...
    'Parent',hPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Help',...
    'Units','normalized',...
    'TooltipString','Open the GNAT pdf Manual',...
    'Position',[0.55 0.2 0.4 0.3],...
    'Tag','PLSDA',...
    'Callback', @HelpButton);
%hBinButton = 
uicontrol(...
    'Parent',hPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Bin',...
    'Units','normalized',...
    'TooltipString','Calculate the Bin preprocessing',...
    'Position',[0.05 0.2 0.4 0.3],...
    'Tag','PLSDA analysis v 1.0',...
    'Callback', {@doBin});

% ------ Split Cal/Val
hPanelPLSDAPlots=uibuttongroup(...
    'Parent',hTabPLSDA,...
    'Title','Split Cal/Val',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.01 0.01 0.3 0.50]);
hPLSk = uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','RadioButton',...
    'String','Kenston',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hPLSd = uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','RadioButton',...
    'String','Duplex',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);
hPLSs = uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','RadioButton',...
    'String','Segments',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.3]);

%hCalibration%=
uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.5 0.6 0.4 0.3],...
    'horizontalalignment','left',...
    'String','% Calibration');
hEditCalPLSDA = uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','Edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.37 0.54 0.12 0.4],...
    'Callback', {@doCalVal});

%hValidation%=
uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.5 0.15 0.4 0.3 ],...
    'horizontalalignment','left',...
    'String','% Validation');
hEditValPLSDA = uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','Edit',...
    'String',num2str(30),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Enable','off',...
    'Position',[0.37 0.07 0.12 0.40]);

% hRunCalVal = 
uicontrol(...
    'Parent',hPanelPLSDAPlots,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.8 0.3 0.15 0.5],...
    'Callback', { @doCalVal});

% ------Class Tab
hTabClassConstructionPLSDA=uitab(...
    'Parent',hTabGroupPLSDA,...
    'Title','Class',...
    'TooltipString','Class construction options',...
    'Units','Normalized');

hPLSDAClassInfo=uipanel(...
    'Parent',hTabClassConstructionPLSDA,...
    'Title','Information',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01,0.01,0.22,0.97]);
%hButtonAddClass = 
uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','PushButton',...
    'String','Add',...
    'Units','normalized',...
    'Position',[0.025,0.70,0.3,0.24],...
    'Callback',{@addClass});
%hButtonDeleteClass = 
uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','PushButton',...
    'String','Delete',...
    'Units','normalized',...
    'Position',[0.35,0.70,0.3,0.24],...
    'Callback',{@deleteClass});
%hButtonLabelClass = 
uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','PushButton',...
    'String','Labels',...
    'Units','normalized',...
    'Position',[0.675,0.70,0.3,0.24],...
    'Callback',{@labelClass});

%hTextClass=
uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.4975 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','Class:' );
hEditClassPLSDA=uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'tag','PLSDA',...
    'Position',[0.40 0.49 0.47,0.15]); 
%hTextBegining=
uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.25 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','Begining:' );
hEditBeginningClassPLSDA=uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.40 0.25 0.47 0.15]); 
%hTextEnd=
uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.025 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','End:' );
hEditEndClassPLSDA=uicontrol(...
    'Parent',hPLSDAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.40 0.03 0.47 0.15]); 

hPLSDAClassTable=uipanel(...
    'Parent',hTabClassConstructionPLSDA,...
    'Title','Class Table',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.24,0.017,0.286,0.97]);
hClassTablePLSDA = uitable(...
    'parent',hPLSDAClassTable,...
    'units','normalized',...
    'columneditable',[true true true],...
    'columnname',{'Class','Beginning','End'},...
    'columnformat',{'numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.01 0.048 0.98 0.95]);

% ------ Cal/Val Table Tab
hTabTableCalVal=uitab(...
    'Parent',[],...
    'Title','Cal/Val Info',...
    'TooltipString','Information about the separation of your dataset in Cal/Val',...
    'Units','Normalized');
hTableCalVal = uitable(...
    'parent',hTabTableCalVal,...
    'units','normalized',...
    'columneditable',[true true true true],...
    'columnname',{'Sample','Calibration','Validation'},...
    'columnformat',{'char','char','char'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.01 0.048 0.6 0.95],...
    'Data',zeros(6,3));

%% ---------OPLSDA

% ------Proces
hOPLSDAProcessPanel=uipanel(...
    'Parent',hTabOPLSDA,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01 0.5 0.3 0.45 ]);
hProcessOPLSDAButton = uicontrol(...
    'Parent',hOPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Enable','off',...
    'Callback', {@doOPLSDA});
%hNormalizwePLSDAButton = 
uicontrol(...
    'Parent',hOPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Normalise',...
    'Units','normalized',...
    'TooltipString','Normalize current data',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', {@normalize_GUI});
%hBinButton = 
uicontrol(...
    'Parent',hOPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Bin',...
    'Units','normalized',...
    'TooltipString','Calculate the Bin preprocessing',...
    'Position',[0.05 0.2 0.4 0.3],...
    'Tag','OPLSDA analysis',...
    'Callback', {@doBin});
%hHelpPCAButton = 
uicontrol(...
    'Parent',hOPLSDAProcessPanel,...
    'Style','PushButton',...
    'String','Help',...
    'Units','normalized',...
    'TooltipString','Open the GNAT pdf Manual',...
    'Position',[0.55 0.2 0.4 0.3],...
    'Tag','OPLSDA',...
    'Callback', @HelpButton);


% ------ Split Cal/Val
hPanelOPLSDAPlots=uibuttongroup(...
    'Parent',hTabOPLSDA,...
    'Title','Split Cal/Val',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.01 0.01 0.3 0.50]);
hOPLSDAk = uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','RadioButton',...
    'String','Ken.Ston.',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hOPLSDAd = uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','RadioButton',...
    'String','Duplex',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);
hOPLSDAs = uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','RadioButton',...
    'String','Segments',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.3]);

%hCalibration%=
uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.5 0.6 0.4 0.3],...
    'horizontalalignment','left',...
    'String','% Calibration');
hEditCalOPLSDA=uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','Edit',...
    'String',num2str(70),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.37 0.54 0.12 0.4]);

%hValidation%=
uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.5 0.15 0.4 0.3 ],...
    'horizontalalignment','left',...
    'String','% Validation');
hEditValOPLSDA=uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','Edit',...
    'String',num2str(30),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Enable','off',...
    'Position',[0.37 0.07 0.12 0.40]);

% hRunCalVal = 
uicontrol(...
    'Parent',hPanelOPLSDAPlots,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.8 0.3 0.15 0.5],...
    'Callback', { @doCalValOPLSDA});


% ------Class Tab
hTabClassConstructionOPLSDA=uitab(...
    'Parent',hTabGroupOPLSDA,...
    'Title','Class',...
    'TooltipString','Class construction options',...
    'Units','Normalized');

hOPLSDAClassInfo=uipanel(...
    'Parent',hTabClassConstructionOPLSDA,...
    'Title','Information',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01,0.01,0.22,0.97]);
%hButtonAddClass = 
uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','PushButton',...
    'String','Add',...
    'Units','normalized',...
    'Position',[0.025,0.70,0.3,0.24],...
    'Callback',{@addClass});
%hButtonDeleteClass = 
uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','PushButton',...
    'String','Delete',...
    'Units','normalized',...
    'Position',[0.35,0.70,0.3,0.24],...
    'Callback',{@deleteClass});
%hButtonLabelClass = 
uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','PushButton',...
    'String','Labels',...
    'Units','normalized',...
    'Position',[0.675,0.70,0.3,0.24],...
    'Callback',{@labelClass});

%hTextClass=
uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.4975 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','Class:' );
hEditClassOPLSDA=uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'tag','PLSDA',...
    'Position',[0.40 0.49 0.47,0.15]); 
%hTextBegining=
uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.25 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','Begining:' );
hEditBeginningClassOPLSDA=uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.40 0.25 0.47 0.15]); 
%hTextEnd=
uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.025 0.025 0.35 0.15 ],...
    'horizontalalignment','left',...
    'String','End:' );
hEditEndClassOPLSDA=uicontrol(...
    'Parent',hOPLSDAClassInfo,...
    'Style','Edit',...
    'String',num2str(1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.40 0.03 0.47 0.15]); 

hOPLSDAClassTable=uipanel(...
    'Parent',hTabClassConstructionOPLSDA,...
    'Title','Class Table',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.24,0.017,0.38,0.97]);
hClassTableOPLSDA = uitable(...
    'parent',hOPLSDAClassTable,...
    'units','normalized',...
    'columneditable',[true true true],...
    'columnname',{'Class','Beginning','End'},...
    'columnformat',{'numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.01 0.048 0.98 0.95]);

% ------ Cal/Val Table Tab
hTabTableCalValOPLSDA=uitab(...
    'Parent',[],...
    'Title','Cal/Val Info',...
    'TooltipString','Information about the separation of your dataset in Cal/Val',...
    'Units','Normalized');
hTableCalValOPLSDA = uitable(...
    'parent',hTabTableCalValOPLSDA,...
    'units','normalized',...
    'columneditable',[true true true true],...
    'columnname',{'Sample','Calibration','Validation'},...
    'columnformat',{'char','char','char'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.01 0.048 0.6 0.95],...
    'Data',zeros(6,3));

%% ---------STOCSY

% ------Proces
hSTOCSYProcessPanel=uipanel(...
    'Parent',hTabSTOCSY,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01 0.5 0.3 0.45 ]);
uicontrol(...
    'Parent',hSTOCSYProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Run STOCSY model with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Enable','on',...
    'Callback', {@doSTOCSY});
%hBinButton = 
uicontrol(...
    'Parent',hSTOCSYProcessPanel,...
    'Style','PushButton',...
    'String','Bin',...
    'Units','normalized',...
    'TooltipString','Calculate the Bin preprocessing',...
    'Position',[0.05 0.2 0.4 0.3],...
    'Tag','STOCSY analysis v 1.0',...
    'Callback', {@doBin});
%hHelpPCAButton = 
uicontrol(...
    'Parent',hSTOCSYProcessPanel,...
    'Style','PushButton',...
    'String','Help',...
    'Units','normalized',...
    'TooltipString','Open the GNAT PDF Manual',...
    'Position',[0.55 0.2 0.4 0.3],...
    'Tag','STOCSY',...
    'Callback', @HelpButton);

% ------ peak ID
hpeakPanel=uipanel(...
    'Parent',hTabSTOCSY,...
    'Title','Set regions',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.33 0.5 0.3 0.45 ]);
%hSetPeakButton = 
uicontrol(...
    'Parent',hpeakPanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Mark the regions to use from STOCSY analysis',...
    'Position',[0.06 0.36 0.4 0.3],...
    'Callback',{ @MeasureButton_Callback});
hMeasureCheck = uicontrol(...
    'Parent',hpeakPanel,...
    'Style','CheckBox',...
    'String','Show',...
    'Units','normalized',...
    'TooltipString','Show selected line',...
    'Position',[0.62 0.35 0.3 0.3],...
    'Callback',{ @MeasureCheck_Callback});

% ------ Parameters for STOCSY
hPanelSTOCSYopts=uibuttongroup(...
    'Parent',hTabSTOCSY,...
    'Title','Correlation parameters',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.01 0.01 0.3 0.47]);
hSTOCSYp = uicontrol(...
    'Parent',hPanelSTOCSYopts,...
    'Style','RadioButton',...
    'String','Pearson',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hSTOCSYs = uicontrol(...
    'Parent',hPanelSTOCSYopts,...
    'Style','RadioButton',...
    'String','Spearman',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);
%hThreshold=
uicontrol(...
    'Parent',hPanelSTOCSYopts,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.5 0.6 0.4 0.3],...
    'horizontalalignment','left',...
    'String','Threshold');
hEditThresSTOCSY=uicontrol(...
    'Parent',hPanelSTOCSYopts,...
    'Style','Edit',...
    'String',num2str(0.1),...
    'BackgroundColor','w',...    
    'Units','Normalized',...
    'Position',[0.37 0.54 0.12 0.4]);

%% ---------Align spectra
% Auto alignment
hAutoPanel=uipanel(...
    'Parent',hTabAlign,...
    'Title','Auto',...
    'FontWeight','bold',...
    'Visible','Off',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.05 0.3 0.9]);
%hPushAutoAlign = 
uicontrol(...
    'Parent',hAutoPanel,...
    'Style','PushButton',...
    'String','Auto find',...
    'Units','normalized',...
    'Position',[0.2 0.7 0.3 0.1],...
    'Callback',{ @AutoAlignButton_Callback});
%hPushZeroAlign = 
uicontrol(...
    'Parent',hAutoPanel,...
    'Style','PushButton',...
    'String','Clear all',...
    'Units','normalized',...
    'Position',[0.5 0.7 0.3 0.1],...
    'Callback',{ @ZeroAlignButton_Callback});
hCheckApplyFT=uicontrol(...
    'Parent',hAutoPanel,...
    'Style','checkbox',...
    'Units','Normalized',...
    'Value',0,...
    'TooltipString','Use the line broadening function',...
    'Position',[0.3 0.1 0.1 0.1 ]);
%hTextAutoApply=
uicontrol(...
    'Parent',hAutoPanel,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Horizontalalignment','left',...
    'Position',[0.41 0.08 0.5 0.1 ],...
    'String','Apply when FT' );
%hTextLinearAlign = 
uicontrol(...
    'Parent',hAutoPanel,...
    'Style','text',...
    'String','Add linear (Hz):',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'Position',[0.34 0.52 0.4 0.1]);
%hTextLinearAlignUse = 
uicontrol(...
    'Parent',hAutoPanel,...
    'Style','text',...
    'String','Use',...
    'FontWeight','bold',...
    'horizontalalignment','l',...
    'Units','normalized',...
    'Position',[0.64 0.4 0.4 0.1]);
hEditLinear=uicontrol(...
    'Parent',hAutoPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'String','0',...
    'Position',[0.4 0.4 0.1 0.1 ],...
    'CallBack', { @EditLinear_Callback});
hCheckApplyLinear=uicontrol(...
    'Parent',hAutoPanel,...
    'Style','checkbox',...
    'Units','Normalized',...
    'Value',0,...
    'TooltipString','Use the linear frequence shift',...
    'Position',[0.55 0.40 0.1 0.1 ]);

% Manual alignment
hManualPanel=uipanel(...
    'Parent',hTabAlign,...
    'Title','Manual shift',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.05 0.3 0.9]);
hShiftPanel=uipanel(...
    'Parent',hManualPanel,...
    'FontWeight','bold',...
    'BorderType','None',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.35,1.0,0.65]);
hSliderShift=uicontrol(...
    'Parent',hShiftPanel,...
    'Style','slider',...
    'Units','Normalized',...
    'Min' ,-10000,'Max',10000, ...
    'Position',[0.05,0.7,0.9,0.2], ...
    'Value', 0,...
    'SliderStep',[1/20000 10/20000], ...
    'CallBack', { @SliderShift_Callback});
hEditShift=uicontrol(...
    'Parent',hShiftPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Chemical shift correction (Hz)',...
    'Position',[0.3 0.4 0.4 0.2 ],...
    'CallBack', { @EditShift_Callback});

%hButtonPlusShift = 
uicontrol(...
    'Parent',hShiftPanel,...
    'Style','PushButton',...
    'String','+0.1',...
    'Units','normalized',...
    'Position',[0.52 0.05 0.2 0.2],...
    'Callback',{ @ButtonPlusShift_Callback});
%hButtonMinusShift = 
uicontrol(...
    'Parent',hShiftPanel,...
    'Style','PushButton',...
    'String','-0.1',...
    'Units','normalized',...
    'Position',[0.28 0.05 0.2 0.2],...
    'Callback',{ @ButtonMinusShift_Callback});
%hButtonPlusShift2 = 
uicontrol(...
    'Parent',hShiftPanel,...
    'Style','PushButton',...
    'String','+0.01',...
    'Units','normalized',...
    'Position',[0.72 0.05 0.2 0.2],...
    'Callback',{ @ButtonPlusShift2_Callback});
%hButtonMinusShift2 = 
uicontrol(...
    'Parent',hShiftPanel,...
    'Style','PushButton',...
    'String','-0.01',...
    'Units','normalized',...
    'Position',[0.08 0.05 0.2 0.2],...
    'Callback',{ @ButtonMinusShift2_Callback});
hCheckAutoApply=uicontrol(...
    'Parent',hManualPanel,...
    'Style','checkbox',...
    'Units','Normalized',...
    'Value',1,...
    'TooltipString','Apply current shift correction automatically',...
    'Position',[0.3 0.1 0.1 0.1 ],...
    'CallBack', { @CheckAutoApply_Callback} );
%hTextAutoApply=
uicontrol(...
    'Parent',hManualPanel,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Horizontalalignment','left',...
    'Position',[0.41 0.08 0.3 0.1 ],...
    'String','Auto apply' );
%hTextCurrent=
uicontrol(...
    'Parent',hShiftPanel,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','bold',...
    'Position',[0.1 0.35 0.2 0.2],...
    'horizontalalignment','l',...
    'String','Current:' );
%% ---------INTEGRAL
% Integrals
hIntegrateProcessPanel=uipanel(...
    'Parent',hTabIntegrate,...
    'Title','Integrals',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hSetIntegralButton = 
uicontrol(...
    'Parent',hIntegrateProcessPanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Mark the integral regions',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback',{ @SetIntegralsButton_Callback});
%hClearIntegralsButton = 
uicontrol(...
    'Parent',hIntegrateProcessPanel,...
    'Style','PushButton',...
    'String','Clear',...
    'Units','normalized',...
    'TooltipString','Clear the marked regions',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback',{ @ClearIntegralsButton_Callback});
hIntegralsShow = uicontrol(...
    'Parent',hIntegrateProcessPanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Value',0,...
    'Units','normalized',...
    'Position',[0.55 0.2 0.4 0.3],...
    'Callback',{ @IntegralsShow_Callback});
%hPickIntegralButton = 
uicontrol(...
    'Parent',hIntegrateProcessPanel,...
    'Style','PushButton',...
    'String','Auto',...
    'Units','normalized',...
    'TooltipString','Automatic integration',...
    'Position',[0.05 0.2 0.4 0.3],...
    'Callback',{ @PeakpickButton_Callback});

% Correct integrals
hIntegraCorrectPanel=uipanel(...
    'Parent',hTabIntegrate,...
    'Title','Correct integral',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.35 0.05 0.4 0.9 ]);
%hTextPeakNumber=
uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','Peak number:',...
    'FontWeight','bold',...
    'Position',[0.05 0.85 0.3 0.15 ],...
    'horizontalalignment','c');
hEditFlipPeak=uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','edit',...
    'Units','Normalized',...
    'BackgroundColor','w',...
    'String',num2str(1),...
    'Position',[0.15 0.76 0.1 0.12 ],...
    'CallBack', {@EditFlipPeak_Callback});
%hButtonFlipPlusPeak = 
uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','PushButton',...
    'String','+1',...
    'Units','normalized',...
    'Position',[0.05 0.76 0.1 0.12],...
    'Callback',{@ButtonFlipPlusPeak_Callback});
%hButtonFlipMinusPeak = 
uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','PushButton',...
    'String','-1',...
    'Units','normalized',...
    'Position',[0.25 0.76 0.1 0.12],...
    'Callback',{@ButtonFlipMinusPeak_Callback});
hIntegralsShowPeak = uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Value',0,...
    'Units','normalized',...
    'Position',[0.73 0.83 0.2 0.15],...
    'Callback',{ @IntegralsShowPeak_Callback});
hRadioScopeGlobalInt = uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','RadioButton',...
    'String','Global',...
    'Value',1,...
    'Units','normalized',...
    'Position',[0.4 0.85 0.3 0.1],...
    'Callback',{ @RadioScopeGlobalInt_Callback});
hRadioScopeIndividualInt = uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','RadioButton',...
    'String','Individual',...
    'Units','normalized',...
    'Position',[0.4 0.70 0.25 0.1],...
    'Callback',{ @RadioScopeIndividualInt_Callback});
%hPushCopyGtoIInt = 
uicontrol(...
    'Parent',hIntegraCorrectPanel,...
    'Style','PushButton',...
    'String','G to I',...
    'Units','normalized',...
    'Position',[0.73 0.73 0.15 0.1],...
    'Callback',{ @GtoIButtonInt_Callback});

% Offset correction
hOffsetPanel=uipanel(...
    'Parent',hIntegraCorrectPanel,...
    'Title','Offset',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0,0.0,0.5,0.7]);
hSliderOffset=uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','slider',...
    'TooltipString','Correct the baseline offset',...
    'Units','Normalized',...
    'Min' ,-1000,'Max',1000, ...
    'Position',[0.05,0.7,0.9,0.2], ...
    'Value', 0,...
    'SliderStep',[1/1000 10/1000], ...
    'CallBack', { @SliderOffset_Callback});
hEditOffset=uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Correct the baseline offset',...
    'Units','Normalized',...
    'String',num2str(0),...
    'Position',[0.4 0.4 0.2 0.2 ],...
    'CallBack', { @EditOffset_Callback});
%hButtonPlusOffset =
uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','PushButton',...
    'String',[char(hex2dec('D7')) ' 2'],...
    'Units','normalized',...
    'Position',[0.27 0.05 0.2 0.2],...
    'Callback',{ @ButtonPlusOffset_Callback});
%hButtonMinusOffset =
uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','PushButton',...
    'String',[char(hex2dec('F7')) ' 2'],...
    'Units','normalized',...
    'Position',[0.05 0.05 0.2 0.2],...
    'Callback',{ @ButtonMinusOffset_Callback});
hEditOffsetMult=uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString','Correct the baseline offset',...
    'Units','Normalized',...
    'String',num2str(1),...
    'Position',[0.55 0.05 0.3 0.2 ],...
    'CallBack', { @EditOffsetMult_Callback});
%hTextMaxOffset=
uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','1000',...
    'Position',[0.7 0.39 0.2 0.2 ],...
    'horizontalalignment','c');
%hTextMinOffset=
uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','-1000',...
    'Position',[0.1 0.39 0.2 0.2 ],...
    'horizontalalignment','c');
uicontrol(...
    'Parent',hOffsetPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','mult',...
    'Position',[0.56 0.22 0.3 0.2 ],...
    'horizontalalignment','c');

% Tilt correction
hTiltPanel=uipanel(...
    'Parent',hIntegraCorrectPanel,...
    'Title','Tilt',...
    'FontWeight','bold',...
    'ForegroundColor','Black',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.5,0.0,0.5,0.7]);
hSliderTilt=uicontrol(...
    'Parent',hTiltPanel,...
    'Style','slider',...
         'TooltipString','Correct the baseline tilt',...
    'Units','Normalized',...
    'Min' ,-1000,'Max',1000, ...
    'Position',[0.05,0.7,0.9,0.2], ...
    'Value', 0,...
    'SliderStep',[1/1000 10/1000], ...
    'CallBack', { @SliderTilt_Callback});
hEditTilt=uicontrol(...
    'Parent',hTiltPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Correct the baseline tilt',...
    'String',num2str(0),...
    'Position',[0.4 0.4 0.2 0.2 ],...
    'CallBack', { @EditTilt_Callback});
%hButtonPlusTilt =
uicontrol(...
    'Parent',hTiltPanel,...
    'Style','PushButton',...
    'TooltipString','Correct the baseline tilt',...
    'String',[char(hex2dec('D7')) ' 2'],...
    'Units','normalized',...
    'Position',[0.27 0.05 0.2 0.2],...
    'Callback',{ @ButtonPlusTilt_Callback});
%hButtonMinusTilt =
uicontrol(...
    'Parent',hTiltPanel,...
    'Style','PushButton',...
    'TooltipString','Correct the baseline tilt',...
    'String',[char(hex2dec('F7')) ' 2'],...
    'Units','normalized',...
    'Position',[0.05 0.05 0.2 0.2],...
    'Callback',{ @ButtonMinusTilt_Callback});
%hTextMaxTilt=
uicontrol(...
    'Parent',hTiltPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','1000',...
    'Position',[0.7 0.39 0.3 0.2 ],...
    'horizontalalignment','c');
%hTextMinTilt=
uicontrol(...
    'Parent',hTiltPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','-1000',...
    'Position',[0.0 0.39 0.3 0.2 ],...
    'horizontalalignment','c');
uicontrol(...
    'Parent',hTiltPanel,...
    'Style','text',...
    'Units','Normalized',...
    'String','mult',...
    'Position',[0.56 0.22 0.3 0.2 ],...
    'horizontalalignment','c');
hEditTiltMult=uicontrol(...
    'Parent',hTiltPanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','Correct the baseline tilt',...
    'String',num2str(1),...
    'Position',[0.55 0.05 0.3 0.2 ],...
    'CallBack', { @EditTiltMult_Callback});

% Normalise
hPanelNormalizeIntegrals=uipanel(...
    'Parent',hTabIntegrate,...
    'Units','Normalized',...
    'Position',[0.78 0.05 0.2 0.9 ],...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Title','Normalise' );
hBGroupNormalise=uibuttongroup(...
    'Parent',hPanelNormalizeIntegrals,...
    'Title','',...
    'BorderType','None',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.0 0.4 1 0.6 ],...
    'SelectionChangeFcn', { @GroupNormalise_Callback});
hRadio1Normalise = uicontrol(...
    'Parent',hBGroupNormalise,...
    'Style','RadioButton',...
    'String','Peak',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2Normalise = uicontrol(...
    'Parent',hBGroupNormalise,...
    'Style','RadioButton',...
    'String','Total',...
    'Units','normalized',...
    'Position',[0.05 0.4 0.9 0.3]);
hRadio3Normalise = uicontrol(...
    'Parent',hBGroupNormalise,...
    'Style','RadioButton',...
    'String','Absolute',...
    'Units','normalized',...
    'Position',[0.05 0.1 0.9 0.3]);
hEditNorm=uicontrol(...
    'Parent',hPanelNormalizeIntegrals,...
    'Style','edit',...
    'BackgroundColor','w',...
    'TooltipString',...
    'Normalisation factor',...
    'String',100,...
    'Units','Normalized',...
    'Position',[0.35 0.2 0.3 0.1 ],...
    'CallBack', { @EditNorm_Callback});
%hTextNorm=
uicontrol(...
    'Parent',hPanelNormalizeIntegrals,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.15 0.35 1 0.1 ],...
    'horizontalalignment','l',...
    'String','Normalisation factor' );
hEditNormPeak=uicontrol(...
    'Parent',hPanelNormalizeIntegrals,...
    'Style','edit',...
    'BackgroundColor','w',...
    'String',1,...
    'TooltipString',...
    'Normalise to peak number',...
    'Units','Normalized',...
    'Position',[0.4 0.05 0.2 0.1 ],...
    'CallBack', { @EditNormPeak_Callback});
%hTextNormPeak=
uicontrol(...
    'Parent',hPanelNormalizeIntegrals,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.1 0.05 0.3 0.1 ],...
    'horizontalalignment','l',...
    'String','Peak' );

% Import/Export
hExportPanelIntegrate=uipanel(...
    'Parent',hTabIntegrate,...
    'Title','Import / Export',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.02 0.05 0.3 0.45 ]);
%hTextIntegralsExport=
uicontrol(...
    'Parent',hExportPanelIntegrate,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.05 0.60 0.2 0.3 ],...
    'horizontalalignment','l',...
    'String','Export' );
%hExportIntegralButton = 
uicontrol(...
    'Parent',hExportPanelIntegrate,...
    'Style','PushButton',...
    'String','Integrals',...
    'Units','normalized',...
    'TooltipString','Export integrals',...
    'Position',[0.65 0.6 0.3 0.3],...
    'Callback',{ @ExportIntegralButton_Callback});
%hExportIntegralSetsButton = 
uicontrol(...
    'Parent',hExportPanelIntegrate,...
    'Style','PushButton',...
    'String','Settings',...
    'Units','normalized',...
    'TooltipString','Export integral settings',...
    'Position',[0.25 0.6 0.3 0.3],...
    'Callback',{ @ExportIntegralSetButton_Callback});
%hTextIntegralsImport=
uicontrol(...
    'Parent',hExportPanelIntegrate,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.05 0.20 0.2 0.3],...
    'horizontalalignment','l',...
    'String','Import' );
%hImportIntegralSetsButton = 
uicontrol(...
    'Parent',hExportPanelIntegrate,...
    'Style','PushButton',...
    'String','Settings',...
    'Units','normalized',...
    'TooltipString','Import integral settings',...
    'Position',[0.25 0.2 0.3 0.3],...
    'Callback',{ @ImportIntegralSetButton_Callback});
%% ---------SIGNAL-TO-NOISE
% Process
hSNRProcessPanel=uipanel(...
    'Parent',hTabSNR,...
    'Title','Process',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hProcessSNRButton = 
uicontrol(...
    'Parent',hSNRProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @doSNR});

% Noise region
hSNRPanel=uipanel(...
    'Parent',hTabSNR,...
    'Title','Noise region',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.35 0.05 0.3 0.45 ]);
%hSetIntegralButton = 
uicontrol(...
    'Parent',hSNRPanel,...
    'Style','PushButton',...
    'String','Set',...
    'Units','normalized',...
    'TooltipString','Mark the integral regions',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback',{ @SetNoiseButton_Callback});
%hClearIntegralsButton = 
uicontrol(...
    'Parent',hSNRPanel,...
    'Style','PushButton',...
    'String','Clear',...
    'Units','normalized',...
    'TooltipString','Clear the marked regions',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback',{ @ClearNoiseButton_Callback});
hSNRShow = uicontrol(...
    'Parent',hSNRPanel,...
    'Style','Checkbox',...
    'String','Show',...
    'Value',0,...
    'Units','normalized',...
    'Position',[0.35 0.2 0.4 0.3],...
    'Callback',{ @NoiseShow_Callback});

% Peal pick
hBGroupSNR=uibuttongroup(...
    'Parent',hTabSNR,...
    'Title','Peak pick',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.5 0.3 0.45 ]);
hRadio1SNR = uicontrol(...
    'Parent',hBGroupSNR,...
    'Style','RadioButton',...
    'String','Peak pick',...
    'Units','normalized',...
    'Position',[0.05 0.6 0.9 0.3]);
hRadio2SNR = uicontrol(...
    'Parent',hBGroupSNR,...
    'Style','RadioButton',...
    'String','Integrals',...
    'Units','normalized',...
    'Position',[0.05 0.2 0.9 0.3]);
%% ---------SEGWE(D2MW)
            hSEGWEPanel=uipanel(...
                'Parent',hTabSEGWE,...
                'BorderType','None',...
                'ForegroundColor','Blue',...
                'Units','Normalized',...
                'Position',[0.01,0.01,0.99,0.995]);

            %	Start button
            uicontrol(...
                'Parent',hSEGWEPanel,...
                'Style','PushButton',...
                'Visible','On',...
                'Units','Normalized',...
                'Enable','On',...
                'FontSize',10,...
                'String','Initiate',...
                'TooltipString','Initiate SEGWE Calculator in a new window',...
                'Position',[0.2 0.65 0.45 0.15 ],...
                'CallBack', {@start_segwe});
%% ---------PARAFAC

% Process
hPARAFACProcessPanel=uipanel(...
    'Parent',hTabPARAFAC,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01 0.5 0.3 0.45 ]);
%hProcessPARAFACButton = 
uicontrol(...
    'Parent',hPARAFACProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.05 0.6 0.4 0.3],...
    'Callback', { @doPARAFAC});
%hReplotPARAFACButton = 
uicontrol(...
    'Parent',hPARAFACProcessPanel,...
    'Style','PushButton',...
    'String','Replot',...
    'Units','normalized',...
    'TooltipString','Replot the data from the last fit',...
    'Position',[0.55 0.6 0.4 0.3],...
    'Callback', { @replotPARAFAC});
%hReplotResidualsButton = 
uicontrol(...
    'Parent',hPARAFACProcessPanel,...
    'Style','PushButton',...
    'String','3D Residuals',...
    'Units','normalized',...
    'TooltipString','Replot 3D residuals from the last fit',...
    'Position',[0.55 0.15 0.4 0.3],...
    'Callback', { @residualsPARAFAC});

% Components
hPARAFACNcompPanel=uipanel(...
    'Parent',hTabPARAFAC,...
    'Title','Components',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.32 0.5 0.15 0.45 ]);
hEditNcompPARAFAC=uicontrol(...
    'Parent',hPARAFACNcompPanel,...
    'Style','edit',...
    'String',2,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to search for in the mixture spectrum',...
    'Units','Normalized',...
    'Position',[0.35 0.3 0.3 0.3 ]);
%hTextNcompPARAFAC=
uicontrol(...
    'Parent',hPARAFACNcompPanel,...
    'Style','text',...
    'String','Fitted components',...
    'TooltipString',...
    'Number of (estimated) components in the mixture spectrum',...
    'Units','Normalized',...
    'Position',[0.1 0.6 0.8 0.3 ],...
    'horizontalalignment','c');

% Constrain
hPanelPARAFACConstrain=uipanel(...
    'Parent',hTabPARAFAC,...
    'Title','Constrain',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.65 0.05 0.34 0.9 ]);
%hTextMode=
uicontrol(...
    'Parent',hPanelPARAFACConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'Position',[0.25 0.86 0.2 0.1 ],...
    'horizontalalignment','c',...
    'FontWeight','bold',...
    'String','Mode' );    
%hTextModeNr1=
uicontrol(...
    'Parent',hPanelPARAFACConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','normal',...
    'Position',[0.1 0.77 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String',' 1' ); 
%hTextModeNr2=
uicontrol(...
    'Parent',hPanelPARAFACConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','normal',...
    'Position',[0.25 0.77 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String',' 2' );
%hTextModeNr3=
uicontrol(...
    'Parent',hPanelPARAFACConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','normal',...
    'Position',[0.40 0.77 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String',' 3' );
%hTextModeNr4=
uicontrol(...
    'Parent',hPanelPARAFACConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','normal',...
    'Position',[0.55 0.77 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String',' 4' );

% Initialisation
hGroupInit=uibuttongroup(...
    'Parent',hTabPARAFAC,...
    'Title','Initialisation',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.48 0.05 0.16 0.9 ]);
hRadioInit1 = uicontrol(...
    'Parent',hGroupInit,...
    'Style','RadioButton',...
    'String','DTLD',...
    'Units','normalized',...
    'Position',[0.05 0.8 0.8 0.2]);
hRadioInit2 = uicontrol(...
    'Parent',hGroupInit,...
    'Style','RadioButton',...
    'String','SVD',...
    'Units','normalized',...
    'Position',[0.05 0.55 0.8 0.2]);
hRadioInit3 = uicontrol(...
    'Parent',hGroupInit,...
    'Style','RadioButton',...
    'String','Random',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.8 0.2]);
hRadioInit4 = uicontrol(...
    'Parent',hGroupInit,...
    'Style','RadioButton',...
    'String','10 best',...
    'Units','normalized',...
    'Position',[0.05 0.05 0.8 0.2]);
hGroupMode1=uibuttongroup(...
    'Parent',hPanelPARAFACConstrain,...
    'Title','',...
    'FontWeight','normal',...
    'Bordertype','none',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.05 0.0 0.2 0.8 ]);
hRadioConst1none = uicontrol(...
    'Parent',hGroupMode1,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.8 0.5 0.2]);
hRadioConst1ortho = uicontrol(...
    'Parent',hGroupMode1,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.55 0.5 0.2]);
hRadioConst1nneg = uicontrol(...
    'Parent',hGroupMode1,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.3 0.5 0.2]);
hRadioConst1unimod = uicontrol(...
    'Parent',hGroupMode1,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.05 0.5 0.2]);
hGroupMode2=uibuttongroup(...
    'Parent',hPanelPARAFACConstrain,...
    'Title','',...
    'FontWeight','normal',...
    'Bordertype','none',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.2 0.0 0.2 0.8 ]);
hRadioConst2none = uicontrol(...
    'Parent',hGroupMode2,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.8 0.5 0.2]);
hRadioConst2ortho = uicontrol(...
    'Parent',hGroupMode2,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.55 0.5 0.2]);
hRadioConst2nneg = uicontrol(...
    'Parent',hGroupMode2,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.3 0.5 0.2]);
hRadioConst2unimod = uicontrol(...
    'Parent',hGroupMode2,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.05 0.5 0.2]);
hGroupMode3=uibuttongroup(...
    'Parent',hPanelPARAFACConstrain,...
    'Title','',...
    'FontWeight','normal',...
    'Bordertype','none',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.35 0.0 0.55 0.8 ]);
hRadioConst3none = uicontrol(...
    'Parent',hGroupMode3,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.1 0.8 0.9 0.2]);
hRadioConst3ortho = uicontrol(...
    'Parent',hGroupMode3,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.1 0.55 0.9 0.2]);
hRadioConst3nneg = uicontrol(...
    'Parent',hGroupMode3,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.1 0.3 0.9 0.2]);
hRadioConst3unimod = uicontrol(...
    'Parent',hGroupMode3,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.1 0.05 0.9 0.2]);
hGroupMode4=uibuttongroup(...
    'Parent',hPanelPARAFACConstrain,...
    'Title','',...
    'FontWeight','normal',...
    'Bordertype','none',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.5 0.0 0.55 0.8 ]);
hRadioConst4none = uicontrol(...
    'Parent',hGroupMode4,...
    'Style','RadioButton',...
    'String','  None',...
    'Units','normalized',...
    'Position',[0.1 0.8 0.9 0.2]);
hRadioConst4ortho = uicontrol(...
    'Parent',hGroupMode4,...
    'Style','RadioButton',...
    'String','  Orthogonal',...
    'Units','normalized',...
    'Position',[0.1 0.55 0.9 0.2]);
hRadioConst4nneg = uicontrol(...
    'Parent',hGroupMode4,...
    'Style','RadioButton',...
    'String','  Non-negative',...
    'Units','normalized',...
    'Position',[0.1 0.3 0.9 0.2]);
hRadioConst4unimod = uicontrol(...
    'Parent',hGroupMode4,...
    'Style','RadioButton',...
    'String','  Unimodal',...
    'Units','normalized',...
    'Position',[0.1 0.05 0.9 0.2]);


% Plots
hPanelPARAFACPlots=uipanel(...
    'Parent',hTabPARAFAC,...
    'Title','Plots',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.01 0.05 0.3 0.45 ]);
hSepPlotUse = uicontrol(...
    'Parent',hPanelPARAFACPlots,...
    'Style','Checkbox',...
    'String','Separate plots',...
    'TooltipString','Turn on/off inherent PARAFAC plots',...
    'Units','normalized',...
    'Position',[0.05 0.65 0.9 0.3]);
hAutoPlotUse = uicontrol(...
    'Parent',hPanelPARAFACPlots,...
    'Style','Checkbox',...
    'String','Auto plots',...
    'Value',1,...
    'TooltipString','Turn on/off component plots',...
    'Units','normalized',...
    'Position',[0.05 0.35 0.9 0.3]);
hResidualPlotUse = uicontrol(...
    'Parent',hPanelPARAFACPlots,...
    'Style','Checkbox',...
    'String','Residual 3D plots',...
    'TooltipString','Turn on/off Residual 3D plots',...
    'Units','normalized',...
    'Position',[0.05 0.05 0.9 0.3]);

%% ---------SLICING

% Process
hSLICINGProcessPanel=uipanel(...
    'Parent',hTabSLICING,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.01 0.5 0.3 0.45 ]);
%hProcessSLICINGButton = 
uicontrol(...
    'Parent',hSLICINGProcessPanel,...
    'Style','PushButton',...
    'String','Run',...
    'Units','normalized',...
    'TooltipString','Process with current parameters',...
    'Position',[0.3 0.50 0.4 0.4],...
    'Callback', { @doSLICING});

% Components
hSLICINGNcompPanel=uipanel(...
    'Parent',hTabSLICING,...
    'Title','Components',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.32 0.5 0.15 0.45 ]);
hEditNcompSLICING=uicontrol(...
    'Parent',hSLICINGNcompPanel,...
    'Style','edit',...
    'String',2,...
    'BackgroundColor','w',...
    'TooltipString',...
    'Number of components to search for in the mixture spectrum',...
    'Units','Normalized',...
    'Position',[0.35 0.3 0.3 0.3 ]);
%hTextNcompSLICING=
uicontrol(...
    'Parent',hSLICINGNcompPanel,...
    'Style','text',...
    'String','Fitted components',...
    'TooltipString',...
    'Number of (estimated) components in the mixture spectrum',...
    'Units','Normalized',...
    'Position',[0.1 0.6 0.8 0.3 ],...
    'horizontalalignment','c');

% Constrain
hPanelSLICINGConstrain=uipanel(...
    'Parent',hTabSLICING,...
    'Title','Constrain',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.65 0.05 0.34 0.9 ]);
%hTextMode=
uicontrol(...
    'Parent',hPanelSLICINGConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','bold',...
    'Position',[0.25 0.86 0.2 0.1 ],...
    'horizontalalignment','c',...
    'String','Mode' );
%hTextModeNr1=
uicontrol(...
    'Parent',hPanelSLICINGConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','normal',...
    'Position',[0.1 0.77 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String',' 1' );
%hTextModeNr2=
uicontrol(...
    'Parent',hPanelSLICINGConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','normal',...
    'Position',[0.30 0.77 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String',' 2' );
%hTextModeNr3=
uicontrol(...
    'Parent',hPanelSLICINGConstrain,...
    'Style','text',...
    'Units','Normalized',...
    'Visible','On',...
    'FontWeight','normal',...
    'Position',[0.50 0.77 0.5 0.1 ],...
    'horizontalalignment','l',...
    'String',' 3' );

% Initialization
hGroupInitSLICING=uibuttongroup(...
    'Parent',hTabSLICING,...
    'Title','Initialisation',...
    'FontWeight','normal',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.48 0.05 0.16 0.9 ]);
hRadioInit1SLICING = uicontrol(...
    'Parent',hGroupInitSLICING,...
    'Style','RadioButton',...
    'String','DTLD',...
    'Units','normalized',...
    'Position',[0.05 0.8 0.8 0.2]);
hRadioInit2SLICING = uicontrol(...
    'Parent',hGroupInitSLICING,...
    'Style','RadioButton',...
    'String','SVD',...
    'Units','normalized',...
    'Position',[0.05 0.55 0.8 0.2]);
hRadioInit3SLICING = uicontrol(...
    'Parent',hGroupInitSLICING,...
    'Style','RadioButton',...
    'String','Random',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.8 0.2]);
hRadioInit4SLICING = uicontrol(...
    'Parent',hGroupInitSLICING,...
    'Style','RadioButton',...
    'String','10 best',...
    'Units','normalized',...
    'Position',[0.05 0.05 0.8 0.2]);
hGroupMode1SLICING=uibuttongroup(...
    'Parent',hPanelSLICINGConstrain,...
    'Title','',...
    'FontWeight','normal',...
    'Bordertype','none',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.05 0.0 0.2 0.8 ]);
hRadioConst1noneSLICING = uicontrol(...
    'Parent',hGroupMode1SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.8 0.5 0.2]);
hRadioConst1orthoSLICING = uicontrol(...
    'Parent',hGroupMode1SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.55 0.5 0.2]);
hRadioConst1nnegSLICING = uicontrol(...
    'Parent',hGroupMode1SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.3 0.5 0.2]);
hRadioConst1unimodSLICING = uicontrol(...
    'Parent',hGroupMode1SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.05 0.5 0.2]);
hGroupMode2SLICING=uibuttongroup(...
    'Parent',hPanelSLICINGConstrain,...
    'Title','',...
    'FontWeight','normal',...
    'Bordertype','none',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.25 0.0 0.2 0.8 ]);
hRadioConst2noneSLICING = uicontrol(...
    'Parent',hGroupMode2SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.8 0.5 0.2]);
hRadioConst2orthoSLICING = uicontrol(...
    'Parent',hGroupMode2SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.55 0.5 0.2]);
hRadioConst2nnegSLICING = uicontrol(...
    'Parent',hGroupMode2SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.3 0.5 0.2]);
hRadioConst2unimodSLICING = uicontrol(...
    'Parent',hGroupMode2SLICING,...
    'Style','RadioButton',...
    'String','',...
    'Units','normalized',...
    'Position',[0.25 0.05 0.5 0.2]);
hGroupMode3SLICING=uibuttongroup(...
    'Parent',hPanelSLICINGConstrain,...
    'Title','',...
    'FontWeight','normal',...
    'Bordertype','none',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.45 0.0 0.55 0.8 ]);
hRadioConst3noneSLICING = uicontrol(...
    'Parent',hGroupMode3SLICING,...
    'Style','RadioButton',...
    'String','  None',...
    'Units','normalized',...
    'Position',[0.1 0.8 0.9 0.2]);
hRadioConst3orthoSLICING = uicontrol(...
    'Parent',hGroupMode3SLICING,...
    'Style','RadioButton',...
    'String','  Orthogonal',...
    'Units','normalized',...
    'Position',[0.1 0.55 0.9 0.2]);
hRadioConst3nnegSLICING = uicontrol(...
    'Parent',hGroupMode3SLICING,...
    'Style','RadioButton',...
    'String','  Non-negative',...
    'Units','normalized',...
    'Position',[0.1 0.3 0.9 0.2]);
hRadioConst3unimodSLICING = uicontrol(...
    'Parent',hGroupMode3SLICING,...
    'Style','RadioButton',...
    'String','  Unimodal',...
    'Units','normalized',...
    'Position',[0.1 0.05 0.9 0.2]);

% Plots
hPanelSLICINGPlots=uipanel(...
    'Parent',hTabSLICING,...
    'Title','Plots',...
    'FontWeight','bold',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'Position',[0.01 0.05 0.3 0.45 ]);
%hSepPlotUseSLICING = 
uicontrol(...
    'Parent',hPanelSLICINGPlots,...
    'Style','Checkbox',...
    'String','Separate plots',...
    'TooltipString','Turn on/off inherent Slicing plots',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hAutoPlotUseSLICING = uicontrol(...
    'Parent',hPanelSLICINGPlots,...
    'Style','Checkbox',...
    'String','Auto plots',...
    'Value',1,...
    'TooltipString','Turn on/off component plots',...
    'Units','normalized',...
    'Position',[0.05 0.3 0.9 0.3]);


%% ---------ICOSHIFT

% Align
hIcoshiftProcessPanel=uipanel(...
    'Parent',hTabIcoshift,...
    'Title','Align',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.65 0.3 0.3 ]);
%hButtonICOAlign = 
uicontrol(...
    'Parent',hIcoshiftProcessPanel,...
    'Style','PushButton',...
    'String','Align',...
    'Units','normalized',...
    'TooltipString','Align spectra using icoshift',...
    'Position',[0.35 0.3 0.3 0.5],...
    'Callback', { @ButtonICOAlign_Callback});

% Alignment mode 
hBPanelIcoshiftMode=uibuttongroup(...
    'Parent',hTabIcoshift,...
    'Title','Alignment mode',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.35 0.05 0.3 0.9 ],...
    'SelectionChangeFcn', { @GroupIcoshiftMode_Callback});
hBGroupIcoshiftMode=uibuttongroup(...
    'Parent',hBPanelIcoshiftMode,...
    'Title','',...
    'BorderType','None',...
    'Units','Normalized',...
    'Position',[0.0 0.45 1.0 0.5 ],...
    'SelectionChangeFcn', { @GroupIcoshiftMode_Callback});
hRadio1IcoshiftMode = uicontrol(...
    'Parent',hBGroupIcoshiftMode,...
    'Style','RadioButton',...
    'String','Interactive',...
    'Units','normalized',...
    'Position',[0.05 0.7 0.9 0.3]);
hRadio2IcoshiftMode = uicontrol(...
    'Parent',hBGroupIcoshiftMode,...
    'Style','RadioButton',...
    'String','Fixed interval',...
    'Units','normalized',...
    'Position',[0.05 0.0 0.9 0.3]);
hRadio3IcoshiftMode = uicontrol(...
    'Parent',hBGroupIcoshiftMode,...
    'Style','RadioButton',...
    'String','Whole',...
    'Units','normalized',...
    'Position',[0.05 0.35 0.9 0.3]);
hEditIntervals=uicontrol(...
    'Parent',hBPanelIcoshiftMode,...
    'Style','edit',...
    'BackgroundColor','w',...
    'String',100,...
    'Units','Normalized',...
    'Position',[0.4 0.25 0.3 0.15 ],...
    'CallBack', { @EditIntervals_Callback});
%hTextIntervals=
uicontrol(...
    'Parent',hBPanelIcoshiftMode,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.2 0.21 0.2 0.15 ],...
    'horizontalalignment','l',...
    'String','Intervals' );

% Target vector
hBGroupIcoshiftTarget=uibuttongroup(...
    'Parent',hTabIcoshift,...
    'Title','Target vector',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.68 0.05 0.3 0.9 ]);
hRadio1IcoshiftTarget = uicontrol(...
    'Parent',hBGroupIcoshiftTarget,...
    'Style','RadioButton',...
    'String','Average',...
    'Units','normalized',...
    'Position',[0.05 0.75 0.9 0.3]);
hRadio2IcoshiftTarget = uicontrol(...
    'Parent',hBGroupIcoshiftTarget,...
    'Style','RadioButton',...
    'String','Median',...
    'Units','normalized',...
    'Position',[0.05 0.55 0.9 0.3]);
hRadio3IcoshiftTarget = uicontrol(...
    'Parent',hBGroupIcoshiftTarget,...
    'Style','RadioButton',...
    'String','Max.',...
    'Units','normalized',...
    'Position',[0.05 0.35 0.9 0.3]);
hRadio4IcoshiftTarget = uicontrol(...
    'Parent',hBGroupIcoshiftTarget,...
    'Style','RadioButton',...
    'String','Average2',...
    'Units','normalized',...
    'Position',[0.05 0.15 0.9 0.3]);

%% ---------Neural Netowrk
% Measure
hNNSelectionPanel=uipanel(...
    'Parent', hTabNeuralNetwork,...
    'Title','Neural Network Selection',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.02 0.005 0.45 0.45 ]);
%hButtonNNSelect=
uicontrol(...
    'Parent',hNNSelectionPanel,...
    'Style','Text',...
    'String','PSYCHE High Flip Angle',...
    'FontWeight','bold',...
    'Units','normalized',...
    'horizontalalignment','c',...
    'Position',[0 0.1 0.65 0.2]);
hNN1Check = uicontrol(...
    'Parent',hNNSelectionPanel,...
    'Style','Checkbox',...
    'String','',...
    'Units','normalized',...
    'Value',0,...
    'TooltipString','Choose this neural network',...
    'Position',[0.65 0.1 0.2 0.2]);
uicontrol(...
    'Parent',hNNSelectionPanel,...
    'Style','Text',...
    'String','PSYCHE Strong Coupling',...
    'FontWeight','bold',...
    'Units','normalized',...
    'horizontalalignment','c',...
    'Position',[0 0.52 0.65 0.2]);
hNN2Check = uicontrol(...
    'Parent',hNNSelectionPanel,...
    'Style','Checkbox',...
    'String','',...
    'Units','normalized',...
    'Value',0,...
    'TooltipString','Choose this neural network',...
    'Position',[0.65 0.55 0.2 0.2]);
hNNProcessPanel=uipanel(...
    'Parent',hTabNeuralNetwork,...
    'Title','Process',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.5 0.005 0.45 0.6 ]);
hNNPlotPanel=uipanel(...
    'Parent',hTabNeuralNetwork,...
    'Title','Plot options',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.02 0.5 0.45 0.45 ]);
hSepPlotCheck = uicontrol(...
    'Parent',hNNPlotPanel,...
    'Style','Checkbox',...
    'String','',...
    'Units','normalized',...
    'Value',0,...
    'TooltipString','Choose this neural network',...
    'Position',[0.75 0.45 0.2 0.2]);
uicontrol(...
    'Parent',hNNPlotPanel,...
    'Style','Text',...
    'String','Separate plot',...
    'FontWeight','bold',...
    'Units','normalized',...
    'horizontalalignment','c',...
    'Position',[0 0.425 0.65 0.2]);
hNNScalePanel=uipanel(...
    'Parent',hTabNeuralNetwork,...
    'Title','Scaling',...
    'Visible','On',...
    'TitlePosition','centertop',...
    'FontWeight','bold',...
    'Units','Normalized',...
    'Position',[0.5 0.65 0.45 0.3 ]);
%hButtonNNPureshift=
uicontrol(...
    'Parent',hNNProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Convert to NN Pure shift spectrum',...
    'Position',[0.15 0.5 0.7 0.45 ],...
    'String','Convert using NN',...
    'CallBack', { @NNPureshift_Callback})
%hTextnfid=
uicontrol(...
    'Parent',hNNScalePanel,...
    'Style','text',...
    'Units','Normalized',...
    'ForegroundColor','Black',...
    'horizontalalignment','left',...
    'Position',[0.15 0.02 0.3 0.65 ],...
    'String','Normalization factor' );
hScaleNN=uicontrol(...
    'Parent',hNNScalePanel,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'String','1.0',... %Default 
    'TooltipString','Normalization factor for maximum peak',...
    'Max',1,...
    'Position',[0.6 0.18 0.3 0.63 ]);
%hButtonUndoNNPureshift=
uicontrol(...
    'Parent',hNNProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Retrieve original PS data',...
    'Position',[0.15 0.02 0.7 0.45 ],...
    'String','Unconvert NN',...
    'CallBack', { @UndoNNPureshift_Callback})
%% ---------Macros
        %hMacroRun = 
        uicontrol(...
            'Parent',hTabMacros,...
            'Style','PushButton',...
            'String','Run',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'CallBack', { @MacroRun_Callback},...
            'Position',[0.1 0.6 0.2 0.1]);
        hMacroUser1 = uicontrol(...
            'Parent',hTabMacros,...
            'Style','PushButton',...
            'String','Empty',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'CallBack', { @MacroUser1_Callback},...
            'Position',[0.5 0.8 0.2 0.1]);
        hMacroUser2 = uicontrol(...
            'Parent',hTabMacros,...
            'Style','PushButton',...
            'String','Empty',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'CallBack', { @MacroUser2_Callback},...
            'Position',[0.7 0.8 0.2 0.1]);
%% Setup default values
set(hEditDres,'string',num2str(512));
set(hEditDmax,'string',num2str(20));
set(hEditDmin,'string',num2str(0));
set(hEditTries,'string',num2str(100));
set(hEditMultexp,'string',num2str(1));
set(hEditTriesR,'string',num2str(100));
set(hEditMultexpR,'string',num2str(1));
set(hEditOrder,'string',2);
set(hEditLb,'string',num2str(0));
set(hEditGw,'string',num2str(0));
set(hEditLbRD,'string',num2str(1));
set(hEditGwRD,'string',num2str(1));
SliderPh1.value=get(hSliderPh1,'value');
SliderPh1.max=get(hSliderPh1,'max');
SliderPh1.min=get(hSliderPh1,'min');
set(hEditPh1,'string',SliderPh1.value);
set(hTextMaxPh1,'string',SliderPh1.max)
set(hTextMinPh1,'string',SliderPh1.min)
SliderPh0.value=get(hSliderPh0,'value');
SliderPh0.max=get(hSliderPh0,'max');
SliderPh0.min=get(hSliderPh0,'min');
set(hEditPh0,'string',SliderPh0.value);
set(hTextMaxPh0,'string',SliderPh0.max);
set(hTextMinPh0,'string',SliderPh0.min);
set(hBGroupNormalise,'SelectedObject',hRadio2Normalise)
set(hEditT1res,'string',num2str(256));
set(hEditT1max,'string',num2str(10));
set(hEditT1min,'string',num2str(0));
set(hEditDiffRes,'string',num2str(256));
set(hEditNp,'string',32768)
set(LP.hEditNCOEF,'string',255)
set(LP.hEditNPU,'string',4096)
set(LP.hEditNPP,'string',7)
% Read in default macros
%MacroPath=which('GNAT');
MacroPath=mfilename('fullpath');
MacroPath(end-17:end)=[];
if isunix()==1
    OSslash='/';
else
    OSslash='\';
end
MacroPath=strcat(MacroPath,OSslash);
MacroPath=strcat(MacroPath,'Macros');
MacroPath=strcat(MacroPath,OSslash);
MacroPath=strcat(MacroPath,'Defaults');
MacroPath=strcat(MacroPath,OSslash);
MacroPath1=strcat(MacroPath,'GNAT_Macro1.m');

if exist(MacroPath1,'file')    
    MacroPath1=strcat(MacroPath,'GNAT_Macro1_name.txt');
    if exist(MacroPath1,'file')
        macfid=fopen(MacroPath1);
        macname=fgetl(macfid);
        if macname==-1
            set(hMacroUser1,'String','Unnamed')
        else
            set(hMacroUser1,'String',macname)
        end
    else
        set(hMacroUser1,'String','Unnamed')
    end
end

MacroPath2=strcat(MacroPath,'GNAT_Macro2.m');

if exist(MacroPath2,'file')    
    MacroPath1=strcat(MacroPath,'GNAT_Macro2_name.txt');
    if exist(MacroPath1,'file')
        macfid=fopen(MacroPath1);
        macname=fgetl(macfid);
        if macname==-1
            set(hMacroUser2,'String','Unnamed')
        else
            set(hMacroUser2,'String',macname)
        end
    else
        set(hMacroUser2,'String','Unnamed')
    end
end


%set preferences for local version



if strcmp(NmrData.local,'yes')
end
%% Initialise data
%NOTE: I think the compiled version is happier if I declare all variables
%and initiate the struct NmrData
NmrData.tmp='';
NmrData.MessageText={''};
Initiate_NmrData();
%Put the Gui in a proper place and show it
guidata(hMainFigure,NmrData);
movegui(hMainFigure,'northwest')
if isdeployed
else
    set(hSplashFig,'Visible','Off')
end
axpath=[mpath 'axes_small.png'];
if exist(axpath,'file')
    axim=imread(axpath);
    image(hAxes,axim);
end
set(hMainFigure,'Visible','on')
%% Callbacks
%----------------MainFigure callbacks--------------------------------------
    function hMainFigure_DeleteFcn(~, ~)     
        QuitToolbox();
    end
    function Axes_ButtonDownFcn(~, ~)
    end
%% ---------Menu callbacks
    function Import_Varian(~, ~, Path)
        nargin
      %  Path
        if nargin==3
            %disp('Jo')
            [vnmrdata]=varianimport(Path);
        else
        [vnmrdata]=varianimport;
        end
        NmrData.MessageText={''};
        guidata(hMainFigure,NmrData);
        if ~isempty(vnmrdata)
            guidata(hMainFigure,NmrData); 
            Initiate_NmrData();

            NmrData.type='Varian';
            NmrData.sfrq=vnmrdata.sfrq;
            NmrData.FID=vnmrdata.FID;
            NmrData.filename=vnmrdata.filename;
            NmrData.dosyconstant=vnmrdata.dosyconstant;
            NmrData.Gzlvl=vnmrdata.Gzlvl;
            NmrData.ngrad=vnmrdata.ngrad;
            NmrData.np=vnmrdata.np;
            NmrData.ni=vnmrdata.ni;
            NmrData.sw=vnmrdata.sw;
            NmrData.sw1=vnmrdata.sw1;
            NmrData.at=vnmrdata.at;
            NmrData.sp=vnmrdata.sp;
            NmrData.sp1=vnmrdata.sp1;
            NmrData.rp=vnmrdata.procpar.rp;
            NmrData.rp1=vnmrdata.procpar.rp1;  
            NmrData.lp=vnmrdata.procpar.lp;
            NmrData.lp1=vnmrdata.procpar.lp1;   
            NmrData.gamma=vnmrdata.gamma;
            NmrData.DELTA=vnmrdata.DELTA;
            NmrData.delta=vnmrdata.delta;
            NmrData.gcal_orig=vnmrdata.DAC_to_G;
            if (isfield(vnmrdata,'arraydim'))
                NmrData.arraydim=vnmrdata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(vnmrdata,'sw1'))
                NmrData.sw1=vnmrdata.sw1;
            end
            if (isfield(vnmrdata,'nchunk'))
                NmrData.nchunk=vnmrdata.nchunk;
            end
            if (isfield(vnmrdata,'droppts'))
                NmrData.droppts=vnmrdata.droppts;
            end

            if (isfield(vnmrdata.procpar,'d2'))
                NmrData.d2=vnmrdata.procpar.d2;
                NmrData.d2_org=vnmrdata.procpar.d2;
            end

            if (isfield(vnmrdata.procpar,'bigtau'))
                NmrData.bigtau=vnmrdata.procpar.bigtau;
                NmrData.d2=vnmrdata.procpar.bigtau;
                NmrData.d2_org=vnmrdata.procpar.bigtau;
            end

            clear vnmrdata;
            guidata(hMainFigure,NmrData);

            Setup_NmrData();            

        else

        end
        NmrData.narray3=1;
        NmrData.ngrad2=NmrData.ngrad;        
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
        
        if isfield(NmrData,'xlim_spec')==1 % MJS edited to work
            scale=NmrData.xlim_spec;
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        else
            scale=[0 0];
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        end
        
    end
    function Import_Varian_Array(~, ~)
        NmrData.MessageText={''};
        guidata(hMainFigure,NmrData);
        Initiate_NmrData();
        guidata(hMainFigure,NmrData);
        [dirpath]=uigetdir('*','Choose the folder containing the numbered experiments');
        if dirpath==0
            return
        end
        dlg_title='Numbered experiments';
        dlg_prompt = {'Matlab array structure'};
        
        
        num_lines=1;
        answer=inputdlg(dlg_prompt,dlg_title,num_lines);
        answer=str2num(answer{1}); %#ok<ST2NM>
        if isempty(answer)
            return
        end

        nExp=numel(answer);
        Explist=answer;
        disp(['The experiments will be imported in this order: ',num2str(Explist)])
        for expnr = 1:nExp
            path=[dirpath '/' num2str(Explist(expnr)) '.fid'];
            [vnmrdata]=varianimport(path);
            if expnr==1
                nIncr=vnmrdata.arraydim;
                NmrData.rpInd=zeros(nExp*nIncr,1);
                NmrData.rpInd=zeros(nExp*nIncr,1);
            end
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=vnmrdata.FID(:,:);
            NmrData.rpInd((expnr-1)*nIncr+1:expnr*nIncr)=vnmrdata.procpar.rp;
            NmrData.lpInd((expnr-1)*nIncr+1:expnr*nIncr)=vnmrdata.procpar.lp;
            guidata(hMainFigure,NmrData);
        end
        disp(['The experiments was imported in this order: ',num2str(Explist)])
        NmrData.type='Varian';
        NmrData.sfrq=vnmrdata.sfrq;
        %NmrData.FID=vnmrdata.FID;
        NmrData.filename=vnmrdata.filename;
        NmrData.dosyconstant=vnmrdata.dosyconstant;
        NmrData.Gzlvl=vnmrdata.Gzlvl;
        NmrData.ngrad=nIncr;
        %NmrData.procpar=vnmrdata.procpar;
        NmrData.np=vnmrdata.np;
        NmrData.fn=NmrData.np;
        NmrData.ni=vnmrdata.ni;
        NmrData.sw=vnmrdata.sw;
        NmrData.sw1=vnmrdata.sw1;
        NmrData.at=vnmrdata.at;
        NmrData.sp=vnmrdata.sp;
        NmrData.sp1=vnmrdata.sp1;
        NmrData.rp=vnmrdata.procpar.rp;
        NmrData.rp1=vnmrdata.procpar.rp1;   %AC
        NmrData.lp=vnmrdata.procpar.lp;
        NmrData.lp1=vnmrdata.procpar.lp1;   %AC
        NmrData.gamma=vnmrdata.gamma;
        NmrData.DELTA=vnmrdata.DELTA;
        NmrData.delta=vnmrdata.delta;
        NmrData.gcal_orig=vnmrdata.DAC_to_G;
        NmrData.arraydim=nExp*nIncr;
        if (isfield(vnmrdata,'sw1'))
            NmrData.sw1=vnmrdata.sw1;
        end
        if (isfield(vnmrdata,'nchunk'))
            NmrData.nchunk=vnmrdata.nchunk;
        end
        if (isfield(vnmrdata,'droppts'))
            NmrData.droppts=vnmrdata.droppts;
        end
        %MN 7Sep12 to accomodate for T1 data
        if (isfield(vnmrdata.procpar,'d2'))
            NmrData.d2=vnmrdata.procpar.d2;
            NmrData.d2_org=vnmrdata.procpar.d2;
        end
        clear vnmrdata;
        guidata(hMainFigure,NmrData);
        % NmrData
        Setup_NmrData();
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function Import_JeolGeneric(~, ~)
        [jeoldata]=jeolimport_generic;
        if ~isempty(jeoldata)
            Initiate_NmrData();

            NmrData.type='Jeol';
            NmrData.lrfid=jeoldata.digshift;
            NmrData.sfrq=jeoldata.sfrq;
            NmrData.FID=jeoldata.FID;
            
            NmrData.filename=jeoldata.filename;
            NmrData.dosyconstant=jeoldata.dosyconstant;
            NmrData.Gzlvl=jeoldata.Gzlvl;
            NmrData.np=jeoldata.np;
            NmrData.fn=NmrData.np;
            NmrData.sw=jeoldata.sw;
            NmrData.at=jeoldata.at;
            NmrData.sp=jeoldata.sp;
            NmrData.lp=jeoldata.lp;
            NmrData.rp=jeoldata.rp;
            NmrData.gamma=jeoldata.gamma;
            NmrData.DELTA=jeoldata.DELTA;
            NmrData.delta=jeoldata.delta;
            if (isfield(jeoldata,'ngrad'))
                NmrData.ngrad=jeoldata.ngrad;
            end
            if (isfield(jeoldata,'arraydim'))
                NmrData.arraydim=jeoldata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(jeoldata,'sw1'))
                NmrData.sw1=jeoldata.sw1;
            end
            if (isfield(jeoldata,'droppts'))
                NmrData.droppts=jeoldata.droppts;
            end
            if (isfield(jeoldata,'tau'))
                NmrData.tau=jeoldata.tau;
            end
             if (isfield(jeoldata,'d2'))
                NmrData.d2=jeoldata.d2;
             end
            
            clear jeoldata;
            guidata(hMainFigure,NmrData);
            Setup_NmrData();
            
        else

        end
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function Import_Jeol(~, ~)
        [jeoldata]=jeolimport;
        
        if ~isempty(jeoldata)
            Initiate_NmrData();

            NmrData.type='Jeol';
            NmrData.lrfid=jeoldata.digshift;
            NmrData.sfrq=jeoldata.sfrq;
            NmrData.FID=jeoldata.FID;            
            NmrData.filename=jeoldata.filename;
            NmrData.dosyconstant=jeoldata.dosyconstant;
            NmrData.Gzlvl=jeoldata.Gzlvl;
            NmrData.ngrad=jeoldata.ngrad;
            NmrData.np=jeoldata.np;
            NmrData.fn=NmrData.np;
            NmrData.sw=jeoldata.sw;
            NmrData.at=jeoldata.at;
            NmrData.sp=jeoldata.sp;
            NmrData.lp=jeoldata.lp;
            NmrData.rp=jeoldata.rp;
            NmrData.gamma=jeoldata.gamma;
            NmrData.DELTA=jeoldata.DELTA;
            NmrData.delta=jeoldata.delta;
            NmrData.jeoldata.tr = jeoldata.tr;
            if (isfield(jeoldata,'arraydim'))
                NmrData.arraydim=jeoldata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(jeoldata,'sw1'))
                NmrData.sw1=jeoldata.sw1;
            end
            if (isfield(jeoldata,'droppts'))
                NmrData.droppts=jeoldata.droppts;
            end
            if (isfield(jeoldata,'tau'))
                NmrData.tau=jeoldata.tau;
            end
            if isfield(jeoldata,'vdlist')
                NmrData.d2=jeoldata.vdlist';
                NmrData.d2_org=jeoldata.vdlist';
            end

            if isfield(jeoldata,'vclist')
                NmrData.vclist=jeoldata.vclist';
                NmrData.vclist_org=jeoldata.vclist';
            end
            if isfield(jeoldata,'vcconstant')
                NmrData.vc_constant=jeoldata.vcconstant';
                NmrData.vc_constant_org=jeoldata.vcconstant';
            end

            if (isfield(jeoldata,'ngrad2')) % Unsure why the code divides by ngrad twice in Setup_NMR function
                NmrData.ngrad2=jeoldata.ngrad2*jeoldata.ngrad;
            end
            if (isfield(jeoldata,'gpnam'))
                NmrData.gpnam=jeoldata.gpnam;
            end
            if (isfield(jeoldata,'alpha'))
                NmrData.alpha=jeoldata.alpha;
            end
            
            NmrData.narray3=1;
            clear jeoldata;

            guidata(hMainFigure,NmrData);
            Setup_NmrData();
            
            % Check size of array
            dimension=NmrData.narray2;
            set(hEditNgrad,'Enable','off')

            if dimension==1 %1D and 2D data
                if NmrData.arraydim~=1
                    set(hEditNgrad,'Enable','on')
                end
                set(hEditArray2,'Enable','off')
                set(hEditArray3,'Enable','off')
            else %nD data
                set(hEditNgrad,'Enable','on')
                set(hEditArray2,'Enable','on')
                if NmrData.narray3>1
                    set(hEditArray3,'Enable','on')
                else
                    set(hEditArray3,'Enable','off')
                end
            end
            guidata(hMainFigure,NmrData);
        else
            
        end
    end
    function Import_JASON(~, ~)
        DataType = 0; % Raw Data
        [jasondata]=jasonimport(DataType,0); 
        % Cheking Data structure:
        % If the user didn't import any data
        if isnumeric(jasondata.filepath)
            return
        end  
        % If the dimensions for imported data are incorrect
        if isfield(jasondata,'nDim_error')
            if  jasondata.nDim_error==1
                return
            end
        end
      
        NmrData.MessageText={''};
        guidata(hMainFigure,NmrData);
        
        if ~isempty(jasondata)
            guidata(hMainFigure,NmrData); 
            WriteLogDispInfo(jasondata.logfile);
            Initiate_NmrData();
            NmrData.type='JASON';

            % The number of data points to left rotate the FID(s)
            NmrData.lrfid=round(jasondata.lrfid);
            NmrData.lrfidOrg=round(jasondata.lrfid); 
            NmrData.sfrq=jasondata.sfrq; %spectrometer frequency 
            NmrData.FID=jasondata.FID;
            NmrData.filename=jasondata.filename; 
            NmrData.dosyconstant=jasondata.dosyconstant; 
            NmrData.DELTA=jasondata.DELTA; 
            NmrData.delta=jasondata.delta;
            NmrData.Gzlvl=jasondata.Gzlvl;
            NmrData.ngrad=jasondata.ngrad; 
            NmrData.np=jasondata.np(1); %Number of data points
%             NmrData.ni=jasondata.ni; 
            NmrData.fn=NmrData.np; % Fourier number in directly detected dimension
            NmrData.sw=jasondata.sw; % Spectral width in directly detected dimension 
            NmrData.at=jasondata.at(1); % Acquisition time
            NmrData.sp=jasondata.sp; % Start of plot in 1st indirectly detected dimension
            NmrData.sp1=jasondata.sp1; % Start of plot in 2nd indirectly detected dimension 
            NmrData.lp=jasondata.lp; % First-order phase in directly detected dimension
            NmrData.rp=jasondata.rp; % Zero-order phase in directly detected dimension 
            NmrData.gamma=jasondata.gamma; %gyromagnetic-ratio
            NmrData.isuf= 0; 
            NmrData.jason.processing.tr=jasondata.processing.tr;
            if (isfield(jasondata,'arraydim'))
                NmrData.arraydim=jasondata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(jasondata,'sw1'))
                NmrData.sw1=jasondata.sw1; %Spectral width in 1st indirectly detected dimension
            end
            if (isfield(jasondata,'tau'))
                NmrData.tau=jasondata.tau; %?
            end
            if (isfield(jasondata,'droppts'))
                NmrData.droppts=jasondata.droppts;
            end
            if (isfield(jasondata,'ngrad2'))
                NmrData.ngrad2=jasondata.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
            end
            % Diffusion list import
            if isfield(jasondata,'vdlist')
                NmrData.d2=jasondata.vdlist';
                NmrData.d2_org=jasondata.vdlist';
            end
            if (isfield(jasondata,'gpnam'))
                NmrData.gpnam=jasondata.gpnam;
            end
            if (isfield(jasondata,'alpha'))
                NmrData.alpha=jasondata.alpha;
            end
            % Relaxation list import
            if isfield(jasondata,'vclist')
                NmrData.vclist=jasondata.vclist';
                NmrData.vclist_org=jasondata.vclist';
            end
            if isfield(jasondata,'vc_constant')
                NmrData.vc_constant=jasondata.vc_constant';
                NmrData.vc_constant_org=jasondata.vc_constant';
            end
            if (isfield(jasondata,'nuslist'))
                NmrData.nus=jasondata.nuslist;
            end
            cd (jasondata.filepath);
            clear jasondata;
            
            guidata(hMainFigure,NmrData);
            Setup_NmrData();
            
        else    
            %do nothing
        end
        set(hTextTest,'Enable','On');
      
        % Checking if clipping the data is necessary from spectra imported from JASON/DELTA
        if NmrData.jason.processing.tr ~= 0
            % Clipping data and inverse FT it
            clip = 1 - NmrData.jason.processing.tr;
            NmrData.SPECTRA = clipping(NmrData.SPECTRA, clip);
            NmrData.Specscale = clipping(NmrData.Specscale, clip);
            temp=flipud(fftshift(NmrData.SPECTRA,1));
            NmrData.FID=(ifft(temp));
%             NmrData.FID=ifft(ifftshift(NmrData.SPECTRA));

            % Correccting some parameters with this new data size
            NmrData.np=size(NmrData.SPECTRA,1);
            NmrData.fn=NmrData.np;
            NmrData.exclude=ones(1,NmrData.fn);
            NmrData.Integral=ones(1,NmrData.fn);
            NmrData.region=ones(1,NmrData.fn);
            NmrData.baselinecorr=zeros(NmrData.fn,NmrData.arraydim);
            set(hEditFn,'string',num2str(NmrData.fn));
            set(hEditNp,'string',num2str(NmrData.np));
            NmrData.sp=NmrData.Specscale(1);
            NmrData.sw=NmrData.Specscale(end)-NmrData.Specscale(1);
            NmrData.lrfid=0;
        end
        guidata(hMainFigure,NmrData);
 
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
                
        if isfield(NmrData,'xlim_spec')==1
            scale=NmrData.xlim_spec;
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        else
            scale=[0 0];
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        end
    end
    function Import_JASON_array(~, ~)
        NmrData.MessageText={''};
        Initiate_NmrData();
        guidata(hMainFigure,NmrData);

        [dirpath]=uigetdir('*','Choose the folder containing the numbered experiments');
        if dirpath==0
            return
        end
        num_lines=1;

        dlg_title='Numbered experiments';
        dlg_prompt = {'Matlab array structure'};

        % answer=inputdlg(dlg_prompt,dlg_title,num_lines);
        answer = 1:42;
        % answer=str2num(answer{1}); %#ok<ST2NM>
        
        if isempty(answer)
            return
        end

        nExp=numel(answer);
        Explist=answer;
        disp(['The experiments will be imported in this order: ',num2str(Explist)])

        if isunix==1
            OSslash='/';
        else
            OSslash='\';
        end

        % Changing the current directory
        cd(dirpath);
        % Taking the name of the files 
        ttl = dir('*.*');
        ttl = struct2cell(ttl);
        ttl = ttl(1,:);
        % Correcting the name of the files
        ttl = natsortfiles(ttl,'\d+\.?\d*','noext','rmdot');
        
        DataType = 0; % Raw Data
        for expnr = 1:nExp
            path=[dirpath OSslash char(ttl(expnr))];
            [jasondata]=jasonimport(DataType,path);
            if expnr==1
                nIncr=jasondata.arraydim;
            end
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=jasondata.FID(:,:);
        end
        NmrData.MessageText={''};
        
        if ~isempty(jasondata)
            guidata(hMainFigure,NmrData); 
            WriteLogDispInfo(jasondata.logfile);
            NmrData.type='JASON';
            % The number of data points to left rotate the FID(s)
            NmrData.lrfid=jasondata.lrfid;            
            NmrData.sfrq=jasondata.sfrq; %spectrometer frequency 
%             NmrData.FID=jasondata.FID;
            NmrData.filename=jasondata.filename; 
            NmrData.dosyconstant=jasondata.dosyconstant; 
            NmrData.DELTA=jasondata.DELTA; 
            NmrData.delta=jasondata.delta;
            NmrData.Gzlvl=jasondata.Gzlvl;
            NmrData.ngrad=jasondata.ngrad; 
            NmrData.np=jasondata.np(1); %Number of data points
%             NmrData.ni=jasondata.ni; 
            NmrData.fn=NmrData.np; % Fourier number in directly detected dimension
            NmrData.sw=jasondata.sw; % Spectral width in directly detected dimension 
            NmrData.at=jasondata.at(1); % Acquisition time
            NmrData.sp=jasondata.sp; % Start of plot in 1st indirectly detected dimension
            NmrData.sp1=jasondata.sp1; % Start of plot in 2nd indirectly detected dimension 
            NmrData.lp=jasondata.lp; % First-order phase in directly detected dimension
            NmrData.rp=jasondata.rp; % Zero-order phase in directly detected dimension 
            NmrData.gamma=jasondata.gamma; %gyromagnetic-ratio
            NmrData.isuf= 0;
            NmrData.arraydim=nExp*nIncr;
            NmrData.jason.processing.tr=jasondata.processing.tr;
            if isfield(jasondata,'vdlist')
                NmrData.d2=jasondata.vdlist';
                NmrData.d2=NmrData.d2(1:nJump:nJump*nExp);
                NmrData.d2_org=jasondata.vdlist';
                NmrData.d2_org=NmrData.d2_org(1:nJump:nJump*nExp);
            end
            if isfield(jasondata,'vclist')
                NmrData.vclist=jasondata.vclist';
                NmrData.vclist=NmrData.vclist(1:nJump:nJump*nExp);
                NmrData.vclist_org=jasondata.vclist';
                NmrData.vclist_org=NmrData.vclist_org(1:nJump:nJump*nExp);
            end

            if isfield(jasondata,'vc_constant')
                NmrData.vc_constant=jasondata.vc_constant';
                NmrData.vc_constant_org=jasondata.vc_constant';
            end
            if (isfield(jasondata,'nuslist'))
                NmrData.nus=jasondata.nuslist;
            end
            if (isfield(jasondata,'gpnam'))
                NmrData.gpnam=jasondata.gpnam;
            end
            if (isfield(jasondata,'alpha'))
                NmrData.alpha=jasondata.alpha;
            end                        
            guidata(hMainFigure,NmrData);
            Setup_NmrData();
        else
            %do nothing
        end
        set(hTextTest,'Enable','On');
        
        % Checking if clipping the data is necessary from spectra imported from JASON/DELTA
        % if NmrData.jason.processing.tr ~= 0
        %     % Clipping data and inverse FT it
        %     clip = 1 - NmrData.jason.processing.tr;
        %     NmrData.SPECTRA = clipping(NmrData.SPECTRA, clip);
        %     NmrData.Specscale = clipping(NmrData.Specscale, clip);
        %     temp=flipud(fftshift(NmrData.SPECTRA,1));
        %     NmrData.FID=(ifft(temp));
        % 
        %     % Correccting some parameters with this new data size
        %     NmrData.np=size(NmrData.SPECTRA,1);
        %     NmrData.fn=NmrData.np;
        %     NmrData.exclude=ones(1,NmrData.fn);
        %     NmrData.Integral=ones(1,NmrData.fn);
        %     NmrData.region=ones(1,NmrData.fn);
        %     NmrData.baselinecorr=zeros(NmrData.fn,NmrData.arraydim);
        %     set(hEditFn,'string',num2str(NmrData.fn));
        %     set(hEditNp,'string',num2str(NmrData.np));
        %     NmrData.sp=NmrData.Specscale(1);
        %     NmrData.sw=NmrData.Specscale(end)-NmrData.Specscale(1);
        % end

        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end        
        guidata(hMainFigure,NmrData);
                
        if isfield(NmrData,'xlim_spec')==1 % MJS edited to work
            scale=NmrData.xlim_spec;
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        else
            scale=[0 0];
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        end
    end
    function Import_JASON_Processed(~, ~)
        DataType = 1; % Processed Data
        [jasondata]=jasonimport(DataType,0);        
        if isfield(jasondata,'nDim_error')
            if  jasondata.nDim_error==1
                return
            end
        end
        NmrData.MessageText={''};
        guidata(hMainFigure,NmrData);
        
        if ~isempty(jasondata)
            guidata(hMainFigure,NmrData); 
            WriteLogDispInfo(jasondata.logfile);
            Initiate_NmrData();
            NmrData.type='JASON';

            % The number of data points to left rotate the FID(s)
            NmrData.lrfid=jasondata.lrfid;            
            NmrData.sfrq=jasondata.sfrq; %spectrometer frequency 
            NmrData.FID=jasondata.FID;
            NmrData.filename=jasondata.filename; 
            NmrData.dosyconstant=jasondata.dosyconstant; 
            NmrData.DELTA=jasondata.DELTA; 
            NmrData.delta=jasondata.delta;
            NmrData.Gzlvl=jasondata.Gzlvl;
            NmrData.ngrad=jasondata.ngrad; 
            NmrData.np=jasondata.np(1); %Number of data points
%             NmrData.ni=jasondata.ni; 
            NmrData.fn=NmrData.np; % Fourier number in directly detected dimension
            NmrData.sw=jasondata.sw; % Spectral width in directly detected dimension 
            NmrData.at=jasondata.at(1); % Acquisition time
            NmrData.sp=jasondata.sp; % Start of plot in 1st indirectly detected dimension
            NmrData.sp1=jasondata.sp1; % Start of plot in 2nd indirectly detected dimension 
            NmrData.lp=jasondata.lp; % First-order phase in directly detected dimension
            NmrData.rp=jasondata.rp; % Zero-order phase in directly detected dimension 
            NmrData.gamma=jasondata.gamma; %gyromagnetic-ratio
            NmrData.isuf= 0;
            NmrData.jason.processing.tr=jasondata.processing.tr;
            if (isfield(jasondata,'arraydim'))
                NmrData.arraydim=jasondata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(jasondata,'sw1'))
                NmrData.sw1=jasondata.sw1; %Spectral width in 1st indirectly detected dimension
            end
            if (isfield(jasondata,'tau'))
                NmrData.tau=jasondata.tau; %?
            end
            if (isfield(jasondata,'droppts'))
                NmrData.droppts=jasondata.droppts;
            end
            if (isfield(jasondata,'ngrad2'))
                NmrData.ngrad2=jasondata.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
            end
            if isfield(jasondata,'vdlist')
                NmrData.d2=jasondata.vdlist';
                NmrData.d2_org=jasondata.vdlist';
            end
            if isfield(jasondata,'vclist')
                NmrData.vclist=jasondata.vclist';
                NmrData.vclist_org=jasondata.vclist';
            end
            if isfield(jasondata,'vc_constant')
                NmrData.vc_constant=jasondata.vc_constant';
                NmrData.vc_constant_org=jasondata.vc_constant';
            end
            if (isfield(jasondata,'nuslist'))
                NmrData.nus=jasondata.nuslist;
            end
            if (isfield(jasondata,'gpnam'))
                NmrData.gpnam=jasondata.gpnam;
            end
            if (isfield(jasondata,'alpha'))
                NmrData.alpha=jasondata.alpha;
            end
            cd (jasondata.filepath);
            clear jasondata;
        
            guidata(hMainFigure,NmrData);
            Setup_NmrData();
        else
            %do nothing
        end
        set(hTextTest,'Enable','On');
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
                
        if isfield(NmrData,'xlim_spec')==1 
            scale=NmrData.xlim_spec;
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        else
            scale=[0 0];
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        end   
    end
    function Import_Bruker(~, ~, FilePath)

        if nargin==3
            %Just take the given path
        else
            %let the user choose
            FilePath=uigetdir(pwd,'Choose the directory containing the NMR experiment (ser or fid file)');
        end
        if FilePath==0
            return
        end
        [brukerdata]=brukerimport(0,FilePath);

        if isfield(brukerdata,'acqus_error')
            if  brukerdata.acqus_error==1
                return
            end
        end
        NmrData.MessageText={''};
        guidata(hMainFigure,NmrData);
        
        if ~isempty(brukerdata)
            guidata(hMainFigure,NmrData); 
            Initiate_NmrData();
            %NmrData=guidata(hMainFigure);
            % setting up the NmrData structure - I think it is safest to
            % initialise them all (for the compiled version)
            %I'll keep all points and see if I can sort out the processing
            NmrData.type='Bruker';
            NmrData.lrfid=brukerdata.digshift;
            NmrData.sfrq=brukerdata.sfrq;
            NmrData.FID=brukerdata.FID;
            NmrData.filename=brukerdata.filename;
            NmrData.dosyconstant=brukerdata.dosyconstant;
            NmrData.Gzlvl=brukerdata.Gzlvl;
            NmrData.ngrad=brukerdata.ngrad;
            NmrData.acqus=brukerdata.acqus;
            NmrData.acqu2s=brukerdata.acqu2s;
            NmrData.np=brukerdata.np;
            NmrData.ni=brukerdata.ni;
            NmrData.fn=NmrData.np;
            NmrData.sw=brukerdata.sw;
            NmrData.at=brukerdata.at;
            NmrData.sp=brukerdata.sp;
            NmrData.sp1=brukerdata.sp1;
            NmrData.lp=brukerdata.lp;
            NmrData.rp=brukerdata.rp;
            NmrData.gamma=brukerdata.gamma;
            NmrData.DELTA=brukerdata.DELTA;
            NmrData.delta=brukerdata.delta;
            NmrData.NUC1=brukerdata.acqus.NUC1;
            % Untrafast import
            if contains(brukerdata.pulprog,'dosyuf')...
                    || contains(brukerdata.pulprog,'ufdosy')
                NmrData.isuf=brukerdata.isuf;
                NmrData.flipnr=size(brukerdata.FID,2);
            else
                NmrData.isuf=0;
            end   
            
            % GNAT import
            if (isfield(brukerdata,'arraydim'))
                NmrData.arraydim=brukerdata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(brukerdata,'sw1'))
                NmrData.sw1=brukerdata.sw1;
            end
            if (isfield(brukerdata,'tau'))
                NmrData.tau=brukerdata.tau;
            end
            if (isfield(brukerdata,'droppts'))
                NmrData.droppts=brukerdata.droppts;
            end
            if (isfield(brukerdata,'ngrad2'))
                NmrData.ngrad2=brukerdata.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
            end
            if isfield(brukerdata,'vdlist')
                NmrData.d2=brukerdata.vdlist';
                NmrData.d2_org=brukerdata.vdlist';
            end
            if isfield(brukerdata,'vclist')
                NmrData.vclist=brukerdata.vclist';
                NmrData.vclist_org=brukerdata.vclist';
            end
            if isfield(brukerdata,'vc_constant')
                NmrData.vc_constant=brukerdata.vc_constant';
                NmrData.vc_constant_org=brukerdata.vc_constant';
            end
            if isfield(brukerdata,'acqus')
                NmrData.brukerdata.acqus=brukerdata.acqus;
            end
            if isfield(brukerdata,'acqu2s')
                NmrData.brukerdata.acqu2s=brukerdata.acqu2s;
            end
            if isfield(brukerdata,'acqu3s')
                NmrData.brukerdata.acqu3s=brukerdata.acqu3s;
            end
            if (isfield(brukerdata,'nuslist'))
                NmrData.nus=brukerdata.nuslist;
            end
            if (isfield(brukerdata,'gpnam'))
                NmrData.gpnam=brukerdata.gpnam;
            end
            if (isfield(brukerdata,'alpha'))
                NmrData.alpha=brukerdata.alpha;
            end
            
            clear brukerdata;            
            guidata(hMainFigure,NmrData);
           % NmrData
            Setup_NmrData();
        else
            %do nothing
        end
        set(hTextTest,'Enable','On');
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
        
       if isfield(NmrData,'xlim_spec')==1 % MJS edited to work
           scale=NmrData.xlim_spec;
           set(hEditScaleUp,'string',num2str(scale(2)));
           set(hEditScaleDown,'string',num2str(scale(1)));
       else
           scale=[0 0];
           set(hEditScaleUp,'string',num2str(scale(2)));
           set(hEditScaleDown,'string',num2str(scale(1)));
       end
    end
    function Import_Bruker_pureacq(~, ~)
        FilePath=uigetdir(pwd,'Choose the directory containing the NMR experiment (ser or fid file)');
        if FilePath==0
            return
        end
        %brukerdata=[];
        [brukerdata]=brukerimport(3,FilePath);
        if isfield(brukerdata,'acqus_error')
            if  brukerdata.acqus_error==1
                return
            end
        end
        NmrData.MessageText={''};
        guidata(hMainFigure,NmrData);
        
        if ~isempty(brukerdata)
            guidata(hMainFigure,NmrData);
            Initiate_NmrData();
            %NmrData=guidata(hMainFigure);
            % setting up the NmrData structure - I think it is safest to
            % initialise them all (for the compiled version)
            %I'll keep all points and see if I can sort out the processing
            NmrData.type='Bruker';
            NmrData.lrfid=brukerdata.digshift;
            NmrData.sfrq=brukerdata.sfrq;
            NmrData.FID=brukerdata.FID;
            NmrData.filename=brukerdata.filename;
            NmrData.dosyconstant=brukerdata.dosyconstant;
            NmrData.Gzlvl=brukerdata.Gzlvl;
            NmrData.ngrad=brukerdata.ngrad;
            NmrData.acqus=brukerdata.acqus;
            NmrData.acqu2s=brukerdata.acqu2s;
            NmrData.np=brukerdata.np;
            NmrData.ni=brukerdata.ni;
            NmrData.fn=NmrData.np;
            NmrData.sw=brukerdata.sw;
            NmrData.at=brukerdata.at;
            NmrData.sp=brukerdata.sp;
            NmrData.sp1=brukerdata.sp1;
            NmrData.lp=brukerdata.lp;
            NmrData.rp=brukerdata.rp;
            NmrData.gamma=brukerdata.gamma;
            NmrData.DELTA=brukerdata.DELTA;
            NmrData.delta=brukerdata.delta;
            if (isfield(brukerdata,'arraydim'))
                NmrData.arraydim=brukerdata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(brukerdata,'sw1'))
                NmrData.sw1=brukerdata.sw1;
            end
            if (isfield(brukerdata,'tau'))
                NmrData.tau=brukerdata.tau;
            end
            if (isfield(brukerdata,'droppts'))
                NmrData.droppts=brukerdata.droppts;
            end
            if (isfield(brukerdata,'ngrad2'))
                NmrData.ngrad2=NmrData.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
            end
            if isfield(brukerdata,'vdlist')
                NmrData.d2=brukerdata.vdlist';
                NmrData.d2_org=brukerdata.vdlist';
            end
            if isfield(brukerdata,'vclist')
                NmrData.vclist=brukerdata.vclist';
                NmrData.vclist_org=brukerdata.vclist';
            end
            if isfield(brukerdata,'vc_constant')
                NmrData.vc_constant=brukerdata.vc_constant';
                NmrData.vc_constant_org=brukerdata.vc_constant';
            end
            if isfield(brukerdata,'acqus')
                NmrData.brukerdata.acqus=brukerdata.acqus;
            end
            if isfield(brukerdata,'acqu2s')
                NmrData.brukerdata.acqu2s=brukerdata.acqu2s;
            end
            if isfield(brukerdata,'acqu3s')
                NmrData.brukerdata.acqu3s=brukerdata.acqu3s;
            end
            if (isfield(brukerdata,'nuslist'))
                NmrData.nus=brukerdata.nuslist;
            end
            if (isfield(brukerdata,'gpnam'))
                NmrData.gpnam=brukerdata.gpnam;
            end
            if (isfield(brukerdata,'alpha'))
                NmrData.alpha=brukerdata.alpha;
            end
            clear brukerdata;
            
            guidata(hMainFigure,NmrData);
           % NmrData
            Setup_NmrData();
        else
            %do nothing
        end
        set(hTextTest,'Enable','On');
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
        
       % NmrData;
        
       if isfield(NmrData,'xlim_spec')==1 % MJS edited to work
           scale=NmrData.xlim_spec;
           set(hEditScaleUp,'string',num2str(scale(2)));
           set(hEditScaleDown,'string',num2str(scale(1)));
       else
           scale=[0 0];
           set(hEditScaleUp,'string',num2str(scale(2)));
           set(hEditScaleDown,'string',num2str(scale(1)));
       end
        
    end
    function Import_Bruker_array(~, ~)
        NmrData.MessageText={''};
        Initiate_NmrData();
        guidata(hMainFigure,NmrData);
        
        [dirpath]=uigetdir('*','Choose the folder containing the numbered experiments');
        if dirpath==0
            return
        end

        dlg_title='Numbered experiments';
        dlg_prompt = {'Matlab array structure'};


        num_lines=1;
        answer=inputdlg(dlg_prompt,dlg_title,num_lines);
        answer=str2num(answer{1}); %#ok<ST2NM>

        if isempty(answer)
            return
        end

        nExp=numel(answer);
        Explist=answer;
        disp(['The experiments will be imported in this order: ',num2str(Explist)])


        if isunix==1
            OSslash='/';
        else
            OSslash='\';
        end

        % Changing the current directory
        cd(dirpath);
        % Taking the name of the files 
        ttl = dir('*.*');
        ttl = struct2cell(ttl);
        ttl = ttl(1,:);
        % Correcting the name of the files
        ttl = natsortfiles(ttl,'\d+\.?\d*','noext','rmdot');

        for expnr = 1:nExp
            %path=[dirpath OSslash num2str(Explist(expnr)) OSslash];
            path=[dirpath OSslash char(ttl(expnr))];
            % path=[dirpath OSslash num2str(Explist(expnr)) ];
            [brukerdata]=brukerimport(0,path);
            if expnr==1
                nIncr=brukerdata.arraydim;
            end

            if isfield(brukerdata,'acqus_error')
                if brukerdata.acqus_error==1
                    return
                end
            end

            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=brukerdata.FID(:,:);
            NmrData.lpOrgInd(expnr)=brukerdata.lp;
            NmrData.rpOrgInd(expnr)=brukerdata.rp;

        end
        NmrData.MessageText=brukerdata.logfile;
        set(hTextTest,'String',NmrData.MessageText)
        disp(['The experiments was imported in this order: ',num2str(Explist)])
        NmrData.lpInd=NmrData.lpOrgInd;
        NmrData.rpInd=NmrData.rpOrgInd;
        NmrData.explist=Explist; %remember the experiments that were imported. 
        NmrData.type='Bruker';
        NmrData.lrfid=brukerdata.digshift;
        NmrData.sfrq=brukerdata.sfrq;

         % % % Added by Rituraj % % %
        NmrData.isuf=0;       
        
        NmrData.filename=brukerdata.filename;
        NmrData.dosyconstant=6.1e10;
        NmrData.Gzlvl=brukerdata.Gzlvl;
        NmrData.ngrad=nIncr;
        NmrData.np=brukerdata.np;
        NmrData.ni=brukerdata.ni;
        NmrData.fn=NmrData.np;
        NmrData.sw=brukerdata.sw;
        NmrData.at=brukerdata.at;
        NmrData.sp=brukerdata.sp;
        NmrData.sp1=brukerdata.sp1;
        NmrData.lp=0;
        NmrData.rp=0;
        NmrData.gamma=2.6752e+08;
        NmrData.DELTA=0.1;
        NmrData.delta=0.03;
        NmrData.arraydim=nExp*nIncr;
        if isfield(brukerdata,'vdlist')
            NmrData.d2=brukerdata.vdlist';
            NmrData.d2=NmrData.d2(1:nJump:nJump*nExp);
            NmrData.d2_org=brukerdata.vdlist';
            NmrData.d2_org=NmrData.d2_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vclist')
            NmrData.vclist=brukerdata.vclist';
            NmrData.vclist=NmrData.vclist(1:nJump:nJump*nExp);
            NmrData.vclist_org=brukerdata.vclist';
            NmrData.vclist_org=NmrData.vclist_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vc_constant')
            NmrData.vc_constant=brukerdata.vc_constant';
            NmrData.vc_constant_org=brukerdata.vc_constant';
        end
        if (isfield(brukerdata,'ngrad2'))
                NmrData.ngrad2=brukerdata.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
        end
        if isfield(brukerdata,'acqus')
            NmrData.brukerdata.acqus=brukerdata.acqus;
        end
        if isfield(brukerdata,'acqu2s')
            NmrData.brukerdata.acqu2s=brukerdata.acqu2s;
        end
        if isfield(brukerdata,'acqu3s')
            NmrData.brukerdata.acqu3s=brukerdata.acqu3s;
        end
        if (isfield(brukerdata,'nuslist'))
            NmrData.nus=brukerdata.nuslist;
        end
        if (isfield(brukerdata,'gpnam'))
            NmrData.gpnam=brukerdata.gpnam;
        end
        if (isfield(brukerdata,'alpha'))
            NmrData.alpha=brukerdata.alpha;
        end

        guidata(hMainFigure,NmrData);
        Setup_NmrData();
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
        if isfield(NmrData,'xlim_spec')==1 % MJS edited to work
            scale=NmrData.xlim_spec;
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        else
            scale=[0 0];
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        end
        
    end
    function Import_Bruker_2Darray(~, ~)
        NmrData.MessageText={''};
        Initiate_NmrData();
        guidata(hMainFigure,NmrData);
        
        [dirpath]=uigetdir('*','Choose the folder containing the numbered experiments');
        if dirpath==0
            return
        end

        dlg_title='Numbered experiments';
        dlg_prompt = {'Matlab array structure'};
        
        num_lines=1;
        answer=inputdlg(dlg_prompt,dlg_title,num_lines);
        answer=str2num(answer{1}); %#ok<ST2NM>
        if isempty(answer)
            return
        end

        nExp=numel(answer);
        Explist=answer;
        disp(['The experiments will be imported in this order: ',num2str(Explist)])

        if isunix==1
            OSslash='/';
        else
            OSslash='\';
        end
        %path=[dirpath OSslash num2str(Explist(expnr)) OSslash];
        expnr=1;
            path=[dirpath OSslash num2str(Explist(expnr)) ];
            [brukerdata]=brukerimport(0,path);
            nIncr=brukerdata.arraydim;
            NmrData.FID=zeros(size(brukerdata.FID,1),nIncr*nExp);
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=brukerdata.FID(:,:);
            
        for expnr = 2:nExp
            %path=[dirpath OSslash num2str(Explist(expnr)) OSslash];
            path=[dirpath OSslash num2str(Explist(expnr)) ];
            [brukerdata_increments]=brukerimport(0,path);
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=brukerdata_increments.FID(:,:);
        end
        NmrData.MessageText=brukerdata.logfile;
        set(hTextTest,'String',NmrData.MessageText)
        disp(['The experiments was imported in this order: ',num2str(Explist)])
        
        NmrData.type='Bruker';
        NmrData.lrfid=brukerdata.digshift;
        NmrData.sfrq=brukerdata.sfrq;
        NmrData.filename=brukerdata.filename;
        NmrData.dosyconstant=6.1e10;
        NmrData.Gzlvl=brukerdata.Gzlvl;
        NmrData.ngrad=nIncr;
        NmrData.np=brukerdata.np;
        NmrData.ni=brukerdata.ni;
        NmrData.fn=NmrData.np;
        NmrData.sw=brukerdata.sw;
        NmrData.at=brukerdata.at;
        NmrData.sp=brukerdata.sp;
        NmrData.sp1=brukerdata.sp1;
        NmrData.lp=0;
        NmrData.rp=0;
        NmrData.gamma=2.6752e+08;
        NmrData.DELTA=0.1;
        NmrData.delta=0.03;
        NmrData.arraydim=nExp*nIncr;
        if isfield(brukerdata,'vdlist')
            NmrData.d2=brukerdata.vdlist';
            NmrData.d2=NmrData.d2(1:nJump:nJump*nExp);
            NmrData.d2_org=brukerdata.vdlist';
            NmrData.d2_org=NmrData.d2_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vclist')
            NmrData.vclist=brukerdata.vclist';
            NmrData.vclist=NmrData.vclist(1:nJump:nJump*nExp);
            NmrData.vclist_org=brukerdata.vclist';
            NmrData.vclist_org=NmrData.vclist_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vc_constant')
            NmrData.vc_constant=brukerdata.vc_constant';
            NmrData.vc_constant_org=brukerdata.vc_constant';
        end
        if (isfield(brukerdata,'ngrad2'))
                NmrData.ngrad2=brukerdata.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
        end
        if isfield(brukerdata,'acqus')
            NmrData.brukerdata.acqus=brukerdata.acqus;
        end
        if isfield(brukerdata,'acqu2s')
            NmrData.brukerdata.acqu2s=brukerdata.acqu2s;
        end
        if isfield(brukerdata,'acqu3s')
            NmrData.brukerdata.acqu3s=brukerdata.acqu3s;
        end
        if (isfield(brukerdata,'nuslist'))
            NmrData.nus=brukerdata.nuslist;
        end
        if (isfield(brukerdata,'gpnam'))
            NmrData.gpnam=brukerdata.gpnam;
        end
        if (isfield(brukerdata,'alpha'))
            NmrData.alpha=brukerdata.alpha;
        end
        guidata(hMainFigure,NmrData);
        Setup_NmrData();
        
        NmrData.narray3=1;
        NmrData.narray2=NmrData.arraydim/NmrData.ngrad;
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function Import_Bruker_Processed(~, ~)
        NmrData.MessageText={''};
        guidata(hMainFigure,NmrData);
        FilePath=uigetdir(pwd,'Choose the directory containing the processed data (e.g 1r, 2rr, etc)');
        if FilePath==0
            return
        end
        [brukerdata]=brukerimport(1,FilePath);
        guidata(hMainFigure,NmrData); 
        if ~isempty(brukerdata)
            Initiate_NmrData();
            %NmrData=guidata(hMainFigure);
            % setting up the NmrData structure - I think it is safest to
            % initialise them all (for the compiled version)
            %I'll keep all points and see if I can sort out the processing
            NmrData.type='Bruker';
            NmrData.lrfid=brukerdata.digshift;
            NmrData.sfrq=brukerdata.sfrq;
            NmrData.FID=brukerdata.FID;
            NmrData.filename=brukerdata.filename;
            NmrData.dosyconstant=brukerdata.dosyconstant;
            NmrData.Gzlvl=brukerdata.Gzlvl;
            NmrData.ngrad=brukerdata.ngrad;
            NmrData.acqus=brukerdata.acqus;
            NmrData.acqu2s=brukerdata.acqu2s;
            NmrData.np=brukerdata.np;
            NmrData.ni=brukerdata.ni;
            NmrData.fn=NmrData.np;
            NmrData.sw=brukerdata.sw;
            NmrData.at=brukerdata.at;
            NmrData.sp=brukerdata.sp;
            NmrData.sp1=brukerdata.sp1;
            NmrData.lp=brukerdata.lp;
            NmrData.rp=brukerdata.rp;
            NmrData.gamma=brukerdata.gamma;
            NmrData.DELTA=brukerdata.DELTA;
            NmrData.delta=brukerdata.delta;

            % % % Added by Rituraj % % %
            NmrData.isuf=0;


            if (isfield(brukerdata,'arraydim'))
                NmrData.arraydim=brukerdata.arraydim;
            else
                NmrData.arraydim=NmrData.ngrad;
            end
            if (isfield(brukerdata,'sw1'))
                NmrData.sw1=brukerdata.sw1;
            end
            if (isfield(brukerdata,'tau'))
                NmrData.tau=brukerdata.tau;
            end
            if (isfield(brukerdata,'droppts'))
                NmrData.droppts=brukerdata.droppts;
            end
            if (isfield(brukerdata,'ngrad2'))
                NmrData.ngrad2=brukerdata.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
            end
            if (isfield(brukerdata,'nuslist'))
                NmrData.nus=brukerdata.nuslist;
            end
            if (isfield(brukerdata,'gpnam'))
                NmrData.gpnam=brukerdata.gpnam;
            end
            if (isfield(brukerdata,'vdlist'))
                NmrData.d2=brukerdata.vdlist';
            end
            if isfield(brukerdata,'acqus')
                NmrData.brukerdata.acqus=brukerdata.acqus;
            end
            if isfield(brukerdata,'acqu2s')
                NmrData.brukerdata.acqu2s=brukerdata.acqu2s;
            end
            if isfield(brukerdata,'acqu3s')
                NmrData.brukerdata.acqu3s=brukerdata.acqu3s;
            end
            if (isfield(brukerdata,'alpha'))
                NmrData.alpha=brukerdata.alpha;
            end            

            clear brukerdata;
            guidata(hMainFigure,NmrData);
            Setup_NmrData();
        else
            
        end
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function Import_Bruker_array_Processed(~, ~)
        NmrData.MessageText={''};
        Initiate_NmrData();
        guidata(hMainFigure,NmrData);
        warndlg('All processed data must be in ../pdata/1 for each experiment for array import to work properly','Import array of processed data')
        uiwait(gcf)
        [dirpath]=uigetdir('*','Choose the folder containing the numbered experiments');
        if dirpath==0
            return
        end
        
        dlg_title='Numbered experiments';
        dlg_prompt = {'Matlab array structure'};
        
        num_lines=1;
        answer=inputdlg(dlg_prompt,dlg_title,num_lines);

        answer=str2num(answer{1}); %#ok<ST2NM>

        if isempty(answer)
            return
        end

        nExp=numel(answer);
        Explist=answer;
        disp(['The experiments will be imported in this order: ',num2str(Explist)])


        if isunix==1
            OSslash='/';
        else
            OSslash='\';
        end
    
        expnr=1;
            path=[dirpath OSslash num2str(Explist(expnr)) ];
            [brukerdata]=brukerimport(2,path);
            nIncr=brukerdata.arraydim;
            NmrData.FID=zeros(size(brukerdata.FID,1),nIncr*nExp);
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=brukerdata.FID(:,:);
        for expnr = 2:nExp
            path=[dirpath OSslash num2str(Explist(expnr)) ];
            [brukerdata_increments]=brukerimport(2,path);
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=brukerdata_increments.FID(:,:);
        end
        disp(['The experiments was imported in this order: ',num2str(Explist)])

        NmrData.MessageText=brukerdata.logfile;
        NmrData.explist=Explist; %remember the experiments that were imported.
        NmrData.type='Bruker';
        NmrData.lrfid=brukerdata.digshift;
        NmrData.sfrq=brukerdata.sfrq;
        NmrData.filename=brukerdata.filename;
        NmrData.dosyconstant=6.1e10;
        NmrData.Gzlvl=brukerdata.Gzlvl;
        NmrData.ngrad=nIncr;
        NmrData.np=brukerdata.np;
        NmrData.ni=brukerdata.ni;
        NmrData.fn=NmrData.np;
        NmrData.sw=brukerdata.sw;
        NmrData.at=brukerdata.at;
        NmrData.sp=brukerdata.sp;
        NmrData.sp1=brukerdata.sp1;
        NmrData.lp=0;
        NmrData.rp=0;
        NmrData.gamma=2.6752e+08;
        NmrData.DELTA=0.1;
        NmrData.delta=0.03;
        NmrData.arraydim=nExp*nIncr;
%         brukerdata
%         brukerdata_increments
% NmrData
        % % % Added by Rituraj % % %
        NmrData.isuf=0;

        if isfield(brukerdata,'vdlist')
            NmrData.d2=brukerdata.vdlist';
            NmrData.d2=NmrData.d2(1:nJump:nJump*nExp);
            NmrData.d2_org=brukerdata.vdlist';
            NmrData.d2_org=NmrData.d2_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vclist')
            NmrData.vclist=brukerdata.vclist';
            NmrData.vclist=NmrData.vclist(1:nJump:nJump*nExp);
            NmrData.vclist_org=brukerdata.vclist';
            NmrData.vclist_org=NmrData.vclist_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vc_constant')
            NmrData.vc_constant=brukerdata.vc_constant';
            NmrData.vc_constant_org=brukerdata.vc_constant';
        end
        if (isfield(brukerdata,'ngrad2'))
            NmrData.ngrad2=brukerdata.ngrad2;
        else
            NmrData.ngrad2=NmrData.ngrad;
        end
        if isfield(brukerdata,'acqus')
            NmrData.brukerdata.acqus=brukerdata.acqus;
        end
        if isfield(brukerdata,'acqu2s')
            NmrData.brukerdata.acqu2s=brukerdata.acqu2s;
        end
        if isfield(brukerdata,'acqu3s')
            NmrData.brukerdata.acqu3s=brukerdata.acqu3s;
        end
        if (isfield(brukerdata,'nuslist'))
            NmrData.nus=brukerdata.nuslist;
        end
        if (isfield(brukerdata,'gpnam'))
            NmrData.gpnam=brukerdata.gpnam;
        end
        if (isfield(brukerdata,'alpha'))
            NmrData.alpha=brukerdata.alpha;
        end
        guidata(hMainFigure,NmrData);
        
        Setup_NmrData();

        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function Import_Bruker_2Darray_Processed(~, ~)
        NmrData.MessageText={''};
        Initiate_NmrData();
        guidata(hMainFigure,NmrData);
        warndlg('All processed data must be in ../pdata/1 for each experiment for array import to work properly','Import array of processed data')
        uiwait(gcf)
        [dirpath]=uigetdir('*','Choose the folder containing the numbered experiments');
        if dirpath==0
            return
        end
        % dlg_title='Data structure';
        % dlg_prompt = {'First experiment','Numbers between experiment:','Last experiment'};
        
        dlg_title='Numbered experiments';
        dlg_prompt = {'Matlab array structure'};
        
        num_lines=1;
        answer=inputdlg(dlg_prompt,dlg_title,num_lines);
        answer=str2num(answer{1}); 
        if isempty(answer)
            return
        end

        nExp=numel(answer);
        Explist=answer;
        disp(['The experiments will be imported in this order: ',num2str(Explist)])


        if isunix==1
            OSslash='/';
        else
            OSslash='\';
        end
        %path=[dirpath OSslash num2str(Explist(expnr)) OSslash];
        expnr=1;
            path=[dirpath OSslash num2str(Explist(expnr)) ];
            [brukerdata]=brukerimport(2,path);
            nIncr=brukerdata.arraydim;
            NmrData.FID=zeros(size(brukerdata.FID,1),nIncr*nExp);
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=brukerdata.FID(:,:);
            
        for expnr = 2:nExp
            path=[dirpath OSslash num2str(Explist(expnr)) ];
            [brukerdata_increments]=brukerimport(2,path);
            NmrData.FID(:,((expnr-1)*nIncr+1):expnr*nIncr)=brukerdata_increments.FID(:,:);
        end
        NmrData.MessageText=brukerdata.logfile;
        set(hTextTest,'String',NmrData.MessageText)
        disp(['The experiments was imported in this order: ',num2str(Explist)])

        NmrData.type='Bruker';
        NmrData.lrfid=brukerdata.digshift;
        NmrData.sfrq=brukerdata.sfrq;
        NmrData.filename=brukerdata.filename;
        NmrData.dosyconstant=6.1e10;
        NmrData.Gzlvl=brukerdata.Gzlvl;
        NmrData.ngrad=nIncr;
        NmrData.np=brukerdata.np;
        NmrData.ni=brukerdata.ni;
        NmrData.fn=NmrData.np;
        NmrData.sw=brukerdata.sw;
        NmrData.at=brukerdata.at;
        NmrData.sp=brukerdata.sp;
        NmrData.sp1=brukerdata.sp1;
        NmrData.lp=0;
        NmrData.rp=0;
        NmrData.gamma=2.6752e+08;
        NmrData.DELTA=0.1;
        NmrData.delta=0.03;
        NmrData.arraydim=nExp*nIncr;
        if isfield(brukerdata,'vdlist')
            NmrData.d2=brukerdata.vdlist';
            NmrData.d2=NmrData.d2(1:nJump:nJump*nExp);
            NmrData.d2_org=brukerdata.vdlist';
            NmrData.d2_org=NmrData.d2_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vclist')
            NmrData.vclist=brukerdata.vclist';
            NmrData.vclist=NmrData.vclist(1:nJump:nJump*nExp);
            NmrData.vclist_org=brukerdata.vclist';
            NmrData.vclist_org=NmrData.vclist_org(1:nJump:nJump*nExp);
        end
        if isfield(brukerdata,'vc_constant')
            NmrData.vc_constant=brukerdata.vc_constant';
            NmrData.vc_constant_org=brukerdata.vc_constant';
        end
        if (isfield(brukerdata,'ngrad2'))
                NmrData.ngrad2=brukerdata.ngrad2;
            else
                NmrData.ngrad2=NmrData.ngrad;
        end
        if isfield(brukerdata,'acqus')
            NmrData.brukerdata.acqus=brukerdata.acqus;
        end
        if isfield(brukerdata,'acqu2s')
            NmrData.brukerdata.acqu2s=brukerdata.acqu2s;
        end
        if isfield(brukerdata,'acqu3s')
            NmrData.brukerdata.acqu3s=brukerdata.acqu3s;
        end
        if (isfield(brukerdata,'nuslist'))
            NmrData.nus=brukerdata.nuslist;
        end
        if (isfield(brukerdata,'gpnam'))
            NmrData.gpnam=brukerdata.gpnam;
        end
        if (isfield(brukerdata,'alpha'))
            NmrData.alpha=brukerdata.alpha;
        end
       
        guidata(hMainFigure,NmrData);
        Setup_NmrData();
        
        NmrData.narray3=1;
        NmrData.narray2=NmrData.arraydim/NmrData.ngrad;
                
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function Import_X_pulse(~,~)
        FilePath=uigetdir(pwd,'Choose the directory containing the NMR experiment (fid file)');
        
        if FilePath==0
            return
        end
        Initiate_NmrData();
        xpulsedata=X_pulse_import(FilePath);
        
        NmrData.type='Bruker';
          %  NmrData.lrfid=brukerdata.digshift;
            NmrData.sfrq=xpulsedata.sfrq;
            NmrData.FID=xpulsedata.FID;
            NmrData.filename=FilePath;

%             NmrData.Gzlvl=brukerdata.Gzlvl;
             NmrData.ngrad=1;
%             NmrData.acqus=brukerdata.acqus;
%             NmrData.acqu2s=brukerdata.acqu2s;
            NmrData.np=xpulsedata.np;
            NmrData.ni=1;
            NmrData.fn=NmrData.np;
            NmrData.sw=xpulsedata.sw;
            NmrData.at=xpulsedata.at;
            NmrData.sp=xpulsedata.sp;
            NmrData.arraydim=1;
            NmrData.ngrad=1;
            NmrData.lp=xpulsedata.lp;
            NmrData.rp=xpulsedata.rp;
            NmrData.gamma=xpulsedata.gamma;
            NmrData.delta='non existing';
            NmrData.DELTA='non existing';
            NmrData.fshift=0;
            NmrData.dosyconstant=0;
            NmrData.NUC1=xpulsedata.NUC1;
            NmrData.lrfid=0;
            NmrData.NCOEF=xpulsedata.NCOEF;
            NmrData.TDoff=xpulsedata.TDoff;
            
        clear xpulsedata;
            guidata(hMainFigure,NmrData);

            Setup_NmrData();
            set(hEditFn,'string',num2str(NmrData.fn));
        set(hEditNp,'string',num2str(NmrData.np));
        set(hEditPh1,'string',num2str(NmrData.lp,4))
        set(hEditPh0,'string',num2str(NmrData.rp,4))
        set(hSliderPh0,'value',NmrData.rp);
        set(hSliderPh1,'value',NmrData.lp);
        set(hEditFlip,'string',num2str(NmrData.gradnr));
        set(hEditFlip2,'string',num2str(NmrData.array2nr));
        set(hEditFlipSpec,'string',num2str(NmrData.flipnr));
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hTextFlip,'string',['/' num2str(NmrData.ngrad)]);
        set(hTextFlip2,'string',['/' num2str(NmrData.narray2)]);
        set(hTextFlipSpec,'string',['/' num2str(NmrData.arraydim)]);
        hPlot=plot(hAxes,NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)));
        set(hPlot,'HitTest','off')
        set(hAxes,'Xdir','Reverse')

        guidata(hMainFigure,NmrData);
        
    end
    function Import_X_pulse_array(~,~)

        Initiate_NmrData();
        xpulsedata=X_pulse_array;
        
        NmrData.type='Bruker';
          %  NmrData.lrfid=brukerdata.digshift;
            NmrData.sfrq=xpulsedata.sfrq;
            NmrData.FID=xpulsedata.FID;
            NmrData.filename=xpulsedata.filepath;

%             NmrData.Gzlvl=brukerdata.Gzlvl;
             NmrData.ngrad=xpulsedata.ni;
%             NmrData.acqus=brukerdata.acqus;
%             NmrData.acqu2s=brukerdata.acqu2s;
            NmrData.np=xpulsedata.np;
            NmrData.ni=1;
            NmrData.fn=NmrData.np;
            NmrData.sw=xpulsedata.sw;
            NmrData.at=xpulsedata.at;
            NmrData.sp=xpulsedata.sp;
            NmrData.arraydim=xpulsedata.ni;
            NmrData.ngrad=xpulsedata.ni;
            NmrData.lp=xpulsedata.lp;
            NmrData.rp=xpulsedata.rp;
            NmrData.gamma=xpulsedata.gamma;
            NmrData.delta='non existing';
            NmrData.DELTA='non existing';
            NmrData.fshift=0;
            NmrData.dosyconstant=0;
            NmrData.NUC1=xpulsedata.NUC1;
            NmrData.lrfid=0;
            if isfield(xpulsedata,'vd')
                NmrData.d2=xpulsedata.vd;
            end 
            
            if isfield(xpulsedata,'vc')
                disp('Assuming PROJECT data')
            NmrData.vclist=xpulsedata.vc;
                if isfield(xpulsedata,'vc_constant')
                NmrData.vc_constant=xpulsedata.vc_constant/1e6;
                else
                NmrData.vc_constant=0.001;
                end 
                NmrData.d2=(NmrData.vclist*4*NmrData.vc_constant)+5*xpulsedata.p90;
            end 
            
            %lets add some values for relaxation just in case
       
            
        clear xpulsedata;
            guidata(hMainFigure,NmrData);

            Setup_NmrData();
            set(hEditFn,'string',num2str(NmrData.fn));
        set(hEditNp,'string',num2str(NmrData.np));
        
        set(hEditPh1,'string',num2str(NmrData.lp,4))
        set(hEditPh0,'string',num2str(NmrData.rp,4))
        set(hSliderPh0,'value',NmrData.rp);
        set(hSliderPh1,'value',NmrData.lp);
        set(hEditFlip,'string',num2str(NmrData.gradnr));
        set(hEditFlip2,'string',num2str(NmrData.array2nr));
        set(hEditFlipSpec,'string',num2str(NmrData.flipnr));
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hTextFlip,'string',['/' num2str(NmrData.ngrad)]);
        set(hTextFlip2,'string',['/' num2str(NmrData.narray2)]);
        set(hTextFlipSpec,'string',['/' num2str(NmrData.arraydim)]);
        hPlot=plot(hAxes,NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)));
        set(hPlot,'HitTest','off')
        set(hAxes,'Xdir','Reverse')

        guidata(hMainFigure,NmrData);
        
        
    end
    function Import_Magritek(~,~)
        
        FilePath=uigetdir(pwd,'Choose the directory containing the NMR experiment (fid file)');
        
        if FilePath==0
            return
        end
        Initiate_NmrData();
        magritekdata=magritek_import(FilePath);
        
        NmrData.type='Bruker';
          %  NmrData.lrfid=brukerdata.digshift;
            NmrData.sfrq=magritekdata.sfrq;
            NmrData.FID=magritekdata.fid;
            NmrData.filename=FilePath;

%             NmrData.Gzlvl=brukerdata.Gzlvl;
             NmrData.ngrad=1;
%             NmrData.acqus=brukerdata.acqus;
%             NmrData.acqu2s=brukerdata.acqu2s;
            NmrData.np=magritekdata.np;
            NmrData.ni=1;
            NmrData.fn=magritekdata.np;
            NmrData.sw=magritekdata.sw;
            NmrData.at=magritekdata.at;
            NmrData.sp=magritekdata.sp;
            NmrData.arraydim=1;
            NmrData.ngrad=1;
            NmrData.lp=magritekdata.lp;
            NmrData.rp=magritekdata.rp;
            NmrData.gamma=magritekdata.gamma;
            NmrData.delta='non existing';
            NmrData.DELTA='non existing';
            NmrData.fshift=0;
            NmrData.dosyconstant=0;
            NmrData.NUC1=magritekdata.NUC1;
            NmrData.lrfid=0;
            
            disp(NmrData)
        clear magritekdata;
            guidata(hMainFigure,NmrData);

            Setup_NmrData();
            set(hEditFn,'string',num2str(NmrData.fn));
        set(hEditNp,'string',num2str(NmrData.np));
        set(hEditPh1,'string',num2str(NmrData.lp,4))
        set(hEditPh0,'string',num2str(NmrData.rp,4))
        set(hSliderPh0,'value',NmrData.rp);
        set(hSliderPh1,'value',NmrData.lp);
        set(hEditFlip,'string',num2str(NmrData.gradnr));
        set(hEditFlip2,'string',num2str(NmrData.array2nr));
        set(hEditFlipSpec,'string',num2str(NmrData.flipnr));
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hTextFlip,'string',['/' num2str(NmrData.ngrad)]);
        set(hTextFlip2,'string',['/' num2str(NmrData.narray2)]);
        set(hTextFlipSpec,'string',['/' num2str(NmrData.arraydim)]);
        hPlot=plot(hAxes,NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)));
        set(hPlot,'HitTest','off')
        set(hAxes,'Xdir','Reverse')

        guidata(hMainFigure,NmrData);
        
    end
    function Import_Magritek_2D(~,~)
        
        FilePath=uigetdir(pwd,'Choose the directory containing the NMR experiment (fid file)');
        
        if FilePath==0
            return
        end
        Initiate_NmrData();
        magritekdata=magritek_import_array(FilePath);
        
        NmrData.type='Bruker';
          %  NmrData.lrfid=brukerdata.digshift;
            NmrData.sfrq=magritekdata.sfrq;
            NmrData.FID=magritekdata.fid;
            NmrData.filename=FilePath;

%             NmrData.Gzlvl=brukerdata.Gzlvl;
             NmrData.ngrad=magritekdata.ni;
%             NmrData.acqus=brukerdata.acqus;
%             NmrData.acqu2s=brukerdata.acqu2s;
            NmrData.np=magritekdata.np;
            NmrData.ni=1;
            NmrData.fn=magritekdata.np;
            NmrData.sw=magritekdata.sw;
            NmrData.at=magritekdata.at;
            NmrData.sp=magritekdata.sp;
            NmrData.arraydim=magritekdata.ni;
            NmrData.ngrad=magritekdata.ni;
            NmrData.lp=magritekdata.lp;
            NmrData.rp=magritekdata.rp;
            NmrData.gamma=magritekdata.gamma;
            NmrData.delta='non existing';
            NmrData.DELTA='non existing';
            NmrData.fshift=0;
            NmrData.dosyconstant=0;
            NmrData.NUC1=magritekdata.NUC1;
            NmrData.lrfid=0;
            
            if isfield(magritekdata,'vd')
                NmrData.d2=magritekdata.vd;
            end 

            disp(NmrData)
        clear magritekdata;
            guidata(hMainFigure,NmrData);

            Setup_NmrData();
            set(hEditFn,'string',num2str(NmrData.fn));
        set(hEditNp,'string',num2str(NmrData.np));
        set(hEditPh1,'string',num2str(NmrData.lp,4))
        set(hEditPh0,'string',num2str(NmrData.rp,4))
        set(hSliderPh0,'value',NmrData.rp);
        set(hSliderPh1,'value',NmrData.lp);
        set(hEditFlip,'string',num2str(NmrData.gradnr));
        set(hEditFlip2,'string',num2str(NmrData.array2nr));
        set(hEditFlipSpec,'string',num2str(NmrData.flipnr));
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hTextFlip,'string',['/' num2str(NmrData.ngrad)]);
        set(hTextFlip2,'string',['/' num2str(NmrData.narray2)]);
        set(hTextFlipSpec,'string',['/' num2str(NmrData.arraydim)]);
        hPlot=plot(hAxes,NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)));
        set(hPlot,'HitTest','off')
        set(hAxes,'Xdir','Reverse')

        guidata(hMainFigure,NmrData);
        
    end
    function Import_mestrenova(~,~)
        %FilePath=uigetdir(pwd,'Choose the directory containing the NMR experiment (fid file)');
        [filename, pathname] = uigetfile('*.jdx','Open JCAMP file');
        FilePath=[pathname filename];
        if filname && filepath == 0
            return
        end
        Initiate_NmrData();
        mestrenovadata=mestrenova_import(FilePath);

        NmrData.FID=mestrenovadata.FID;

        dims=ndims(NmrData.FID);
        tmp=size( NmrData.FID);


        switch dims

            case 1
                NmrData.arraydim=1;
                NmrData.narray2=1;
                NmrData.ngrad=1;

            case 2
                NmrData.arraydim=tmp(2);
                NmrData.ngrad= tmp(2);
                NmrData.ngrad2= tmp(2);
                NmrData.narray2=1;

            case 3
                NmrData.arraydim=tmp(2).*tmp(3);
                NmrData.ngrad= tmp(2);
                NmrData.ngrad2= tmp(2)*tmp(3);
                NmrData.narray2=tmp(3);
                NmrData.FID=reshape(NmrData.FID,tmp(1),tmp(2).*tmp(3));


            case 4
                NmrData.arraydim=tmp(2).*tmp(3).*tmp(4);
                NmrData.ngrad= tmp(2);
                NmrData.ngrad2= tmp(2)*tmp(3);
                NmrData.narray2=tmp(3);
                NmrData.narray3=tmp(4);
                NmrData.FID=reshape(NmrData.FID,tmp(1),tmp(2).*tmp(3).*tmp(4));

            otherwise
                logtext='GNAT only supports up to 4 dimensions';
                error(logtext)

        end


        NmrData.np=mestrenovadata.np;
        NmrData.sfrq=mestrenovadata.sfrq;
        NmrData.sw=mestrenovadata.sw;
        NmrData.sp=mestrenovadata.sp;

        switch mestrenovadata.nucleus
            case '<H'
                NmrData.gamma=267524618.573;
            case '1H'
                NmrData.gamma=267524618.573;
            case '2H'
                NmrData.gamma=41066000;
            case '10B'
                NmrData.gamma=28747000;
            case '11B'
                NmrData.gamma=85847000;
            case '13C'
                NmrData.gamma=67283000;
            case '14N'
                NmrData.gamma=19338000;
            case '15N'
                NmrData.gamma=-27126000;
            case '17O'
                NmrData.gamma=-36281000;
            case '19F'
                NmrData.gamma=251815000;
            case '23Na'
                NmrData.gamma=70808000;
            case '27Al'
                NmrData.gamma=69764000;
            case '29Si'
                NmrData.gamma=-53190000;
            case '31P'
                NmrData.gamma=108394000;

            otherwise
                logtext='unknown nucleus - defaulting to proton';
                disp(logtext)
                NmrData.gamma=267524618.573;
        end


        NmrData.gamma=1;


        NmrData.type='Mestrenova JCAMP';
        NmrData.at=NmrData.np/(NmrData.sw*NmrData.sfrq);
        NmrData.fn=NmrData.np;
        NmrData.rp=0;
        NmrData.lp=0;
        NmrData.delta='non existing';
        NmrData.DELTA='non existing';
        NmrData.dosyconstant=0;
        %NmrData.arraydim=1;
        %NmrData.ngrad=1;
        NmrData.filename=FilePath;
        NmrData.fshift=0;

        guidata(hMainFigure,NmrData);
        Setup_NmrData();
        
        guidata(hMainFigure,NmrData);

    end
    function Import_ToolboxASCII(~, ~)
        [filename, pathname] = uigetfile('*.*','Import Toolbox ASCII format');
       if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'rt');
        hp=msgbox('Reading data - this may take a while','Data Import');
        [ImportData]=ImportToolboxFormat(statfil);
        close(hp)
        Initiate_NmrData();
        NmrData=guidata(hMainFigure);
        % Import mandatory fields first
        NmrData.filename=filepath;
        if isfield(ImportData,'GNATFormatVersion')
            GNATFormatVersion=ImportData.GNATFormatVersion.Value; %#ok<NASGU>
        else
            GNATFormatVersion=0.1; %#ok<NASGU>
            warning('File import. Mandatory "GNAT  Format Version" is missing ')
        end
        if isfield(ImportData,'DataClass')
            DataClass=ImportData.DataClass.Value;
        else
            error('File import. Mandatory "Data Class" is missing ')
        end
        if isfield(ImportData,'ComplexData')
            ComplexData=ImportData.ComplexData.Value;
        else
            error('File import. Mandatory "Complex Data" is missing ')
        end
        if isfield(ImportData,'PointsPerRow')
            NmrData.np=ImportData.PointsPerRow.Value;
        else
            error('File import. Mandatory "Points Per Row" is missing ')
        end
        if isfield(ImportData,'ObserveFrequency')
            NmrData.sfrq=ImportData.ObserveFrequency.Value;
        else
            error('File import. Mandatory "Observe Frequency" is missing ')
        end
        if isfield(ImportData,'SpectralWidth')
            NmrData.sw=ImportData.SpectralWidth.Value;
        else
            error('File import. Mandatory "Spectral Width" is missing ')
        end
        if isfield(ImportData,'AcquisitionTime')
            NmrData.at=ImportData.AcquisitionTime.Value;
        else
            error('File import. Mandatory "Acquisition Time" is missing ')
        end
        if isfield(ImportData,'LeftRotation')
            NmrData.lrfid=ImportData.LeftRotation.Value;
        end
        if isfield(ImportData,'LowestFrequency')
            NmrData.sp=ImportData.LowestFrequency.Value;
        else
            error('File import. Mandatory "Lowest Frequency" is missing ')
        end
        
        if isfield(ImportData,'NumberOfArrays')
            NumberOfArrays=ImportData.NumberOfArrays.Value;
        else
            error('File import. Mandatory "Number Of Arrays" is missing ')
        end
        if isfield(ImportData,'ObserveNucleus')
            ObserveNucleus=ImportData.ObserveNucleus.Value; %#ok<NASGU>
        else
            error('File import. Mandatory "Observe Nucleus" is missing ')
        end
        %Import optional fields
        if isfield(ImportData,'RightPhase')
            NmrData.rp=ImportData.RightPhase.Value;
        else
            NmrData.rp=0;
        end
        if isfield(ImportData,'LeftPhase')
            NmrData.lp=ImportData.LeftPhase.Value;
        else
            NmrData.lp=0;
        end
        if isfield(ImportData,'SpectrometerDataSystem')
            NmrData.type=ImportData.SpectrometerDataSystem.Value;
        else
            NmrData.type='Unknown';
        end
        if isfield(ImportData,'DataType')
            DataType=ImportData.DataType.Value;
        else
            DataType='';
        end
        if isfield(ImportData,'BinaryFileName')
            BinaryFileName=ImportData.BinaryFileName.Value; %#ok<NASGU>
        else
            BinaryFileName=''; %#ok<NASGU>
        end
        if isfield(ImportData,'PulseSequenceName')
            PulseSequenceName=ImportData.PulseSequenceName.Value; %#ok<NASGU>
        else
            PulseSequenceName='';%#ok<NASGU>
        end
        if isfield(ImportData,'FourierNumber')
            NmrData.fn=ImportData.FourierNumber.Value;
        else
            NmrData.fn=NmrData.np;
        end
        %If DOSY data
        if strcmp(DataType,'DOSY data') || strcmp(DataType,'DOSY') || strcmp(DataType,'SCORE residuals')
            guidata(hMainFigure,NmrData); WriteLogDispInfo(['Labelled as: ' DataType])
            %check for mandatory DOSY parameters
            if isfield(ImportData,'GradientShape')
                GradientShape=ImportData.GradientShape.Value;
            else
                GradientShape='Rectangular';
                %error('File import. Mandatory DOSY data parameter "Gradient Shape" is missing ')
            end
            if strcmpi(GradientShape,'Square') || strcmpi(GradientShape,'Rectangular')
                %all is fine
            else
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only rectangular gradient shapes supported at the moment, treating them as such')
                %error('File import.Compensation for non rectangular "Gradient Shape" is not yet implemented ')
            end
            
            if isfield(ImportData,'DiffusionDelay')
                NmrData.DELTA=ImportData.DiffusionDelay.Value;
            else
                error('File import. Mandatory DOSY data parameter "Diffusion Delay" is missing ')
            end
            if isfield(ImportData,'DiffusionEncodingTime')
                NmrData.delta=ImportData.DiffusionEncodingTime.Value;
            else
                NmrData.delta=1;
                %error('File import. Mandatory DOSY data parameter "Diffusion Encoding Time" is missing ')
            end
            if isfield(ImportData,'Dosygamma')
                Dosygamma=ImportData.Dosygamma.Value;
                NmrData.gamma=Dosygamma;
            else
                Dosygamma=1;
                NmrData.gamma=Dosygamma;
                % error('File import. Mandatory DOSY data parameter "Dosygamma" is missing ')
            end
            if isfield(ImportData,'PulseSequenceType')
                PulseSequenceType=ImportData.PulseSequenceType.Value;
            else
                error('File import. Mandatory DOSY data parameter "Pulse Sequence Type" is missing ')
            end
            if strcmpi(PulseSequenceType,'Other')
                if isfield(ImportData,'Dosytimecubed') && ~isempty(ImportData.Dosytimecubed)
                    NmrData.dosyconstant=ImportData.Dosytimecubed.Value.*Dosygamma.^2;
                    NmrData.DELTAprime=NmrData.dosyconstant/(Dosygamma.^2.*NmrData.delta.^2);
                else
                    error('File import. Mandatory (when pulse sequence is Other) DOSY data parameter "Dosytimecubed" is missing ')
                end
            elseif strcmpi(PulseSequenceType,'Bipolar')
                if isfield(ImportData,'Dosytimecubed') && ~isempty(ImportData.Dosytimecubed)
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('File import. Parameter "Dosytimecubed" present - over rules calculation of corrected diffusion time for Bipolar sequence ')
                    NmrData.dosyconstant=ImportData.Dosytimecubed.Value.*Dosygamma.^2.*NmrData.DELTAprime;
                elseif isfield(ImportData,'Tau') && ~isempty(ImportData.Tau)
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('File import. calculation of corrected diffusion time using Tau')
                    NmrData.DELTAprime=NmrData.DELTA-NmrData.delta/3-ImportData.Tau/2;
                    NmrData.dosyconstant=NmrData.gamma.^2.*NmrData.delta.^2.*...
                        NmrData.DELTAprime;
                else
                    error('File import. Parameter "Tau" (mandatory for Bipolar pulse sequences) missing')
                end
            elseif strcmpi(PulseSequenceType,'Unipolar')
                if isfield(ImportData,'Dosytimecubed') && ~isempty(ImportData.Dosytimecubed)
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('File import. Parameter "Dosytimecubed" present - over rules calculation of corrected diffusion time for Unipolar sequence ')
                    NmrData.dosyconstant=ImportData.Dosytimecubed.Value.*Dosygamma.^2;
                else
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('File import. calculation of corrected diffusion time')
                    NmrData.DELTAprime=NmrData.DELTA-NmrData.delta/3;
                    NmrData.dosyconstant=NmrData.gamma.^2.*NmrData.delta.^2.*...
                        NmrData.DELTAprime;
                end
            else
                error('File import. mandatory DOSY data parameter "Pulse Sequence Type" must be Other, Bipolar or Unipolar')
            end
            if isfield(ImportData,'GradientAmplitude')
                NmrData.ngrad=length(ImportData.GradientAmplitude.Value);
                for p=1:NmrData.ngrad
                    NmrData.Gzlvl(p)=str2double(ImportData.GradientAmplitude.Value{p});
                end
                %ImportData
                %ImportData.NumberOfRows.Value
                NmrData.arraydim=ImportData.NumberOfRows.Value;
                NmrData.ngrad2= NmrData.ngrad;
                %NmrData.arraydim=NmrData.ngrad;
            else
                error('File import. Mandatory DOSY data parameter "Gradient Amplitude" is missing ')
            end
            %elseif strcmp(DataType,'SCORE components')
        elseif strcmp(DataType,'Relaxation data')
            NmrData.Gzlvl=0;
            NmrData.dosyconstant=0;
            NmrData.gamma=267524618.573;
            NmrData.DELTA='non existing';
            NmrData.delta='non existing';
            NmrData.ngrad=1;
            if isfield(ImportData,'Delays')
                NmrData.arraydim=ImportData.NumberOfRows.Value;
                for p=1:NmrData.arraydim
                    NmrData.d2(p)=str2double(ImportData.Delays.Value{p});
                end
                NmrData.d2= NmrData.d2';
                NmrData.bigtau= NmrData.d2;
                NmrData.ngrad=NmrData.arraydim;
                NmrData.ngrad2= NmrData.ngrad;
            else
                error('File import. Mandatory Relaxation data parameter "Delays" is missing ')
            end
            
            
        elseif  ~isempty(DataType)
           guidata(hMainFigure,NmrData); WriteLogDispInfo(DataType)
            NmrData.Gzlvl=0;
            NmrData.dosyconstant=0;
            NmrData.gamma=267524618.573;
            NmrData.DELTA='non existing';
            NmrData.delta='non existing';
            NmrData.ngrad=1;
            if NumberOfArrays==0
                guidata(hMainFigure,NmrData); WriteLogDispInfo('No arrays ; Trying import as a 1D spectrum')
                NmrData.arraydim=1;
            elseif NumberOfArrays==1
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Import as an arrayed data set with one array')
                %find the array
                fnames=fieldnames(ImportData);
                for fds=1:length(fnames)
                    if iscell(ImportData.(fnames{fds}).Value)
                        NmrData.arraydim=numel(ImportData.(fnames{fds}).Value);
                        numel(ImportData.(fnames{fds}).Value)
                        break;
                    end
                end
                if isempty(NmrData.arraydim)
                    NmrData.arraydim=ImportData.NumberOfRows.Value;
                    NmrData.ngrad=NmrData.arraydim;
                    NmrData.ngrad2= NmrData.ngrad;
                end
            elseif NumberOfArrays==2
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Import as an arrayed data set with two nested arrays')
                error('File import. This import option is not implemented yet')
            end
        else
            error('File import. Unkown data type - aborting')
        end
        %import phase array if present
        if isfield(ImportData,'LeftPhaseArray')
            guidata(hMainFigure,NmrData); WriteLogDispInfo('LPA')
            
            
            for p=1:NmrData.arraydim
                NmrData.lpInd(p)=str2double(ImportData.LeftPhaseArray.Value{p});
            end
        end
        if isfield(ImportData,'RightPhaseArray')
            
            for p=1:NmrData.arraydim
                NmrData.rpInd(p)=str2double(ImportData.RightPhaseArray.Value{p});
            end
            
        end
        
        %If synthetic
        if isfield(ImportData,'NumberofSyntheticPeaks')
            NmrData.issynthetic=1;
            set(hEditnpeaks,'string',ImportData.NumberofSyntheticPeaks.Value)
            if isfield(ImportData,'LowestGradientStrength')
                set(hEditmingrad,'string',ImportData.LowestGradientStrength.Value)
            end
            if isfield(ImportData,'HighestGradientStrength')
                set(hEditmaxgrad,'string',ImportData.HighestGradientStrength.Value)
            end
            if isfield(ImportData,'NumberofDOSYIncrements')
                set(hEditni,'string',ImportData.NumberofDOSYIncrements.Value)
            end
            if isfield(ImportData,'SignaltoNoiseRatio')
                set(hEditnoise,'string',ImportData.SignaltoNoiseRatio.Value)
            end
            if isfield(ImportData,'PeakFrequencies')
                SynthData(:,1)=str2double(ImportData.PeakFrequencies.Value);
                SynthData(:,2)=str2double(ImportData.DiffusionCoefficients.Value);
                SynthData(:,3)=str2double(ImportData.PeakAmplitudes.Value);
                SynthData(:,4)=str2double(ImportData.LineWidthsLorentzian.Value);
                SynthData(:,5)=str2double(ImportData.LineWidthsGaussian.Value);
                set(hTableSynthPeaks,'Data',SynthData)
            end
        end
        %Import Data Points
     
        if isfield(ImportData,'DataPoints')
            
            if strcmpi(DataClass,'FID')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('FID data')
                if strcmpi(ImportData.BinaryFileName.ParmForm,'string')
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Binary Data')
                    filepath=filepath(1:(end-4));
                    filepath=[filepath '.bin'];
                    binfile=fopen(filepath, 'r','b');
                    FID=fread(binfile,'int64','b');
                    R=FID(1:length(FID)/2);
                    I=FID(length(FID)/2+1:end);
                    FID=complex(R,I);
                    NmrData.FID=reshape(FID,NmrData.np,NmrData.arraydim);
                else
                    NmrData.FID=reshape(ImportData.DataPoints.Value,NmrData.np,NmrData.arraydim);
                end
            elseif strcmpi(DataClass,'Spectra') || strcmpi(DataClass,'Spectrum')
                if strcmpi(ComplexData,'Yes')
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Spectra data (complex)')
                    if strcmpi(ImportData.BinaryFileName.ParmForm,'string')
                        guidata(hMainFigure,NmrData); WriteLogDispInfo('Binary Data')
                        filepath=filepath(1:(end-4));
                        filepath=[filepath '.bin'];
                        binfile=fopen(filepath, 'r','b');
                        FID=fread(binfile,'int64','b');
                        R=FID(1:length(FID)/2);
                        I=FID(length(FID)/2+1:end);
                        FID=complex(R,I);
                        NmrData.SPECTRA=reshape(FID,NmrData.np,NmrData.arraydim);
                    else
                        
                        NmrData.SPECTRA=reshape(ImportData.DataPoints.Value,NmrData.np,NmrData.arraydim);
                        
                    end
 
                    NmrData.SPECTRA=fftshift(NmrData.SPECTRA,1);
                    NmrData.FID=ifft(NmrData.SPECTRA);
%                 
%                    
                    %NmrData.FID=fftshift(NmrData.FID);
                   % NmrData.FID(1,:)=NmrData.FID(1,:).*2;
                    NmrData.at=NmrData.np/(NmrData.sw*NmrData.sfrq);
                elseif strcmpi(ComplexData,'No')
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Spectra data (real)')
                    if strcmpi(ImportData.BinaryFileName.ParmForm,'string')
                        guidata(hMainFigure,NmrData); WriteLogDispInfo('Binary Data')
                        filepath=filepath(1:(end-4));
                        filepath=[filepath '.bin'];
                        binfile=fopen(filepath, 'r','b');
                        FID=fread(binfile,'int64','b');
                        NmrData.SPECTRA=reshape(FID,NmrData.fn,NmrData.arraydim);
                    else
                        NmrData.SPECTRA=reshape(ImportData.DataPoints.Value,NmrData.fn,NmrData.arraydim);
                        
                    end
                    NmrData.SPECTRA=flipud(fftshift(NmrData.SPECTRA,1));
                    NmrData.FID=(ifft(NmrData.SPECTRA));
                    NmrData.FID(1,:)=NmrData.FID(1,:)./2;
                    NmrData.FID=NmrData.FID(1:round(NmrData.fn/2),:);
                    NmrData.np=round(NmrData.fn/2);
                    NmrData.fn=NmrData.np*2;
                    NmrData.at=NmrData.np/(NmrData.sw*NmrData.sfrq);
                else
                    error('File import. Cannot determine if data is complex')
                end
            else
                error('File import. Unknown Data Class')
            end
        else
            error('File import. Mandatory DOSY data parameter "Data Points" is missing ')
        end
        %size(NmrData.FID)
        guidata(hMainFigure,NmrData);

        Setup_NmrData();
        NmrData=guidata(hMainFigure);
        
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function Import_Matlab_structure(~, ~)
        %Import data from a Matlab structure containing fields
        %fid, sw, sfrq, ppmAxis, nucleus
        % with the following structure
        %  fid: matlab array with dimensions [np dim2 dim3 dim4]
        %       dim3 and dim4 can be left out
        %  sw: spectral width in Hz
        %  sfrq: spectromter frquency in Hz
        %  ppmAxis: chemical shift axis in ppm
        %  nucleus: used isotope e..g 1H or 31P
        %


        Initiate_NmrData();
        NmrData=guidata(hMainFigure);
        [filename, pathname] = uigetfile('*.mat','Import MATLAB structure Data');
        filepath=[pathname filename];
        S=load(filepath,'-mat');
        A=fields(S);
        S=S.(A{1});

        NmrData.FID=S.fid;

        dims=ndims(NmrData.FID);
        tmp=size( NmrData.FID);


        switch dims

            case 1
                NmrData.arraydim=1;
                NmrData.narray2=1;
                NmrData.ngrad=1;

            case 2
                NmrData.arraydim=tmp(2);
                NmrData.ngrad= tmp(2);
                NmrData.ngrad2= tmp(2);
                NmrData.narray2=1;

            case 3
                NmrData.arraydim=tmp(2).*tmp(3);
                NmrData.ngrad= tmp(2);
                NmrData.ngrad2= tmp(2)*tmp(3);
                NmrData.narray2=tmp(3);
                NmrData.FID=reshape(NmrData.FID,tmp(1),tmp(2).*tmp(3));


            case 4
                NmrData.arraydim=tmp(2).*tmp(3).*tmp(4);
                NmrData.ngrad= tmp(2);
                NmrData.ngrad2= tmp(2)*tmp(3);
                NmrData.narray2=tmp(3);
                NmrData.narray3=tmp(4);
                NmrData.FID=reshape(NmrData.FID,tmp(1),tmp(2).*tmp(3).*tmp(4));

            otherwise
                logtext='GNAT only supports up to 4 dimensions';
                error(logtext)

        end


        NmrData.np=numel(S.ppmAxis);
        NmrData.sfrq=S.sfrq/1e6;
        NmrData.sw=S.sw./NmrData.sfrq;
        NmrData.sp=S.ppmAxis(1);

    switch S.nucleus
        case '<H'
            NmrData.gamma=267524618.573;
        case '1H'
            NmrData.gamma=267524618.573;
        case '2H'
            NmrData.gamma=41066000;
        case '10B'
            NmrData.gamma=28747000;
        case '11B'
            NmrData.gamma=85847000;
        case '13C'
            NmrData.gamma=67283000;
        case '14N'
            NmrData.gamma=19338000;
        case '15N'
            NmrData.gamma=-27126000;
        case '17O'
            NmrData.gamma=-36281000;
        case '19F'
            NmrData.gamma=251815000;
        case '23Na'
            NmrData.gamma=70808000;
        case '27Al'
            NmrData.gamma=69764000;
        case '29Si'
            NmrData.gamma=-53190000;
        case '31P'
            NmrData.gamma=108394000;
            
        otherwise
            logtext='unknown nucleus - defaulting to proton';
            disp(logtext)
            NmrData.gamma=267524618.573;
    end


        NmrData.gamma=1;
     

        NmrData.type='Matlab structure';
        NmrData.at=NmrData.np/(NmrData.sw*NmrData.sfrq);
        NmrData.fn=NmrData.np;
        NmrData.rp=0;
        NmrData.lp=0;
        NmrData.delta='non existing';
        NmrData.DELTA='non existing';
        NmrData.dosyconstant=0;
        %NmrData.arraydim=1;
        %NmrData.ngrad=1;
        NmrData.filename=filepath;
        NmrData.fshift=0;
        
        guidata(hMainFigure,NmrData);
        Setup_NmrData();

        guidata(hMainFigure,NmrData);
    end
    function Open_data( ~, ~, Path)
        Initiate_NmrData();
        NmrData=guidata(hMainFigure);
        if nargin==3
            filepath=Path;
        else
            
            [filename, pathname] = uigetfile('*.mat','Open NMR Data');
            if isnumeric(filename) || isnumeric(pathname)
                if filename==0 || pathname==0
                    return
                end
            end
            filepath=[pathname filename];
        end
        S=load(filepath,'-mat');
        S=S.NmrData;
        % Copy over all relevant parameters
        names=fieldnames(S);
        for nstruct=1:length(names)
            NmrData.(names{nstruct})=S.(names{nstruct});
        end
        NmrData.fshift=zeros(1,NmrData.arraydim);
        set(hEditFn,'string',num2str(NmrData.fn));
        set(hEditNp,'string',num2str(NmrData.np));
        set(hEditPh1,'string',num2str(NmrData.lp,4))
        set(hEditPh0,'string',num2str(NmrData.rp,4))
        set(hSliderPh0,'value',NmrData.rp);
        set(hSliderPh1,'value',NmrData.lp);
        set(hEditFlip,'string',num2str(NmrData.gradnr));
        set(hEditFlip2,'string',num2str(NmrData.array2nr));
        set(hEditFlipSpec,'string',num2str(NmrData.flipnr));
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hTextFlip,'string',['/' num2str(NmrData.ngrad)]);
        set(hTextFlip2,'string',['/' num2str(NmrData.narray2)]);
        set(hTextFlipSpec,'string',['/' num2str(NmrData.arraydim)]);
        hPlot=plot(hAxes,NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)));
        set(hPlot,'HitTest','off')
        
        if isempty(NmrData.xlim)
        else
            xlim(NmrData.xlim);
        end
        if isempty(NmrData.ylim)
        else
            ylim(NmrData.ylim);
        end
        set(hAxes,'Xdir','Reverse')
        set(hPushCopyGtoI,'Enable','On')
        guidata(hMainFigure,NmrData);
        guidata(hMainFigure,NmrData); WriteLogDispInfo(NmrData.filename)
        
        % Check size of array
        dimension=NmrData.narray2;
        set(hEditNgrad,'Enable','off')
        if dimension==1 %1D and 2D data
            if NmrData.arraydim~=1
                set(hEditNgrad,'Enable','on')
            end
            set(hEditArray2,'Enable','off')
            set(hEditArray3,'Enable','off')
        else %nD data
            set(hEditNgrad,'Enable','on')
            set(hEditArray2,'Enable','on')
            if NmrData.narray3>1
                set(hEditArray3,'Enable','on')
            else
                set(hEditArray3,'Enable','off')
            end
        end
        guidata(hMainFigure,NmrData);
        
        if isfield(NmrData,'xlim_spec')==1 % MJS edited to work
            scale=NmrData.xlim_spec;
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        else
            scale=[0 0];
            set(hEditScaleUp,'string',num2str(scale(2)));
            set(hEditScaleDown,'string',num2str(scale(1)));
        end
        if isfield(NmrData,'phase_type')==1 % MJS edited to work
            if NmrData.phase_type==1
                set(hScopeGroup,'SelectedObject',hRadioScopeIndividual)
                set(hPushCopyGtoI,'Enable','On')
            end
        end

    end
    function SaveDataMatlab( ~, ~)
        NmrData=guidata(hMainFigure);
        [filename, pathname] = uiputfile('*.mat','Save NMR Data');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        NmrData.xlim= get(hAxes,'xlim');
        NmrData.ylim= get(hAxes,'ylim');
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                NmrData.phase_type=0;
            case hRadioScopeIndividual
                NmrData.phase_type=1;
        end
        guidata(hMainFigure,NmrData);
        save(filepath,'NmrData','-v7.3');
    end
    function SaveFIDDataToolboxASCII( ~, ~)
        [filename, pathname] = uiputfile('*.txt','Export data in ASCII format');
       if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        ExportToolboxFormat(statfil, 1, 1, filename, pathname);
    end
    function SaveComplexSpecDataToolboxASCII( ~, ~)
        [filename, pathname] = uiputfile('*.txt','Export data in ASCII format');
       if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        ExportToolboxFormat(statfil, 2, 1, filename, pathname);
        
    end
    function SaveRealSpecDataToolboxASCII( ~, ~)
        [filename, pathname] = uiputfile('*.txt','Export data in ASCII format');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        ExportToolboxFormat(statfil, 3, 1, filename, pathname);
    end
    function SaveFIDDataToolboxBinary( ~, ~)
        [filename, pathname] = uiputfile('*.txt','Export data in ASCII format');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        ExportToolboxFormat(statfil, 1, 2, filename, pathname);
    end
    function SaveComplexSpecDataToolboxBinary( ~, ~)
        [filename, pathname] = uiputfile('*.txt','Export data in ASCII format');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        ExportToolboxFormat(statfil, 2, 2, filename, pathname);
    end
    function SaveRealSpecDataToolboxBinary( ~, ~)
        [filename, pathname] = uiputfile('*.txt','Export data in ASCII format');
       if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        ExportToolboxFormat(statfil, 3, 2, filename, pathname);
    end
    function QuitToolbox(~, ~)
        if isfield(NmrData,'hEditParameters')
            if isvalid(NmrData.hEditParameters)
                close(NmrData.hEditParameters)
            end
        end
        if isfield(NmrData,'hSettings')
            if isvalid(NmrData.hSettings)
                close(NmrData.hSettings)
            end
        end
        delete(hMainFigure)
    end
    function ExportDOSY( ~, ~)
        [filename, pathname] = uiputfile('*.mat','Save NMR Data for DOSY processing');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        pfgdata=PreparePfgnmrdata();
        save(filepath,'pfgdata','-v7.3');
    end
    function ExportPARAFAC( ~, ~)
        [filename, pathname] = uiputfile('*.pfc','Save NMR data for PARAFAC processing');
         if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        pfgnmrdata=PreparePfgnmr3Ddata();
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        Specrange=speclim;
        if length(Specrange)~=2
            error('SCORE: Specrange should have excatly 2 elements')
        end
        if Specrange(1)<pfgnmrdata.sp
            guidata(hMainFigure,NmrData); WriteLogDispInfo('SCORE: Specrange(1) is too low. The minumum will be used')
            Specrange(1)=pfgnmrdata.sp;
        end
        if Specrange(2)>(pfgnmrdata.wp+pfgnmrdata.sp)
            guidata(hMainFigure,NmrData); WriteLogDispInfo('SCORE: Specrange(2) is too high. The maximum will be used')
            Specrange(2)=pfgnmrdata.wp+pfgnmrdata.sp;
        end
        for k=1:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>Specrange(1))
                begin=k-1;
                break;
            end
        end
        for k=begin:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>=Specrange(2))
                endrange=k;
                break;
            end
        end
        pfgnmrdata.sp=pfgnmrdata.Ppmscale(begin);
        pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(begin);
        pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(begin:endrange);
        pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(begin:endrange,:,:);
        pfgnmrdata.np=length(pfgnmrdata.Ppmscale) ;
        save(filepath,'pfgnmrdata','-v7.3');
    end
    function ExportTDData( ~, ~)
        [filename, pathname] = uiputfile('*.txt','Save time domain NMR data');
         if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        %print out FID data to file
        fprintf(statfil,'%-s  \n',['Time domain data for: ' NmrData.filename]);
        fprintf(statfil,'%-s\t\t\t  %s \n','Data type: ', NmrData.type);
        fprintf(statfil,'%-s\t\t\t %-f  \n','Spectrometer frequency (MHz): ', NmrData.sfrq);
        fprintf(statfil,'%-s\t\t %-d  \n','Number of complex points per FID: ', NmrData.np);
        fprintf(statfil,'%-s\t\t\t\t %-f  \n','Spectral width(ppm): ', NmrData.sw);
        fprintf(statfil,'%-s\t\t\t\t %-f  \n','Acquistion time: ', NmrData.at);
        fprintf(statfil,'%-s\t %-f  \n','Frequency at right end of spectrum (ppm): ', NmrData.sp);
        fprintf(statfil,'%-s\t %-f  \n','Diffusion encoding time (little delta) (s): ', NmrData.delta);
        fprintf(statfil,'%-s\t\t\t\t %-f  \n','Diffusion time (s): ', NmrData.DELTA);
        fprintf(statfil,'%-s\t\t\t\t %-f  \n','Magnetogyric ratio: ', NmrData.gamma);
        fprintf(statfil,'%-s\t\t\t\t\t %-f  \n','DOSYconstant: ', NmrData.dosyconstant);
        fprintf(statfil,'%-s\n','Gradient amplitues (T/m): ');
        for k=1:length(NmrData.Gzlvl)
            fprintf(statfil,'%-16f\n',NmrData.Gzlvl(k));
        end
        fprintf(statfil,'%-s\n','FID data points: ');
        fprintf(statfil,'%s\t\t%s\n','real', 'imag');
        for m=1:length(NmrData.FID(1,:))
            for k=1:length(NmrData.FID(:,m))
                fprintf(statfil,'%-16f\t%-16f\n',real(NmrData.FID(k,m)),...
                    imag(NmrData.FID(k,m)));
            end
        end
        fclose(statfil);
    end
    
    function ExportBruker( ~, ~)

        [filename, pathname] = uiputfile('*.*','Save processed current NMR Data in Bruker format to a new folder');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end

        if isunix()==1
            OSslash='/';
        else
            OSslash='\';
        end



        if not(strcmpi(NmrData.type, 'Bruker'))
            errordlg('This is currently only supported for data that was imported as Bruker data')
        else
       
            SPECTRA=NmrData.SPECTRA;

            Rc=1i*(pi/180);
            lpCorrDSP= -linspace(0,1,NmrData.fn)*(NmrData.dspPhase+360);

            switch get(hScopeGroup,'SelectedObject')
                case hRadioScopeGlobal
                    %apply the same phase parameters to all spectra in
                    %array

                    lpCorr= -linspace(0,1,NmrData.fn)*(NmrData.lp +(-NmrData.lp+NmrData.lpOrg));
                    rpChange=-NmrData.rp +(NmrData.rp-NmrData.rpOrg);
                    phaseCorr=...
                        (exp(Rc*(rpChange + lpCorr)))';
                    SPECTRA=SPECTRA.*repmat...
                        (phaseCorr,1,(NmrData.arraydim));

                case hRadioScopeIndividual
                    %apply individual phase parameters to all spectra in
                    %array

                    for ind_num=1:NmrData.arraydim
                        lpCorr= -linspace(0,1,NmrData.fn)*(NmrData.lpInd(ind_num) +(-NmrData.lpInd(ind_num)+NmrData.lpOrg));
                        rpChange=-NmrData.rpInd(ind_num) +(NmrData.rpInd(ind_num)-NmrData.rpOrg);
                        phaseCorr=...
                            (exp(Rc*(rpChange + lpCorr)))';
                        SPECTRA(:,ind_num)=SPECTRA(:,ind_num).*phaseCorr;

                    end


                otherwise
                    error('illegal choice')

            end

            % do the DSP correction
            phaseCorr=...
                (exp(Rc*(lpCorrDSP)))';

            SPECTRA=SPECTRA.*repmat...
                (phaseCorr,1,(NmrData.arraydim));


            FID=zeros(size(SPECTRA));
            for k=1:NmrData.arraydim
                SPECTRA(:,k)=fftshift(SPECTRA(:,k));
                FID(:,k)=ifft(SPECTRA(:,k));
                %
                FID(:,k)=flip(FID(:,k));

            end
            np=NmrData.np;
            FID(np+1:end,:)=[];
            %return
            FID_tot=zeros(np*2,NmrData.arraydim);
            for k=1:NmrData.arraydim
                tr=-real(FID(:,k));
                ti=imag(FID(:,k));
                FID_tot(1:2:end,k)=tr;
                FID_tot(2:2:end,k)=ti;
            end

            %fileID=fopen(FIDfile,'w','l');


            switch str2double(NmrData.brukerdata.acqus.DTYPA) %MN 29 March correcting chunkSize to accomodate for Neo
                case 0 %32 bit integer
                    byte_size='int32';
                    %chunkSize = 256;
                case 1  %double
                    byte_size='double';
                    %chunkSize = 128;
                case 2  %double
                    byte_size='double'; %MN 13March2017 Not sure if 1 or 2 does any difference to Matlab
                    %chunkSize = 128;
                otherwise
                    error('unknown data format (DTYPA)')
            end
            old_path=NmrData.filename;
            filepath=[pathname filename];
            if NmrData.arraydim==1
                %single experiment
                copyfile( old_path, filepath )
                FIDfile=[filepath OSslash 'fid'];
                fileID=fopen(FIDfile,'w','l');
                for k=1:NmrData.arraydim
                    fwrite(fileID, FID_tot(:,k), byte_size);
                end
                fclose(fileID);
            else
                %an array imported as a series of fids in separate
                %experiments              
                if isfield(NmrData,'explist')
                    % ACP 2025 - chop the last part of oldpath off %
                    chopped_old_path = split(old_path, OSslash)
                    % check that the chopped part is an int, ie. an expno %
                    should_be_int = str2num( cell2mat(chopped_old_path(end)) )
                    if isempty(should_be_int) 
                        error('[end] of old_path not a number parsed by str2num! GNAT.m/10208')
                    elseif 0 ~= mod(should_be_int, 1) 
                        error('[end] of old_path not an integer! GNAT.m/10210')
                    else
                        % continue
                        clear should_be_int
                    end
                        
                    
                         

                    for k=1:NmrData.arraydim
                        filepath=[pathname filename];
                        expno_str = num2str(NmrData.explist(k))

                        joined_old_path = cell2mat(join([chopped_old_path(1:end-1); expno_str], OSslash))
                        joined_new_path = [filepath OSslash expno_str]
                        
                        copyfile( joined_old_path, joined_new_path )
                        FIDfile=[filepath OSslash num2str(NmrData.explist(k)) OSslash 'fid'];

                        fileID=fopen(FIDfile,'w','l');
                        fwrite(fileID, FID_tot(:,k), byte_size);
                        fclose(fileID);
                    end
                else
                    %and array imported as a 2D experiments
                    % old_path=NmrData.filename;
                    copyfile( old_path, filepath )
                    FIDfile=[filepath OSslash 'ser'];
                    fileID=fopen(FIDfile,'w','l');
                    for k=1:NmrData.arraydim
                        fwrite(fileID, FID_tot(:,k), byte_size);
                    end
                    fclose(fileID);
                end
            end


        end
    end
    function ExportConvolData( ~, ~)
        %Export function for use of spectra in a external deconvolutiuon
        %GUI
        [filename, pathname] = uiputfile('*.txt','Save data for convolution GUI');
         if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        %print out FID data to file
        % fprintf(statfil,'%-s  \n',['Time domain data for: ' NmrData.filename]);
        % fprintf(statfil,'%-s\t\t\t  %s \n','Data type: ', NmrData.type);
        % fprintf(statfil,'%-s\t\t\t %-f  \n','Spectrometer frequency (MHz): ', NmrData.sfrq);
        % fprintf(statfil,'%-s\t\t %-d  \n','Number of complex points per FID: ', NmrData.np);
        % fprintf(statfil,'%-s\t\t\t\t %-f  \n','Spectral width(ppm): ', NmrData.sw);
        % fprintf(statfil,'%-s\t\t\t\t %-f  \n','Acquistion time: ', NmrData.at);
        % fprintf(statfil,'%-s\t %-f  \n','Frequency at right end of spectrum (ppm): ', NmrData.sp);
        % fprintf(statfil,'%-s\t %-f  \n','Diffusion encoding time (little delta) (s): ', NmrData.delta);
        % fprintf(statfil,'%-s\t\t\t\t %-f  \n','Diffusion time (s): ', NmrData.DELTA);
        % fprintf(statfil,'%-s\t\t\t\t %-f  \n','Magnetogyric ratio: ', NmrData.gamma);
        % fprintf(statfil,'%-s\t\t\t\t\t %-f  \n','DOSYconstant: ', NmrData.dosyconstant);
        % fprintf(statfil,'%-s\n','Gradient amplitues (T/m): ');


        %Here we may want to write out some information about the data

        %Write out the X and Y labels
        fprintf(statfil,'%-s\t','X');
        for k=1:NmrData.arraydim
            fprintf(statfil,'%-s%s\t','Y',num2str(k-1));
        end
        fprintf(statfil,'\n');

        %Write out the X and Y data of the real spectra
        for p=1:NmrData.fn
            fprintf(statfil,'%-16f',NmrData.Specscale(p));
            for k=1:NmrData.arraydim
                fprintf(statfil,'%-16f\t',real(NmrData.SPECTRA(p)));
            end
            fprintf(statfil,'\n');
        end
        fclose(statfil);
    end
    
    function Edit_Settings( ~, ~)
        NmrData=guidata(hMainFigure);
        if isfield(NmrData,'hSettings')
            if isvalid(NmrData.hSettings)
                close(NmrData.hSettings)
            end
        end
        hSettings=figure(...
            'NumberTitle','Off',...
            'MenuBar','none',...
            'Units','Normalized',...
            'Visible','Off',...
            'DeleteFcn',@hSettings_DeleteFcn,...
            'Toolbar','none',...
            'ResizeFcn' , @hSettingsResizeFcn,...
            'Name','Settings');
        NmrData.hSettings=hSettings;
        hSettingsUiTabGroup=uitabgroup(...
            'Parent',hSettings,...
            'Position',[0.0 0.0 1.0 1.0],...
            'Units','Normalized');
        hSettingsUiTab1=uitab(...
            'Parent',hSettingsUiTabGroup,...
            'Title','Settings',...
            'Units','Normalized');
        hSettingsUiTab2=uitab(...
            'Parent',hSettingsUiTabGroup,...
            'Title','Diffusion',...
            'Units','Normalized');
        hSettingsUiTab3=uitab(...
            'Parent',hSettingsUiTabGroup,...
            'Title','NUG',...
            'Units','Normalized');
        hSettingsUiTab4=uitab(...
            'Parent',hSettingsUiTabGroup,...
            'Title','Relaxation',...
            'Units','Normalized');
        
        hDCGroup=uibuttongroup(...
            'Parent',hSettingsUiTab1,...
            'Title','',...
            'FontWeight','bold',...
            'TitlePosition','centertop',...
            'Title','DC correct FID',...
            'ForegroundColor','Blue',...
            'Units','Normalized',...
            'SelectionChangeFcn', { @DC_Callback},...
            'Visible','On',...
            'Position',[0.0,0.5 ,0.25 ,0.2]);
        hDCYesPPM = uicontrol(...
            'Parent',hDCGroup,...
            'Style','RadioButton',...
            'String','Yes',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.1 0.6 0.5 0.25]);
        hDCNoPPM = uicontrol(...
            'Parent',hDCGroup,...
            'Style','RadioButton',...
            'String','No',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.1 0.2 0.5 0.25]);
        
        hDCLSSpecGroup=uibuttongroup(...
            'Parent',hSettingsUiTab1,...
            'Title','',...
            'FontWeight','bold',...
            'TitlePosition','centertop',...
            'Title','Left shift spectrum',...
            'ForegroundColor','Blue',...
            'Units','Normalized',...
            'SelectionChangeFcn', { @LSSpec_Callback},...
            'Visible','On',...
            'Position',[0.25,0.2 ,0.25 ,0.2]);
        hDCSpecLinPPM = uicontrol(...
            'Parent',hDCLSSpecGroup,...
            'Style','RadioButton',...
            'String','Linear',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.01 0.6 0.5 0.25]);
        hDCSpecConPPM = uicontrol(...
            'Parent',hDCLSSpecGroup,...
            'Style','RadioButton',...
            'String','Const',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.01 0.2 0.5 0.25]);
        hEditLSspec=uicontrol(...
            'Parent',hDCLSSpecGroup,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','The spectrum will be left shifted with lsspec data points',...
            'Max',1,...
            'Position',[0.51 0.3 0.3 0.25 ],...
            'CallBack', { @EditLSspec_Callback});
        %hTextlsspec=
        uicontrol(...
            'Parent',hDCLSSpecGroup,...
            'Style','text',...
            'Units','Normalized',...
            'ForegroundColor','Blue',...
            'horizontalalignment','center',...
            'FontWeight','bold',...
            'Position',[0.51 0.55 0.3 0.2 ],...
            'String','lsspec' );
        
        hDCSpecGroup=uibuttongroup(...
            'Parent',hSettingsUiTab1,...
            'Title','',...
            'FontWeight','bold',...
            'TitlePosition','centertop',...
            'Title','DC correct spectrum',...
            'ForegroundColor','Blue',...
            'Units','Normalized',...
            'SelectionChangeFcn', { @DCSpec_Callback},...
            'Visible','On',...
            'Position',[0.25,0.5 ,0.25 ,0.2]);
        hDCSpecYesPPM = uicontrol(...
            'Parent',hDCSpecGroup,...
            'Style','RadioButton',...
            'String','Yes',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.1 0.6 0.5 0.25]);
        hDCSpecNoPPM = uicontrol(...
            'Parent',hDCSpecGroup,...
            'Style','RadioButton',...
            'String','No',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.1 0.2 0.5 0.25]);
        
        hEditfpmult=uicontrol(...
            'Parent',hSettingsUiTab1,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','The first data point in the FID(s) will be multiplied with fpmult',...
            'Max',1,...
            'Position',[0.075 0.80 0.1 0.05 ],...
            'CallBack', { @Editfpmult_Callback});
        %hTextfpmult=
        uicontrol(...
            'Parent',hSettingsUiTab1,...
            'Style','text',...
            'Units','Normalized',...
            'ForegroundColor','Blue',...
            'horizontalalignment','left',...
            'FontWeight','bold',...
            'Position',[0.09 0.85 0.1 0.05 ],...
            'String','fpmult' );
        hEditlrfid=uicontrol(...
            'Parent',hSettingsUiTab1,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','The number of data points to left rotate the FID(s)',...
            'Max',1,...
            'Position',[0.275 0.80 0.1 0.05 ],...
            'CallBack', { @Editlrfid_Callback});
        %hTextlrfid=
        uicontrol(...
            'Parent',hSettingsUiTab1,...
            'Style','text',...
            'Units','Normalized',...
            'ForegroundColor','Blue',...
            'horizontalalignment','left',...
            'FontWeight','bold',...
            'Position',[0.305 0.85 0.1 0.05 ],...
            'String','lrfid' );
        
        hFittypeGroup=uibuttongroup(...
            'Parent',hSettingsUiTab1,...
            'Title','',...
            'FontWeight','bold',...
            'TitlePosition','centertop',...
            'Title','Fitting routine',...
            'ForegroundColor','Blue',...
            'Units','Normalized',...
            'SelectionChangeFcn', { @Fittype_Callback},...
            'Visible','On',...
            'Position',[0.6,0.5 ,0.3 ,0.2]);
        hFittypeLsq = uicontrol(...
            'Parent',hFittypeGroup,...
            'Style','RadioButton',...
            'String','lsqcurvefit (*)',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.1 0.6 0.7 0.25]);
        hFittypeFmin = uicontrol(...
            'Parent',hFittypeGroup,...
            'Style','RadioButton',...
            'String','fminsearch',...
            'FontWeight','Bold',...
            'Units','normalized',...
            'Position',[0.1 0.2 0.7 0.25]);
        %hTextFittpemult=
        uicontrol(...
            'Parent',hSettingsUiTab1,...
            'Style','text',...
            'Units','Normalized',...
            'ForegroundColor','Black',...
            'horizontalalignment','left',...
            'Position',[0.6 0.28 0.30 0.2 ],...
            'String','(*) Recommended [requires Optim Toolbox]' );%switch
        
        hEditNMRPanel=uipanel(...
            'Parent',hSettingsUiTab3,...
            'Title','Non Uniform Gradient (NUG) parameters',...
            'FontWeight','bold',...
            'ForegroundColor','Blue',...
            'Visible','Off',...
            'TitlePosition','centertop',...
            'Units','Normalized',...
            'Position',[0.0, 0.5 ,1.0, 0.5]);
        %hTextNUGTable=
        uicontrol(...
            'Parent',hEditNMRPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'horizontalalignment','c',...
            'Position',[0.38 0.85 0.25 0.1 ],...
            'String','NUG Coefficients' );
        hTableNUG=uitable(...
            'Data',{NmrData.probename; NmrData.gcal ;NmrData.nug(1) ;NmrData.nug(2) ;NmrData.nug(3) ;NmrData.nug(4) },...
            'Parent',hEditNMRPanel,...
            'Units','Normalized',...
            'ColumnEditable',true(1,6),...
            'ColumnName',{'Values'},...
            'RowName',{'probe' 'gcal' 'c1' 'c2' 'c3' 'c4'},...
            'ColumnFormat',{'char' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric'},...
            'Position',[0.35 0.20 0.3 0.65 ],...
            'CellEditCallBack', { @TableNUG_Callback});
        %hButtonReadNUG=
        uicontrol(...
            'Parent',hEditNMRPanel,...
            'Style','PushButton',...
            'Units','Normalized',...
            'Visible','on',...
            'TooltipString','Read in NUG data from file',...
            'FontWeight','bold',...
            'Position',[0.42 0.05 0.2 0.1 ],...
            'String','Import',...
            'CallBack', { @ReadNUG_Callback});
        hTextMancs=uicontrol(...
            'Parent',hEditNMRPanel,...
            'Style','text',...
            'Units','Normalized',...
            'Visible','off',...
            'FontWeight','bold',...
            'horizontalalignment','c',...
            'Position',[0.05 0.25 0.25 0.1 ],...
            'String','UoM Spectrometers' );
        hButtonv400=uicontrol(...
            'Parent',hEditNMRPanel,...
            'Style','PushButton',...
            'Units','Normalized',...
            'Visible','off',...
            'FontWeight','bold',...
            'Position',[0.05 0.1 0.1 0.1 ],...
            'String','v400',...
            'CallBack', { @Buttonv400_Callback});
        hButtonv500=uicontrol(...
            'Parent',hEditNMRPanel,...
            'Style','PushButton',...
            'Units','Normalized',...
            'Visible','off',...
            'FontWeight','bold',...
            'Position',[0.2 0.1 0.1 0.1 ],...
            'String','v500',...
            'CallBack', { @Buttonv500_Callback});
        
        hEditDOSYPanel=uipanel(...
            'Parent',hSettingsUiTab2,...
            'Title','Diffusion related parameters',...
            'FontWeight','bold',...
            'ForegroundColor','Blue',...
            'TitlePosition','centertop',...
            'Visible','off',...
            'Units','Normalized',...
            'Position',[0.0, 0.0 ,1.0, 1.0]);
        if ~strcmp(NmrData.Gzlvl,'non existing')
            hTableGzlvl=uitable(...
                'Data',NmrData.Gzlvl',...
                'Parent',hEditDOSYPanel,...
                'Units','Normalized',...
                'ColumnEditable',true(1,numel(NmrData.Gzlvl)),...
                'ColumnName',{'T/m'},...
                ...'RowName',{'probe' 'gcal' 'c1' 'c2' 'c3' 'c4'},...
                ...'ColumnFormat',{'char' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric'},...
                'Position',[0.6 0.05 0.4 0.9 ],...
                'CellEditCallBack', { @TableGzlvl_Callback});
        end
        hEditDELTA=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','Experimental diffusion time',...
            'Max',1,...
            'Position',[0.05 0.4 0.1 0.05 ],...
            'CallBack', { @EditDELTA_Callback});
        %hTextDELTA=
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'FontName','Symbol',...
            'Position',[0.075 0.45 0.05 0.05 ],...8.841
            'String','D' );
        hEditDELTAprime=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','Corrected diffusion time',...
            'Max',1,...
            'Position',[0.2 0.4 0.1 0.05 ],...
            'CallBack', { @EditDELTAprime_Callback});
        %hTextDELTAprime2=
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            ...'FontName','Symbol',...
            'Position',[0.25 0.45 0.02 0.05 ],...
            'String','''' );
        %hTextDELTAprime=
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'FontName','Symbol',...
            'Position',[0.235 0.45 0.02 0.05 ],...
            'String','D' );
        hEditdelta=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','Diffusion encoding time',...
            'Max',1,...
            'Position',[0.35 0.4 0.1 0.05 ],...
            'CallBack', { @Editdelta_Callback});
        %hTextdelta=
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'FontName','Symbol',...
            'Position',[0.375 0.45 0.05 0.05 ],...
            'String','d' );
        hEditTau=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','Time between pulses in a bipolar pulse pair',...
            'Max',1,...
            'Position',[0.35 0.25 0.1 0.05 ],...8.841
            'CallBack', { @EditTau_Callback});
        %hTextTau=
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'horizontalalignment','c',...
            'FontName','Symbol',...
            'Position',[0.35 0.3 0.1 0.05 ],...
            'String','t' );
        hEditDosygamma=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','Magnetogyric ratio of the studied nucleus',...
            'Max',1,...
            'Position',[0.05 0.25 0.25 0.05 ],...
            'CallBack', { @EditDosygamma_Callback});
        %hTextgamma=
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'FontName','Symbol',...
            'Position',[0.15 0.3 0.05 0.05 ],...
            'String','g' );
        hEditDosyconstant=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','edit',...
            'Visible','On',...
            'BackgroundColor','w',...
            'Units','Normalized',...
            'TooltipString','',...
            'Max',1,...
            'Position',[0.05 0.1 0.25 0.05 ],...
            'CallBack', { @EditDosyconstant_Callback});
        %hTextdosyconstant=
        uicontrol(...8.841
            'Parent',hEditDOSYPanel,...8.841
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'Position',[0.075 0.15 0.2 0.05 ],...
            'String','dosyconstant' );

        %hTextMethods=
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...EditScaleUp_Callback
            ...'ForegroundColor','Blue',...
            'horizontalalignment','l',...
            'Position',[0.05 0.9 0.4 0.05 ],...
            'String','Calculate diffusion parameters' );

        %hButtonMeth1 = 
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','PushButton',...
            'String','Calculate',...
            'Units','normalized',...
            'TooltipString',...
            'Calculate corrected DELTA (and dosyconstant) based on pulse sequence and gradient shape',...
            'Position',[0.05 0.85 0.15 0.05],...
            'Callback',{ @ButtonMeth1_Callback});
        %hButtonMeth2 = 
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','PushButton',...
            'String','Original',...
            'Units','normalized',...
            'TooltipString','Restore original DOSY parameters',...
            'Position',[0.20 0.85 0.15 0.05],...
            'Callback',{ @ButtonRestore_Callback}); 
        
        %   Pulse sequence Popup list %GDP 04iii2021
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'horizontalalignment','l',...
            'Position',[0.05 0.7 0.4 0.05 ],...
            'String','Pulse sequence' );
        hPPpopup=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','popupmenu',...
            'Units','Normalized',...
            'TooltipString','Selects the pulse sequence used for diffusion encoding',...
            'FontWeight','normal',...
            'FontSize',10,...
            'HorizontalAlignment','center',...
            'String',...
            '|Oneshot|Monopolar|Bipolar|Double bipolar',...
            'Position',[0.25 0.68 0.25 0.08 ],...
            'CallBack', { @pulseprog_Callback});
        
        %   Gradient Popup list %GDP 04iii2021
        uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','text',...
            'Units','Normalized',...
            'FontWeight','bold',...
            'horizontalalignment','l',...
            'Position',[0.05 0.6 0.4 0.05 ],...
            'String','Gradient shape' );
        hGPNAMpopup=uicontrol(...
            'Parent',hEditDOSYPanel,...
            'Style','popupmenu',...
            'Units','Normalized',...
            'TooltipString','Selects the shape of the gradient pulse used for diffusion encoding',...
            'FontWeight','normal',...
            'FontSize',10,...
            'HorizontalAlignment','center',...
            'String',...
            '|SINE|SMSQ|RECT',...
            'Position',[0.25 0.58 0.25 0.08 ],...
            'CallBack', { @GPNAM_Callback});
        
        
        hEditRelaxationPanel=uipanel(...
            'Parent',hSettingsUiTab4,...
            'Title','Relaxation related parameters',...
            'FontWeight','bold',...
            'ForegroundColor','Blue',...
            'TitlePosition','centertop',...
            'Visible','off',...
            'Units','Normalized',...
            'Position',[0.0, 0.0 ,1.0, 1.0]);
        if ~isempty(NmrData.d2)
            hTableTau=uitable(...
                'Data',NmrData.d2,...
                'Parent',hEditRelaxationPanel,...
                'Units','Normalized',...
                'ColumnEditable',true(1,numel(NmrData.d2)),...
                'ColumnName',{'sec'},...
                ...'RowName',{'probe' 'gcal' 'c1' 'c2' 'c3' 'c4'},...
                ...'ColumnFormat',{'char' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric'},...
                'Position',[0.5 0.05 0.2 0.9 ],...
                'CellEditCallBack', { @TableTau_Callback});
            uicontrol(...
                'Parent',hEditRelaxationPanel,...
                'Style','text',...
                'Units','Normalized',...
                'FontWeight','bold',...
                'horizontalalignment','l',...
                'Position',[0.525 0.95 0.4 0.05 ],...
                'String','Delays (vdlist)' );
            
            uicontrol(...
                'Parent',hEditRelaxationPanel,...
                'Style','text',...
                'Units','Normalized',...
                'FontWeight','bold',...
                'horizontalalignment','l',...
                'Position',[0.05 0.45 0.4 0.05 ],...
                'String','Revert to original values' );
            
            %hButtonVCRevert = 
            uicontrol(...
                'Parent',hEditRelaxationPanel,...
                'Style','PushButton',...
                'String','Revert',...
                'Units','normalized',...
                'TooltipString',...
                'Revert to original values',...
                'Position',[0.1 0.40 0.15 0.05],...
                'Callback',{ @ButtonVCRevert_Callback});
            
            if isfield(NmrData,'vclist')
                
                hTableVclist=uitable(...
                    'Data',NmrData.vclist,...
                    'Parent',hEditRelaxationPanel,...
                    'Units','Normalized',...
                    'ColumnEditable',true(1,numel(NmrData.vclist)),...
                    'ColumnName',{'count'},...
                    ...'RowName',{'probe' 'gcal' 'c1' 'c2' 'c3' 'c4'},...
                    ...'ColumnFormat',{'char' 'numeric' 'numeric' 'numeric' 'numeric' 'numeric'},...
                    'Position',[0.75 0.05 0.2 0.9 ],...
                    'CellEditCallBack', { @TableVclist_Callback});
                uicontrol(...
                    'Parent',hEditRelaxationPanel,...
                    'Style','text',...
                    'Units','Normalized',...
                    'FontWeight','bold',...
                    'horizontalalignment','l',...
                    'Position',[0.775 0.95 0.4 0.05 ],...
                    'String','Counter (vclist)' );
                
               uicontrol(...
                    'Parent',hEditRelaxationPanel,...
                    'Style','text',...
                    'Units','Normalized',...
                    'FontWeight','bold',...
                    'horizontalalignment','l',...
                    'Position',[0.1 0.75 0.4 0.05 ],...
                    'String','Loop duration (s)' );

                hEditVCLIST=uicontrol(...
                    'Parent',hEditRelaxationPanel,...
                    'Style','edit',...
                    'Visible','On',...
                    'BackgroundColor','w',...
                    'Units','Normalized',...
                    'TooltipString','Constant for converting vclist to vdlist',...
                    'Max',1,...
                    'Position',[0.1 0.7 0.15 0.05 ],...
                    'CallBack', { @EditVCLIST_Callback});
                set(hEditVCLIST,'string',num2str(NmrData.vc_constant));
                
                uicontrol(...
                    'Parent',hEditRelaxationPanel,...
                    'Style','text',...
                    'Units','Normalized',...
                    'FontWeight','bold',...
                    'horizontalalignment','l',...
                    'Position',[0.05 0.87 0.4 0.05 ],...
                    'String','Convert counter to delays' );
                
                %hButtonVCConvert = 
                uicontrol(...
                    'Parent',hEditRelaxationPanel,...
                    'Style','PushButton',...
                    'String','Convert',...
                    'Units','normalized',...
                    'TooltipString',...
                    'Constant for converting vclist to vdlist using vc constant',...
                    'Position',[0.1 0.82 0.15 0.05],...
                    'Callback',{ @ButtonVCConvert_Callback});
                
                uicontrol(...
                    'Parent',hEditRelaxationPanel,...
                    'Style','text',...
                    'Units','Normalized',...
                    'FontWeight','bold',...
                    'horizontalalignment','l',...
                    'Position',[0.08 0.61 0.4 0.05 ],...
                    'String','For CPMG => 2*tau+p2');
                
                
                uicontrol(...
                    'Parent',hEditRelaxationPanel,...
                    'Style','text',...
                    'Units','Normalized',...
                    'FontWeight','bold',...
                    'horizontalalignment','l',...
                    'Position',[0.08 0.56 0.4 0.05 ],...
                    'String','For PROJECT => 4*tau+2*p2+p1');
                
            end
        end
        set(hEditDELTA,'string',num2str(NmrData.DELTA));
        set(hEditdelta,'string',num2str(NmrData.delta));
        set(hEditTau,'string',num2str(NmrData.tau));
        set(hEditDosygamma,'string',num2str(NmrData.gamma));
        set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
        set(hEditDELTAprime,'string',num2str(NmrData.DELTAprime));
        set(hEditNMRPanel,'Visible','On');
        set(hEditDOSYPanel,'Visible','On');
        set(hEditRelaxationPanel,'Visible','On');
        set(hEditfpmult,'string',num2str(NmrData.fpmult));
        set(hEditlrfid,'string',num2str(NmrData.lrfid));
        set(hEditLSspec,'string',num2str(NmrData.lsspec));
        if NmrData.linshift==1
            set(hDCLSSpecGroup,'SelectedObject',hDCSpecLinPPM)
            
        else
            set(hDCLSSpecGroup,'SelectedObject',hDCSpecConPPM)
        end
        
        if isfield(NmrData,'xlim_spec')==1 % MJS edited to work
            scale=NmrData.xlim_spec;
        set(hEditScaleUp,'string',num2str(scale(2)));
        set(hEditScaleDown,'string',num2str(scale(1)));
        else
            scale=[0 0];
            set(hEditScaleUp,'string',num2str(scale(2)));
        set(hEditScaleDown,'string',num2str(scale(1)));
        end
        
        
        if isempty(NmrData.dc)
            NmrData.dc=0;
        end
        switch NmrData.dc
            case 1
                set(hDCGroup,'SelectedObject',hDCYesPPM)
            case 0
                set(hDCGroup,'SelectedObject',hDCNoPPM)
            otherwise
                error('illegal choice')
        end
        switch NmrData.dcspec
            case 1
                set(hDCSpecGroup,'SelectedObject',hDCSpecYesPPM)
            case 0
                set(hDCSpecGroup,'SelectedObject',hDCSpecNoPPM)
            otherwise
                error('illegal choice')
        end
        switch NmrData.FitType
            case 0
                set(hFittypeGroup,'SelectedObject',hFittypeLsq)
            case 1
                set(hFittypeGroup,'SelectedObject',hFittypeFmin)
            otherwise
                error('illegal choice')
        end
        switch NmrData.shiftunits
            case 'ppm'
                set(hRadioPPM,'Value',1)
            case 'Hz'
                set(hRadioHz,'Value',1)
            otherwise
                error('illegal choice')
        end
        
        %set local data version
        if strcmp(NmrData.local,'yes')
            set(hButtonv500,'Visible','on');
            set(hButtonv400,'Visible','on');
            set(hTextMancs,'Visible','on');
        end
        guidata(hMainFigure,NmrData);
        function TableGzlvl_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            tmpgrad=get(hTableGzlvl,'Data');
            if sum(isnan(tmpgrad))
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only numeric values can be entered as gradient amplitudes')
            else
                NmrData.Gzlvl=tmpgrad';
            end
            set(hTableGzlvl,'Data',NmrData.Gzlvl')
            
            guidata(hMainFigure,NmrData);
            
        end
        function TableTau_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            tmpgrad=get(hTableTau,'Data');
            if sum(isnan(tmpgrad))
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only numeric values can be entered as delay times')
            else
                NmrData.d2=tmpgrad;
            end
            set(hTableTau,'Data',NmrData.d2)
            
            guidata(hMainFigure,NmrData);
            
        end
        function TableVclist_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            tmpgrad=get(hTableVclist,'Data');
            if sum(isnan(tmpgrad))
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only numeric values can be entered as counter ')
            else
                NmrData.vclist=round(tmpgrad)';
            end
            set(hTableVclist,'Data',NmrData.vclist')
            
            guidata(hMainFigure,NmrData);
            
        end
        function EditVCLIST_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.vc_constant=str2double(get(hEditVCLIST,'string'));
            set(hEditVCLIST,'string',num2str(NmrData.vc_constant));
            guidata(hMainFigure,NmrData);
        end
        function ButtonVCConvert_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.d2=NmrData.vclist.*NmrData.vc_constant;
            if iscolumn(NmrData.d2)
            else
                NmrData.d2=NmrData.d2';
            end
            guidata(hMainFigure,NmrData);
            set(hTableTau,'Data',NmrData.d2)
            
        end
        function ButtonVCRevert_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.d2=NmrData.d2_org;
            set(hTableTau,'Data',NmrData.d2_org)
            if isfield(NmrData,'vclist')
                NmrData.vclist=NmrData.vclist_org;
                set(hTableVclist,'Data',NmrData.vclist)
                NmrData.vc_constant=NmrData.vc_constant_org;
                set(hEditVCLIST,'string',num2str(NmrData.vc_constant));
            end
            
            guidata(hMainFigure,NmrData);
        end
        function Buttonv500_Callback( ~, ~)
            %Manchester Varian 500 MHz Triple probe
            NmrData=guidata(hMainFigure);
            NmrData.nug=[1 -0.024654 -0.000973 0.000114];
            NmrData.probename='v500';
            NmrData.gcal=0.001996;
            set(hTableNUG,'Data',{NmrData.probename; NmrData.gcal ;NmrData.nug(1) ;NmrData.nug(2) ;NmrData.nug(3) ;NmrData.nug(4) });
            guidata(hMainFigure,NmrData);
            
        end
        function Buttonv400_Callback( ~, ~)
            %Manchester Varian 400 MHz Triple probe
            NmrData=guidata(hMainFigure);
            NmrData.nug=[9.280636e-1 -9.789118e-3 -3.834212e-4 2.51367e-5];
            NmrData.probename='v400';
            NmrData.gcal=0.00101;
            set(hTableNUG,'Data',{NmrData.probename; NmrData.gcal ;NmrData.nug(1) ;NmrData.nug(2) ;NmrData.nug(3) ;NmrData.nug(4) });
            guidata(hMainFigure,NmrData);
            
        end
        function TableNUG_Callback( ~, ~)
            
            NmrData=guidata(hMainFigure);
            tmp=get(hTableNUG,'Data');
            NmrData.probename=tmp{1};
            NmrData.gcal=tmp{2};
            NmrData.nug(1)=tmp{3};
            NmrData.nug(2)=tmp{4};
            NmrData.nug(3)=tmp{5};
            NmrData.nug(4)=tmp{6};
            guidata(hMainFigure,NmrData);
            
            set(hTableNUG,'Data',{NmrData.probename; NmrData.gcal ;NmrData.nug(1) ;NmrData.nug(2) ;NmrData.nug(3) ;NmrData.nug(4) });
            guidata(hMainFigure,NmrData);
        end
        function ReadNUG_Callback( ~, ~)
            %Read in NUG data from file
            [FileName,PathName] =uigetfile('*.*','Choose the file containing nug data');
            nugfile=[PathName FileName];
            nugid=fopen(nugfile,'rt');
            nugline=fgetl(nugid);
            iter=1;
            while ischar(nugline)
                nugdata{iter}=nugline; %#ok<AGROW>
                nugline=fgetl(nugid);
                iter=iter+1;
            end
            if length(nugdata)>6
                guidata(hMainFigure,NmrData); WriteLogDispInfo('The number of lines in the file containing nug data are more than expected. ')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only the first 4 coefficients will be used')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Make sure that the format of the file is correct')
            elseif length(nugdata)<3
                guidata(hMainFigure,NmrData); WriteLogDispInfo('The number of lines in the file containing nug data are fewer than three.')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('At least three lines are necessary')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Make sure that the format of the file is correct')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Cannot use this file')
                return
            elseif length(nugdata)<4
                guidata(hMainFigure,NmrData); WriteLogDispInfo('The number of lines in the file containing nug data are fewer than four.')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only one nug coefficient is not useful - but I will allow it')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('The remaining coeficients will be set to zero')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Make sure that the format of the file is correct')
            elseif length(nugdata)<6
                guidata(hMainFigure,NmrData); WriteLogDispInfo('The number of lines in the file containing nug data are fewer than expected.')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('The remaining coeficients will be set to zero')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Make sure that the format of the file is correct')
            else
                %we assume that the file was fine
            end
            NmrData.probename=nugdata{1};
            NmrData.gcal=str2double(nugdata{2});
            NmrData.nug=[0 0 0 0];
            for iter=3:length(nugdata)
                NmrData.nug(iter-2)=str2double(nugdata{iter});
            end
            set(hTableNUG,'Data',{NmrData.probename; NmrData.gcal ;NmrData.nug(1) ;NmrData.nug(2) ;NmrData.nug(3) ;NmrData.nug(4) });
            guidata(hMainFigure,NmrData);
        end
        function ButtonMeth1_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            item = get(hGPNAMpopup,'Value'); % list entry
            list = get(hGPNAMpopup,'String'); % list of shapes
            gpnam = strtrim(list(item,:)); % retrieve shapes as string
            
            item2 = get(hPPpopup,'Value'); % list entry
            list2 = get(hPPpopup,'String'); % list of pulprog
            pulprog = strtrim(list2(item2,:)); % retrieve pulprog as string
            
            if contains(pulprog,'Oneshot')
                if contains(gpnam,'SINE')
                    NmrData.DELTAprime=NmrData.DELTA-((5-(3*NmrData.alpha*NmrData.alpha))*(NmrData.delta/16))-((1-(NmrData.alpha*NmrData.alpha))*(NmrData.tau/2));
                elseif contains(gpnam,'SMSQ')
                    NmrData.DELTAprime=NmrData.DELTA-((1-(NmrData.alpha*NmrData.alpha))*(NmrData.tau/2))...
                        -(((((3367*(pi^2))-207)*(NmrData.alpha*NmrData.alpha))+(((6344*(pi^2))-207)*(NmrData.delta)))/(19440*(pi^2)));
                elseif contains(gpnam,'RECT')
                    NmrData.DELTAprime=NmrData.DELTA-((2-(NmrData.alpha*NmrData.alpha))*(NmrData.delta/6))-((1-(NmrData.alpha*NmrData.alpha))*(NmrData.tau/2));
                else
                    NmrData.gpnam='SINE';
                    gpnam='SINE';
                    %set(hGPNAMpopup,'value',1);
                    NmrData.DELTAprime=NmrData.DELTA-((5-(3*NmrData.alpha*NmrData.alpha))*(NmrData.delta/16))-((1-(NmrData.alpha*NmrData.alpha))*(NmrData.tau/2));
                end
            elseif contains(pulprog,'Monopolar')
                if contains(gpnam,'SINE')
                    NmrData.DELTAprime=NmrData.DELTA-NmrData.delta/4;
                elseif contains(gpnam,'SMSQ')
                    NmrData.DELTAprime=NmrData.DELTA-((((1484*pi^2)-207)/(4860*pi^2))*NmrData.delta);
                elseif contains(gpnam,'RECT')
                    NmrData.DELTAprime=NmrData.DELTA-NmrData.delta/3;
                else
                     NmrData.gpnam='SINE';
                    %set(hGPNAMpopup,'value',1);
                    NmrData.DELTAprime=NmrData.DELTA-NmrData.delta/4;
                end
            elseif contains(pulprog,'Bipolar')
                if contains(gpnam,'SINE')
                    NmrData.DELTAprime=NmrData.DELTA-(5*NmrData.delta/16)-(NmrData.tau/2);
                elseif contains(gpnam,'SMSQ')
                    NmrData.DELTAprime=NmrData.DELTA-((((6344*pi^2)-207)/(19440*pi^2))*NmrData.delta)-(NmrData.tau/2);
                elseif contains(gpnam,'RECT')
                    NmrData.DELTAprime=NmrData.DELTA-(NmrData.delta/3)-(NmrData.tau/2);
                else
                    NmrData.gpnam='<SINE.100>';
                   % set(hGPNAMpopup,'value',1);
                    NmrData.DELTAprime=NmrData.DELTA-(5*NmrData.delta/16)-(NmrData.tau/2);
                end
            elseif contains(pulprog,'Double')
                if contains(gpnam,'SINE')
                    NmrData.DELTAprime=NmrData.DELTA-(5*NmrData.delta/8)-(NmrData.tau);
                elseif contains(gpnam,'SMSQ')
                    NmrData.DELTAprime=NmrData.DELTA-((((6344*pi^2)-207)/(9720*pi^2))*NmrData.delta)-(NmrData.tau);
                elseif contains(gpnam,'RECT')
                    NmrData.DELTAprime=NmrData.DELTA-(2*NmrData.delta/3)-(NmrData.tau);
                else
                     NmrData.gpnam='SINE';
                    %set(hGPNAMpopup,'value',1);
                    NmrData.DELTAprime=NmrData.DELTA-(5*NmrData.delta/16)-(NmrData.tau/2);
                end
            else
                error('Unknown diffusion parameters')
            end
            
            set(hEditDELTAprime,'string',num2str(NmrData.DELTAprime));
            NmrData.dosyconstant=NmrData.gamma.^2.*NmrData.delta.^2.*...
                NmrData.DELTAprime;
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            guidata(hMainFigure,NmrData);
            WriteLogDispInfo(['DOSY gradient shape is: ' gpnam ' and pulse sequence is ' pulprog])
        end
        function GPNAM_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            item = get(hGPNAMpopup,'Value'); % list entry
            list = get(hGPNAMpopup,'String'); % list of shapes
            gpnam = strtrim(list(item,:)); % retrieve shapes as string

            if contains(gpnam,'SINE')
                 NmrData.gpnam='SINE'; %##$SHAPE_INTEGFAC= 6.3656674E-01
            elseif contains(gpnam,'SMSQ')
                 NmrData.gpnam='SMSQ'; %##$SHAPE_INTEGFAC= 9.000000E-01
            elseif contains(gpnam,'RECT')
                 NmrData.gpnam='RECT'; %##$SHAPE_INTEGFAC= 10.000000E-01
            else
                NmrData.gpnam='SINE';
                %set(hGPNAMpopup,'value',1);
            end
            
            NmrData.DELTA=str2double(get(hEditDELTA,'string'));
            set(hEditDELTA,'string',num2str(NmrData.DELTA));
            NmrData.DELTAprime='Calculate';
            NmrData.dosyconstant='Calculate';
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            set(hEditDELTAprime,'string',NmrData.DELTAprime)
            
            guidata(hMainFigure,NmrData);
            WriteLogDispInfo(['DOSY gradient shape is: ' NmrData.gpnam])
        end
        function pulseprog_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            item2 = get(hPPpopup,'Value'); % list entry
            list2 = get(hPPpopup,'String'); % list of pulprog
            pulprog = strtrim(list2(item2,:)); % retrieve pulprog as string
            
            NmrData.DELTA=str2double(get(hEditDELTA,'string'));
            set(hEditDELTA,'string',num2str(NmrData.DELTA));
            NmrData.DELTAprime='Calculate';
            NmrData.dosyconstant='Calculate';
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            set(hEditDELTAprime,'string',NmrData.DELTAprime);
            
            guidata(hMainFigure,NmrData);
            WriteLogDispInfo(['Pulse sequence is: ' pulprog])
        end
        function ButtonRestore_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.dosyconstant=NmrData.dosyconstantOriginal;
            NmrData.DELTA=NmrData.DELTAOriginal;
            NmrData.delta=NmrData.deltaOriginal;
            NmrData.tau=NmrData.tauOriginal;
            NmrData.gamma=NmrData.gammaOriginal;
            NmrData.DELTAprime=NmrData.dosyconstant./...
                (NmrData.gamma.^2.*NmrData.delta.^2);
            %set(hPPpopup,'value',1);
            set(hEditDELTA,'string',num2str(NmrData.DELTA));
            set(hEditdelta,'string',num2str(NmrData.delta));
            set(hEditTau,'string',num2str(NmrData.tau));
            set(hEditDELTAprime,'string',num2str(NmrData.DELTAprime));
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            set(hEditDosygamma,'string',num2str(NmrData.gamma));
            guidata(hMainFigure,NmrData);
        end
        function EditDosyconstant_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.dosyconstant=str2double(get(hEditDosyconstant,'string'));
            NmrData.DELTAprime=NmrData.dosyconstant./...
                (NmrData.gamma.^2.*NmrData.delta.^2);
            guidata(hMainFigure,NmrData);
            set(hEditDELTAprime,'string',num2str(NmrData.DELTAprime));
            
        end
        function EditDELTAprime_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.DELTAprime=str2double(get(hEditDELTAprime,'string'));
            NmrData.dosyconstant=...
                NmrData.gamma.^2.*NmrData.delta.^2.*NmrData.DELTAprime;
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            guidata(hMainFigure,NmrData);
        end
        function EditDosygamma_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.gamma=str2double(get(hEditDosygamma,'string'));
            NmrData.dosyconstant=(NmrData.gamma.^2).*(NmrData.delta.^2).*NmrData.DELTAprime;
            guidata(hMainFigure,NmrData);
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            set(hEditDosygamma,'string',num2str(NmrData.gamma));
        end
        function EditDELTA_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.DELTA=str2double(get(hEditDELTA,'string'));
            set(hEditDELTA,'string',num2str(NmrData.DELTA));
            NmrData.DELTAprime='Calculate';
            NmrData.dosyconstant='Calculate';
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            set(hEditDELTAprime,'string',NmrData.DELTAprime);
            guidata(hMainFigure,NmrData);
        end
        function Editdelta_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.delta=str2double(get(hEditdelta,'string'));
            set(hEditdelta,'string',num2str(NmrData.delta));
            NmrData.DELTAprime='Calculate';
            NmrData.dosyconstant='Calculate';
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            set(hEditDELTAprime,'string',NmrData.DELTAprime);
            guidata(hMainFigure,NmrData);
        end
        function EditTau_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.tau=str2double(get(hEditTau,'string'));
            set(hEditTau,'string',num2str(NmrData.tau));
            NmrData.DELTAprime='Calculate';
            NmrData.dosyconstant='Calculate';
            set(hEditDosyconstant,'string',num2str(NmrData.dosyconstant));
            set(hEditDELTAprime,'string',NmrData.DELTAprime);
            guidata(hMainFigure,NmrData);
        end
        function hSettingsResizeFcn(varargin)
            % Figure resize callback
        end
        function hSettings_DeleteFcn(~, ~)
%             NmrData=guidata(hMainFigure);
%             
%             guidata(hMainFigure,NmrData);
        end
        function Editfpmult_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.fpmult=str2double(get(hEditfpmult,'string'));
            set(hEditfpmult,'string',num2str(NmrData.fpmult));
            guidata(hMainFigure,NmrData);
        end
        function Editlrfid_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.lrfid=round(str2double(get(hEditlrfid,'string')));
            set(hEditlrfid,'string',num2str(NmrData.lrfid));
            guidata(hMainFigure,NmrData);
        end
        function EditLSspec_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.lsspec=round(str2double(get(hEditLSspec,'string')));
            set(hEditLSspec,'string',num2str(NmrData.lsspec));
            guidata(hMainFigure,NmrData);
        end
        function DC_Callback( ~, ~)
            zoom off
            pan off
            switch get(hDCGroup,'SelectedObject')
                case hDCYesPPM
                    NmrData.dc=1;
                case hDCNoPPM
                    NmrData.dc=0;
                otherwise
                    error('illegal choice')
            end
            guidata(hMainFigure,NmrData);
        end
        function LSSpec_Callback(~, ~)
            if get(hDCLSSpecGroup,'SelectedObject')==hDCSpecLinPPM
                NmrData.linshift=1;
            else
                NmrData.linshift=0;
            end
            guidata(hMainFigure,NmrData);
        end
        function DCSpec_Callback( ~, ~)
            zoom off
            pan off
            switch get(hDCSpecGroup,'SelectedObject')
                case hDCSpecYesPPM
                    NmrData.dcspec=1;
                case hDCSpecNoPPM
                    NmrData.dcspec=0;
                otherwise
                    error('illegal choice')
            end
            guidata(hMainFigure,NmrData);
        end
        function Fittype_Callback( ~, ~)
            zoom off
            pan off
            switch get(hFittypeGroup,'SelectedObject')
                case hFittypeLsq
                    NmrData.FitType=0;
                case hFittypeFmin
                    NmrData.FitType=1;
                otherwise
                    error('illegal choice')
            end
            
            guidata(hMainFigure,NmrData);
        end
        guidata(hMainFigure,NmrData);
        set(hSettings,'Visible','On');
    end
%     function Edit_Macros( eventdata, handles)
%         NmrData=guidata(hMainFigure);
%         if isfield(NmrData,'hMacros')
%             if isvalid(NmrData.hMacros)
%                 close(NmrData.hMacros)
%             end
%         end
%         hMacros=figure(...
%             'NumberTitle','Off',...
%             'MenuBar','none',...
%             'Units','Normalized',...
%             'Visible','Off',...
%             'Toolbar','none',...
%             'Name','Settings');
%         NmrData.hMacros=hMacros;
%         hMacrosUiTabGroup=uitabgroup(...
%             'Parent',hMacros,...
%             'Position',[0.0 0.0 1.0 1.0],...
%             'Units','Normalized');
%         %hMacrosUiTab1=
%         uitab(...
%             'Parent',hMacrosUiTabGroup,...
%             'Title','One',...
%             'Units','Normalized');
% %         hMacrosUiTab2=uitab(...
% %             'Parent',hMacrosUiTabGroup,...
% %             'Title','Two',...
% %             'Units','Normalized');
% 
% 
%         guidata(hMainFigure,NmrData);
%         set(hMacros,'Visible','On');
%     end
    function Help_About(~,~)
        hHelpAbout=figure(...
            'NumberTitle','Off',...
            'MenuBar','none',...
            'Units','Normalized',...
            'Toolbar','none',...
            'Name','About');
        hHelpAboutPanel=uipanel(...
            'Parent',hHelpAbout,...
            'Title','Contact Details and License',...
            'FontWeight','bold',...
            'ForegroundColor','Blue',...
            'TitlePosition','centertop',...
            'Units','Normalized',...
            'Position',[0.0, 0.0 ,1.0, 1.0]);
        
        CellArrayString=cell(1,12);
        CellArrayString{1,1}=NmrData.version;
        CellArrayString{1,2}='2021';
        CellArrayString{1,3}='';
        CellArrayString{1,4}='A freeware programme for analysis of NMR data';
        CellArrayString{1,5}='Licenced under the GNU General Public License';
        CellArrayString{1,6}='Copyright (C) <2021>  <Mathias Nilsson>';
        CellArrayString{1,7}='';
        CellArrayString{1,8}='Mathias Nilsson ';
        CellArrayString{1,9}='School of Chemistry, University of Manchester';
        CellArrayString{1,10}='Oxford Road, Manchester M13 9PL, UK';
        CellArrayString{1,11}='mathias.nilsson@manchester.ac.uk';
        CellArrayString{1,12}='http://personalpages.manchester.ac.uk/staff/mathias.nilsson/';
        CellArrayString{1,13}='http://nmr.chemistry.manchester.ac.uk/';
        
        %hTextOnline=
        uicontrol(...
            'Parent',hHelpAboutPanel,...
            'Style','text',...
            'Units','Normalized',...
            'horizontalalignment','center',...
            'FontWeight','bold',...
            'Position',[0.1 0.1 0.8 0.7 ],...
            'String',CellArrayString);
        
        
    end
%----------------End of Menu callbacks-------------------------------------
%% ---------Common Callbacks
    function ThresholdButton_Callback( ~, ~)
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        set(hMainFigure,'WindowButtonDownFcn','')
        if  get(hThreshButton,'Value') == 1
            % Button pressed
            set(hAxes,'ButtonDownFcn',@Threshold_function);
            hThresh=findobj(hAxes,'tag','threshold');
            if isempty(hThresh)
                %do nothing
            else
                set(hThresh,'Visible','on');
            end
        elseif get(hThreshButton,'Value') == 0
            % Button up
            set(hAxes,'ButtonDownFcn','');
            hThresh=findobj(hAxes,'tag','threshold');
            if isempty(hThresh)
                %do nothing
            else
                set(hThresh,'Visible','off');
            end
            
        else
            warning('Cannot determing state of hThresButton')
        end
        guidata(hMainFigure,NmrData);
    end
%% ---------Plot Tab Callbacks
    function GroupZoomPan_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        zoom off
        pan off
        switch get(hZoomPanGroup,'SelectedObject')
            case hRadioZoom
                
            case hRadioPan
                
            otherwise
                error('illegal choice')
        end
        guidata(hMainFigure,NmrData);
    end
    function panXYButton_Callback(~,~)
        zoom off
        pan off
        switch get(hZoomPanGroup,'SelectedObject')
            case hRadioZoom
                zoom on
                ZoomObj=zoom(hMainFigure);
        set(ZoomObj,'ActionPostCallback', @zoomChanged);
            case hRadioPan
                pan on
                PanObj=pan(hMainFigure);
        set(PanObj,'ActionPostCallback', @zoomChanged);
            otherwise
                error('illegal choice')
        end
        
    end
    function panXButton_Callback(~,~)
        zoom off
        pan off
        switch get(hZoomPanGroup,'SelectedObject')
            case hRadioZoom
                zoom xon
                ZoomObj=zoom(hMainFigure);
                set(ZoomObj,'ActionPostCallback', @zoomChanged);
            case hRadioPan
                pan xon
                PanObj=pan(hMainFigure);
        set(PanObj,'ActionPostCallback', @zoomChanged);
            otherwise
                error('illegal choice')
        end
    end
    function panYButton_Callback(~,~)
        zoom off
        pan off
        switch get(hZoomPanGroup,'SelectedObject')
            case hRadioZoom
                zoom yon
            case hRadioPan
                pan yon
            otherwise
                error('illegal choice')
        end
    end
    function panOffButton_Callback(~,~)
        pan off
        zoom off
    end
    function GroupAbsPhase_Callback(~,~)
        % Display the data in absolute value mode.
        pan off
        zoom off
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
            NmrData.ylim_fid=ylim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        else
            error('Illegal plot type')
        end
        switch get(hAbsPhaseGroup,'SelectedObject')
            case hRadioPhase
                NmrData.disptype=1;
            case hRadioAbs
                NmrData.disptype=0;
            otherwise
                error('illegal choice')
        end
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        NmrData.xlim_fid=xlim(hAxes);
        NmrData.ylim_fid=ylim(hAxes);
        guidata(hMainFigure,NmrData);
        
        
    end
    function ButtonPlotCurrent_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
            NmrData.ylim_fid=ylim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        else
            error('Illegal plot type')
        end
        NmrData.plotsep=1;
        NmrData.plotpub=0;
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        NmrData.plotsep=0;
        guidata(hMainFigure,NmrData);
    end
    function ButtonPlotCurrentPubl_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
            NmrData.ylim_fid=ylim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        else
            error('Illegal plot type')
        end
        NmrData.plotsep=1;
        NmrData.plotpub=1;
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        NmrData.plotsep=0;
        guidata(hMainFigure,NmrData);
    end
    function ButtonPlotCloseall_Callback(~,~)
        NmrData=guidata(hMainFigure);
            delete(setdiff(findall(0, 'type', 'figure'), hMainFigure));
        guidata(hMainFigure,NmrData);
    end

    function ButtonFid_Callback(~,~)
        % Display the Fid.
        NmrData=guidata(hMainFigure);
        pan off
        zoom off
        switch get(hButtonFid,'value')
            case 1
                NmrData.plottype=0; %FID
                set(hPlotFID,'Enable','on');
                set(hPlotWinfunc,'Enable','on');
                set(hPlotFIDWinfunc,'Enable','on');
                NmrData.xlim_spec=xlim(hAxes);
                NmrData.ylim_spec=ylim(hAxes);
                guidata(hMainFigure,NmrData);
                PlotSpectrum();
                NmrData.xlim_fid=xlim(hAxes);
                NmrData.ylim_fid=ylim(hAxes);
                guidata(hMainFigure,NmrData);
                set(hButtonSpec,'value',0)
                
            case 0
                
                
            otherwise
        end
        guidata(hMainFigure,NmrData);
    end
    function ButtonSpec_Callback(~,~)
        % Display the spectrum.
        
        NmrData=guidata(hMainFigure);
        pan off
        zoom off
        get(hButtonFid,'value')
        switch get(hButtonSpec,'value')
            case 1
                NmrData.plottype=1; %FID
                set(hPlotFID,'Enable','off');
                set(hPlotWinfunc,'Enable','off');
                set(hPlotFIDWinfunc,'Enable','off')
                NmrData.xlim_fid=xlim(hAxes);
                NmrData.ylim_fid=ylim(hAxes);
                guidata(hMainFigure,NmrData);
                PlotSpectrum();
                NmrData.xlim_spec=xlim(hAxes);
                NmrData.ylim_spec=ylim(hAxes);
                guidata(hMainFigure,NmrData);
                set(hButtonFid,'value',0)
                
            case 0
                
                
            otherwise
        end
    end
    function ButtonMult2_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
        else
            error('Illegal plot type')
        end
        
        ylim(ylim()/2);
        if NmrData.plottype==0
            NmrData.ylim_fid=ylim();
        elseif NmrData.plottype==1
            NmrData.ylim_spec=ylim();
        else
            error('Illegal plot type')
        end
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        
    end
    function ButtonMult11_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
        else
            error('Illegal plot type')
        end
        
        ylim(ylim()/1.1);
        if NmrData.plottype==0
            NmrData.ylim_fid=ylim();
        elseif NmrData.plottype==1
            NmrData.ylim_spec=ylim();
        else
            error('Illegal plot type')
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        
    end
    function ButtonDiv2_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
        else
            error('Illegal plot type')
        end
        
        ylim(ylim()*2);
        if NmrData.plottype==0
            NmrData.ylim_fid=ylim();
        elseif NmrData.plottype==1
            NmrData.ylim_spec=ylim();
        else
            error('Illegal plot type')
        end
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonDiv11_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
        else
            error('Illegal plot type')
        end
        
        ylim(ylim()*1.1);
        if NmrData.plottype==0
            NmrData.ylim_fid=ylim();
        elseif NmrData.plottype==1
            NmrData.ylim_spec=ylim();
        else
            error('Illegal plot type')
        end
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonAutoscale_Callback(~,~)
        %Autoscale the spectrum.
        NmrData=guidata(hMainFigure);
        if get(hIntegralsShow,'Value')
            NmrData.Intscale=1;
            guidata(hMainFigure,NmrData);
            DrawIntLine();
        else
            set(hBaselineShow,'Value',0);
            ylim('auto');
            yax=ylim();
            yax(1)=yax(1)-yax(2)*0.1;
            yax(2)=yax(2)*1.1;
            if NmrData.plottype==0
                NmrData.xlim_fid=xlim(hAxes);
                NmrData.ylim_fid=yax;
            elseif NmrData.plottype==1
                NmrData.xlim_spec=xlim(hAxes);
                NmrData.ylim_spec=yax;
            else
                error('Illegal plot type')
            end
            guidata(hMainFigure,NmrData);
            PlotSpectrum()
        end
        set(hEditScaleUp,'string',num2str(NmrData.xlim_spec(2)));
        set(hEditScaleDown,'string',num2str(NmrData.xlim_spec(1)));
    end
    function ButtonFull_Callback(~,~)
        %Display full FID/Spectrum
        
        axis('tight')
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
        else
            error('Illegal plot type')
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum()
        set(hEditScaleUp,'string',num2str(NmrData.xlim_spec(2)));
        set(hEditScaleDown,'string',num2str(NmrData.xlim_spec(1)));
    end
    function EditScaleUp_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        scaleup=str2double(get(hEditScaleUp,'string'));
        if isnan(scaleup>0)
        elseif scaleup<NmrData.xlim_spec(1)
            set(hEditScaleDown,'string',num2str(scaleup));
            set(hEditScaleUp,'string',num2str(NmrData.xlim_spec(1)));
            set(hAxes,'Xlim',[scaleup NmrData.xlim_spec(1)]);
            NmrData.xlim_spec=[scaleup NmrData.xlim_spec(1)];
         
        else
            set(hEditScaleUp,'string',num2str(scaleup));
            set(hAxes,'Xlim',[NmrData.xlim_spec(1) scaleup]);
            NmrData.xlim_spec=[NmrData.xlim_spec(1) scaleup];
            
        end
    
        guidata(hMainFigure,NmrData);
    end
    function EditScaleDown_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        scaledown=str2double(get(hEditScaleDown,'string'));
        
        if isnan(scaledown>0)
        elseif scaledown>NmrData.xlim_spec(2) 
            set(hEditScaleUp,'string',num2str(scaledown));
            set(hEditScaleDown,'string',num2str(NmrData.xlim_spec(2)));
            set(hAxes,'Xlim',[NmrData.xlim_spec(2) scaledown]);
            NmrData.xlim_spec=[NmrData.xlim_spec(2) scaledown];
            
        else
            set(hEditScaleDown,'string',num2str(scaledown));
            set(hAxes,'Xlim',[scaledown NmrData.xlim_spec(2)]);
            NmrData.xlim_spec=[scaledown NmrData.xlim_spec(2)];
            
        end
        guidata(hMainFigure,NmrData);
    end
    function zoomChanged(~,AxisStruct) % MJS added to update zoom fields
        scale = get(AxisStruct.Axes,'XLim'); 
        set(hEditScaleUp,'string',num2str(scale(2)));
        set(hEditScaleDown,'string',num2str(scale(1)))
    end
    function Units_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.xlim_spec=xlim(hAxes);
        guidata(hMainFigure,NmrData);
        switch get(hUnitsGroup,'SelectedObject')
            case hRadioPPM
                NmrData.shiftunits='ppm';
                NmrData.xlim_spec=NmrData.xlim_spec./NmrData.sfrq;
                NmrData.RDleft=NmrData.RDleft./NmrData.sfrq;
                NmrData.RDright=NmrData.RDright./NmrData.sfrq;
                NmrData.RDcentre=NmrData.RDcentre./NmrData.sfrq;
            case hRadioHz
                NmrData.shiftunits='Hz';
                NmrData.xlim_spec=NmrData.xlim_spec.*NmrData.sfrq;
                NmrData.RDleft=NmrData.RDleft.*NmrData.sfrq;
                NmrData.RDright=NmrData.RDright.*NmrData.sfrq;
                NmrData.RDcentre=NmrData.RDcentre.*NmrData.sfrq;
            otherwise
                error('illegal choice')
        end
        guidata(hMainFigure,NmrData);
        figure(hMainFigure)
        PlotSpectrum();
    end
%---------End of Plot Control Callbacks------------------------------------
%% ---------Phase Tab Callbacks
    function PivotButton_Callback( ~, ~)
        zoom off; pan off
        set(hPivotCheck,'Value',1)
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@Pivot_function)
    end
    function PivotCheck_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hPivotCheck,'Value');
        if button_state == 1
            Pivot_function();
        elseif button_state == 0
            hPivot=findobj(hAxes,'tag','Pivot');
            delete(hPivot);
            set(hAxes,'ButtonDownFcn','');
        end
    end
    function GtoIButton_Callback ( ~, ~)
        NmrData=guidata(hMainFigure);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                for k=1:NmrData.arraydim
                    NmrData.lpInd(k)=NmrData.lp;
                    NmrData.rpInd(k)=NmrData.rp;
                end
                
            case hRadioScopeIndividual
                guidata(hMainFigure,NmrData); WriteLogDispInfo('only works with global scope')
                
            otherwise
                error('illegal choice')
        end
        
        
        guidata(hMainFigure,NmrData);
        
    end
    function GroupScope_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal                
                PhaseSpectrum...
                    (0,0,20)
               % PhaseSpectrum(NmrData.lp,NmrData.rp,20)
                tmpflip=NmrData.flipnr;
                set(hScopeGroup,'SelectedObject',hRadioScopeGlobal)
                set(hPushCopyGtoI,'Enable','On')
                 set(hPushAutoAll,'Enable','Off')
                set(hPushAuto0All,'Enable','Off')
            case hRadioScopeIndividual
                PhaseSpectrum...
                    (0,0,20)
                tmpflip=NmrData.flipnr;
                set(hScopeGroup,'SelectedObject',hRadioScopeIndividual)
                set(hPushCopyGtoI,'Enable','Off')
                set(hPushAutoAll,'Enable','On')
                set(hPushAuto0All,'Enable','On')
            otherwise
                error('illegal choice')
        end
        NmrData.flipnr=tmpflip;
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function SliderPh0_Callback(~,~)
        %Phase the spectrum: zeroth order
        NmrData=guidata(hMainFigure);
        
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                rpChange=get(hSliderPh0,'value')-NmrData.rp;
                lpChange=get(hSliderPh1,'value')-NmrData.lp;
            case hRadioScopeIndividual
                rpChange=get(hSliderPh0,'value')-...
                    NmrData.rpInd(NmrData.flipnr);
                lpChange=get(hSliderPh1,'value')-...
                    NmrData.lpInd(NmrData.flipnr);
            otherwise
                error('illegal choice')
        end
        
        AbsPhase=0;
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
    end
    function EditPh0_Callback(~,~)
        NmrData=guidata(hMainFigure);
        AbsPhase=2;
        %get(hEditPh0,'value')
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                rpChange=str2double(get(hEditPh0,'String'))-NmrData.rp;
                lpChange=0;
            case hRadioScopeIndividual
                rpChange=str2double(get(hEditPh0,'String'))-NmrData.rpInd(NmrData.flipnr);
                lpChange=0;
            otherwise
                error('illegal choice')
        end
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
    end
    function SliderPh1_Callback(~,~)
        %Phase the spectrum: zeroth order
        NmrData=guidata(hMainFigure);
        AbsPhase=0;
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                rpChange=get(hSliderPh0,'value')-NmrData.rp;
                lpChange=get(hSliderPh1,'value')-NmrData.lp;
            case hRadioScopeIndividual
                rpChange=get(hSliderPh0,'value')-NmrData.rpInd(NmrData.flipnr);
                lpChange=get(hSliderPh1,'value')-NmrData.lpInd(NmrData.flipnr);
            otherwise
                error('illegal choice')
        end
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
        
    end
    function EditPh1_Callback(~,~)
        %Phase the spectrum: zeroth order
        NmrData=guidata(hMainFigure);
        AbsPhase=2;
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                rpChange=0;
                lpChange=str2double(get(hEditPh1,'String'))-NmrData.lp;
            case hRadioScopeIndividual
                rpChange=0;
                lpChange=str2double(get(hEditPh1,'String'))-NmrData.lpInd(NmrData.flipnr);
            otherwise
                error('illegal choice')
        end
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
    end
    function ButtonPlusPh0_Callback(~,~)
        %Phase the spectrum: zeroth order
        AbsPhase=0;
        rpChange=0.1;
        lpChange=0;
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
    end
    function ButtonMinusPh0_Callback(~,~)
        %Phase the spectrum: zeroth order
        AbsPhase=0;
        rpChange=-0.1;
        lpChange=0;
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
    end
    function ButtonPlusPh1_Callback(~,~)
        %Phase the spectrum: zeroth order
        AbsPhase=0;
        rpChange=0;
        lpChange=0.5;
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
    end
    function ButtonMinusPh1_Callback(~,~)
        AbsPhase=0;
        rpChange=0;
        lpChange=-0.5;
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        PlotSpectrum();
    end

%AUTOPHASE SHOULD BE MADE INTO 1 FUNCTION
    function ButtonAutophase_Callback(~,~)
        NmrData=guidata(hMainFigure);
        % cutting of edges of spectrum (often distorted)
        cut_perc=5;%ignore this % of spectrum each side
        
        spec=NmrData.SPECTRA(:,NmrData.flipnr);
        spec_cut=round(numel(spec)*cut_perc*0.01);
        spec(1:spec_cut)=0;
        spec(end-spec_cut:end)=0;        
        
        opts_fmin=optimset('fminsearch');
        opts_fmin=optimset(opts_fmin,'MaxFunEvals',100000);
        opts_fmin=optimset(opts_fmin,'TolX',1e-14);
        
        fac=fminsearch('mn_autophase',[NmrData.rp NmrData.lp ],opts_fmin,spec);
        lpChange=-fac(2);
        rpChange=-fac(1);
        AbsPhase=2;
        
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonAutophase0_Callback(~,~)
        NmrData=guidata(hMainFigure);
        % cutting of edges of spectrum (often distorted)
        cut_perc=5;%ignore this % of spectrum each side
        
        spec=NmrData.SPECTRA(:,NmrData.flipnr);
        spec_cut=round(numel(spec)*cut_perc*0.01);
        spec(1:spec_cut)=0;
        spec(end-spec_cut:end)=0;        
        
        opts_fmin=optimset('fminsearch');
        opts_fmin=optimset(opts_fmin,'MaxFunEvals',100000);
        opts_fmin=optimset(opts_fmin,'TolX',1e-14);
        
        fac=fminsearch('mn_autophase',[NmrData.rp],opts_fmin,spec);
        lpChange=0;
        rpChange=-fac(1);
        AbsPhase=2;
        
        PhaseSpectrum(lpChange,rpChange,AbsPhase);
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end

    function ButtonAutophase0All_Callback(~,~)
        NmrData=guidata(hMainFigure);
        flip_tmp=NmrData.flipnr;

        for k_flip=1:NmrData.arraydim
            % cutting of edges of spectrum (often distorted)
            set(hEditFlipSpec,'String',num2str(k_flip))
            guidata(hMainFigure,NmrData);
            EditFlipSpec_Callback()
            NmrData=guidata(hMainFigure);

            cut_perc=5;%ignore this % of spectrum each side
            spec=NmrData.SPECTRA(:,NmrData.flipnr);
            spec_cut=round(numel(spec)*cut_perc*0.01);
            spec(1:spec_cut)=0;
            spec(end-spec_cut:end)=0;

            opts_fmin=optimset('fminsearch');
            opts_fmin=optimset(opts_fmin,'MaxFunEvals',100000);
            opts_fmin=optimset(opts_fmin,'TolX',1e-14);

            fac=fminsearch('mn_autophase',[NmrData.rp],opts_fmin,spec);

            lpChange=0;
            rpChange=-fac(1);
            AbsPhase=2;

            PhaseSpectrum(lpChange,rpChange,AbsPhase);
            guidata(hMainFigure,NmrData);
        end
        set(hEditFlipSpec,'String',num2str(flip_tmp))
        guidata(hMainFigure,NmrData);
        EditFlipSpec_Callback();

    end
    function ButtonAutophaseAll_Callback(~,~)
        NmrData=guidata(hMainFigure);
        flip_tmp=NmrData.flipnr;

        for k_flip=1:NmrData.arraydim
            % cutting of edges of spectrum (often distorted)
            set(hEditFlipSpec,'String',num2str(k_flip))
            guidata(hMainFigure,NmrData);
            EditFlipSpec_Callback()
            NmrData=guidata(hMainFigure);

            cut_perc=5;%ignore this % of spectrum each side
            spec=NmrData.SPECTRA(:,NmrData.flipnr);
            spec_cut=round(numel(spec)*cut_perc*0.01);
            spec(1:spec_cut)=0;
            spec(end-spec_cut:end)=0;

            opts_fmin=optimset('fminsearch');
            opts_fmin=optimset(opts_fmin,'MaxFunEvals',100000);
            opts_fmin=optimset(opts_fmin,'TolX',1e-14);

            fac=fminsearch('mn_autophase',[NmrData.rp NmrData.lp ],opts_fmin,spec);
            lpChange=-fac(2);
            rpChange=-fac(1);
            AbsPhase=2;

            PhaseSpectrum(lpChange,rpChange,AbsPhase);
            guidata(hMainFigure,NmrData);
        end
        set(hEditFlipSpec,'String',num2str(flip_tmp))
        guidata(hMainFigure,NmrData);
        EditFlipSpec_Callback();


    end






%----------End of Phase panel Callbacks------------------------------------
%% ---------FT Tab Callbacks
    function FTButton_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hIntegralsShow,'Value',0)
        set(hBaselineShow,'Value',0)
        set(hExcludeShow,'Value',0)
        set(hLRWindowsShow,'Value',0)
        set(hPivotCheck,'Value',0)
        set(hReferenceCheck,'Value',0)
        set(hRDshowLRCheck,'Value',0)
        set(hRDshowCheck,'Value',0)
        set(hButtonFid,'value',0)
        set(hButtonSpec,'value',1)
        
        NmrData.fn=round(str2double(get(hEditFn,'string')));
        guidata(hMainFigure,NmrData);
        Winfunc=GetWinfunc('FTButton_Callback');
        NmrData=guidata(hMainFigure);
        if  get(hThreshButton,'Value') == 1
            hThresh=findobj(hAxes,'tag','threshold');
            if isempty(hThresh)
                %do nothing
            else
                set(hThresh,'Visible','on');
            end
        end
        
        %         hThresh=findobj(hAxes,'tag','threshold');
        %         delete(hThresh)
        hPivot=findobj(hAxes,'tag','Pivot');
        delete(hPivot)
        % Chemical shift frequency axis
        NmrData.SPECTRA=zeros(NmrData.fn,NmrData.ngrad);
        %keep the origial FID
        orgfid = NmrData.FID;
                
        %Apply frequency shift if desired
        if get(hCheckApplyFT,'Value')

            guidata(hMainFigure,NmrData); WriteLogDispInfo('Applying frequency shifts (alignment)')
            fshift=NmrData.fshift;
            if get(hCheckApplyLinear,'Value')
                linStep=str2double(get(hEditLinear,'String'))./NmrData.sfrq;
                linarray=linspace(0,linStep*(NmrData.arraydim-1),NmrData.arraydim);
                fshift=fshift+linarray;
            end
            Timescale=linspace(0,NmrData.at,NmrData.np)';
            tmpfid=NmrData.FID;
            for k=1:NmrData.arraydim
                tmp=exp(1i.*fshift(k)*2*pi.*Timescale);
                tmp=circshift(tmp,NmrData.lrfid);
                tmpfid(:,k)= tmpfid(:,k).*tmp;
                %tmpfid(:,k)= tmpfid(:,k).*exp(1i.*fshift(k)*2*pi.*Timescale);
                %  NmrData.FID(:,k)= NmrData.FID(:,k).*exp(1i.*fshift(k)*2*pi.*Timescale);
            end
            NmrData.FID=tmpfid;
        end
        
        if get(hReferenceFIDCheck,'value') == 1 && ~isempty(NmrData.reference_list)
            % Taking the chemical shift reference
            if get(hReferenceFIDCheck,'value') == 1 && get(hReferenceAutoCheck,'value') == 0
                DeltaShift = (NmrData.new_ref-NmrData.reference_list(NmrData.flipnr));
                DeltaShift = DeltaShift*NmrData.sfrq;

                wholeFID = orgfid(:,NmrData.flipnr);
                % t=linspace(0,0.5*(NmrData.fn/NmrData.np)*NmrData.at,NmrData.fn);
                t=linspace(0,NmrData.at,size(wholeFID,1));
                exponential = exp(1i * 2 * pi * DeltaShift * t);  
                % Appling the exponential to the FID
                fid_shifted = wholeFID .* exponential';
                % fid_shifted(1,:) = fid_shifted(1,:).*NmrData.fpmult;
                NmrData.FID(:,NmrData.flipnr)=fid_shifted;              
            elseif get(hReferenceFIDCheck,'value') == 1 && get(hReferenceAutoCheck,'value') == 1
                for ii = 1:size(NmrData.reference_list,1)
                    DeltaShift = (NmrData.new_ref-NmrData.reference_list(ii));
                    DeltaShift = DeltaShift*NmrData.sfrq;
                    % Correcting reference signal in TIME domaing

                    wholeFID = orgfid(:,ii);
                    t=linspace(0,NmrData.at,NmrData.np);
                    exponential = exp(1i * 2 * pi * DeltaShift * t);  
                    % Appling the exponential to the FID
                    fid_shifted = wholeFID .* exponential';
                    fid_shifted(1,:) = fid_shifted(1,:).*NmrData.fpmult;
                    NmrData.FID(:,ii)=fid_shifted;
                end
            end
        end 
        
        %leftshift the fid
        if NmrData.lrfid>0
            %left shift the fid
            for k=1:NmrData.arraydim
                NmrData.FID(:,k)= circshift(NmrData.FID(:,k),-NmrData.lrfid);
            end
        end
        
        %DC correction
        tmpfid=zeros(NmrData.fn,NmrData.arraydim);
        dcpoints=round(5*NmrData.np/20);
        for k=1:NmrData.arraydim
            if NmrData.fn>=NmrData.np
                if NmrData.dc
                    tmpfid(1:NmrData.np,k)=NmrData.FID(1:NmrData.np,k) - mean(orgfid(dcpoints:end,k));
                else
                    tmpfid(1:NmrData.np,k)=NmrData.FID(1:NmrData.np,k);
                end
            else
                if NmrData.dc
                    tmpfid(1:NmrData.fn,k)=NmrData.FID(1:NmrData.fn,k) - mean(orgfid(dcpoints:end,k));
                else
                    tmpfid(1:NmrData.fn,k)=NmrData.FID(1:NmrData.fn,k);
                end
            end
            
        end
        
        %remove shifted points before any zerofilling

        if NmrData.fn>=NmrData.np         
            if abs(NmrData.lrfid)>0
               tmpfid((NmrData.np-NmrData.lrfid+1):NmrData.np,:)=0; 
            end
            NmrData.FID=zeros(NmrData.fn,NmrData.arraydim);
            NmrData.FID(:,:)=tmpfid.*repmat(Winfunc,1,NmrData.arraydim);
        else
            NmrData.FID=tmpfid.*repmat(Winfunc,1,NmrData.arraydim);
            % NmrData.FID((NmrData.fn+1):end,:)=[];
        end
        
        NmrData.FID(1,:)=NmrData.FID(1,:).*NmrData.fpmult;
        NmrData.SPECTRA=fft(NmrData.FID);
        %NmrData.SPECTRA=fft(NmrData.FID,NmrData.fn);
        NmrData.FID=orgfid;
        NmrData.SPECTRA=flipud((fftshift(NmrData.SPECTRA,1)));
        %         Baseline_function();
        %         IntLine_function();
         
        guidata(hMainFigure,NmrData);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                PhaseSpectrum(NmrData.lp,NmrData.rp,1)
            case hRadioScopeIndividual
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Using individual phases for arrayed spectra')
                PhaseSpectrum(0,0,10)                
                guidata(hMainFigure,NmrData);
            otherwise
                error('illegal choice')
        end
        
        NmrData.plottype=1;
        NmrData.isuf=1; %temporary modification. UFNMR import will not work with this modification 

        if NmrData.isuf==1
            NmrData.SPECTRA=NmrData.SPECTRA;
        else       
            if NmrData.dcspec
                dcpoints=round(2*NmrData.fn/20);
                for k=1:NmrData.arraydim
                    NmrData.SPECTRA(:,k)=NmrData.SPECTRA(:,k)-mean(NmrData.SPECTRA([round(dcpoints/10):dcpoints end-dcpoints:end-round(dcpoints/10)],k));
                end
            end
        end

        for k=1:NmrData.arraydim        
            NmrData.SPECTRA(:,k)=circshift(NmrData.SPECTRA(:,k), NmrData.lsspec + NmrData.linshift*NmrData.lsspec*(k-1));
        end

        guidata(hMainFigure,NmrData);
        PlotSpectrum();
   end
    function EditFn_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        %NmrData.fn=round(str2double(get(hEditFn,'string')));
        fn=round(str2double(get(hEditFn,'string')));
        if isnan(NmrData.fn)
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Illegal fourier number - defaulting to np')
            fn=NmrData.np;
        end
        %set(hEditFn,'String',num2str(NmrData.fn))
        set(hEditFn,'String',num2str(fn))
        guidata(hMainFigure,NmrData);
    end
    function FnButtonPlus_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        %         NmrData.fn=2^nextpow2(NmrData.fn+1);
        %         set(hEditFn,'string',num2str(NmrData.fn))
        fn=round(str2double(get(hEditFn,'string')));
        fn=2^nextpow2(fn+1);
        set(hEditFn,'string',num2str(fn))
        guidata(hMainFigure,NmrData);
    end
    function FnButtonMinus_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        %         NmrData.fn=2^nextpow2(NmrData.fn/2);
        %         set(hEditFn,'string',num2str(NmrData.fn))
        fn=round(str2double(get(hEditFn,'string')));
        fn=2^nextpow2(fn/2);
        set(hEditFn,'string',num2str(fn))
        guidata(hMainFigure,NmrData);
    end
    function EditLb_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        NmrData.lb=(str2double(get(hEditLb,'string')));
        guidata(hMainFigure,NmrData);
        if NmrData.plottype==0
            %ButtonFid_Callback();
            PlotSpectrum();
        end
        %ButtonFid_Callback();
    end
    function CheckLb_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        if get(hCheckLb,'Value')
            set(hEditLb,'Enable','On')
            NmrData.lb=str2double(get(hEditLb,'string'));
        else
            set(hEditLb,'Enable','Off')
        end
        
        guidata(hMainFigure,NmrData);
        if NmrData.plottype==0
            %ButtonFid_Callback();
            PlotSpectrum();
        end
    end
    function EditGw_Callback(~, ~)
        NmrData=guidata(hMainFigure);
%         gwtmp=NmrData.gw;
         NmrData.gw=(str2double(get(hEditGw,'string')));
%         if NmrData.gw==0
%             errordlg('gw = 0 is illegal','gw error')
%             NmrData.gw=gwtmp;
%             set(hEditGw,'String',num2str(gwtmp))
%         end
        
        guidata(hMainFigure,NmrData);
        if NmrData.plottype==0
            %ButtonFid_Callback();
            PlotSpectrum();
        end
        %ButtonFid_Callback();
    end
    function CheckGw_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        if get(hCheckGw,'Value')
            set(hEditGw,'Enable','On')
            NmrData.gw=(str2double(get(hEditGw,'string')));
        else
            set(hEditGw,'Enable','Off')
        end
                guidata(hMainFigure,NmrData);

        if NmrData.plottype==0
            %ButtonFid_Callback();
            PlotSpectrum();
        end
    end
    function PlotFID_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hPlotFID,'Value');
        if button_state == 1
            
        elseif button_state == 0
            
        end
        if NmrData.plottype==0
            %ButtonFid_Callback();
            PlotSpectrum();
        end
    end
    function PlotWinfunc_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hPlotWinfunc,'Value');
        if button_state == 1
            
        elseif button_state == 0
            
        end
        if NmrData.plottype==0
            % ButtonFid_Callback();
            PlotSpectrum();
        end
    end
    function PlotFIDWinfunc_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hPlotFIDWinfunc,'Value');
        if button_state == 1
            
        elseif button_state == 0
            
        end
        if NmrData.plottype==0
            %ButtonFid_Callback();
            PlotSpectrum();
        end
    end
%Reference
    function ReferenceButton_Callback( ~, ~)
        zoom off
        pan off
        set(hReferenceCheck,'Value',1)
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@Reference_function)
    end
    function FindButton_Callback( ~, ~)
        set(hMainFigure,'WindowButtonDownFcn','')
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        switch NmrData.shiftunits
            case 'ppm'
                startunit='ppm';
            case 'Hz'
                NmrData.shiftunits='ppm';
                NmrData.xlim_spec=NmrData.xlim_spec./NmrData.sfrq;
                NmrData.reference=NmrData.reference./NmrData.sfrq;
                startunit='Hz';
            otherwise
                error('illegal choice')
        end
        
        hReference=findobj(hAxes,'tag','Reference');
        delete(hReference)

        % HSR modification for reference diff. spectrum 
        % Checking the active area of the spectrum
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end

        NmrData.pfgnmrdata=PreparePfgnmrdata();
        pfgnmrdata=NmrData.pfgnmrdata;
        for k=1:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>speclim(1))
                begin=k-1;
                k1=begin;
                break;
            end
        end
        for k=begin:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>=speclim(2))
                endrange=k;
                break;
            end
        end

        tempspec=real(NmrData.SPECTRA(:,NmrData.flipnr));
        tempspec([1:k1 endrange:end],:)=tempspec([1:k1 endrange:end],:).*0.0;

        % Calculate the baseline as the median intensity of the spectrum
        baseline = median(tempspec);

        % Find the global maximum and minimum peaks and their indices
        [maxPeak, maxIdx] = max(tempspec);  % Maximum peak and its index
        [minPeak, minIdx] = min(tempspec);  % Minimum peak and its index

        % Calculate the absolute distances of the peaks from the baseline
        distMax = abs(maxPeak - baseline);
        distMin = abs(minPeak - baseline);

        % Determine which peak is farthest from the baseline and return its ppm position
        if distMax > distMin
            % Return the ppm of the maximum peak
            maxpoint=maxIdx/NmrData.fn;
            maxpoint=maxpoint*NmrData.sw;
            maxpoint=maxpoint + NmrData.sp;
            NmrData.reference=maxpoint;
        else
            % Return the ppm of the minimum peak // This is necessary for
            % PARAFAC datasets when the reference signal is negative
            minpoint=minIdx/NmrData.fn;
            minpoint=minpoint*NmrData.sw;
            minpoint=minpoint + NmrData.sp;
            NmrData.reference=minpoint;
        end

        switch startunit
            case 'ppm'
                %all fine
            case 'Hz'
                NmrData.shiftunits='Hz';
                NmrData.xlim_spec=NmrData.xlim_spec.*NmrData.sfrq;
                NmrData.reference=NmrData.reference.*NmrData.sfrq;
            otherwise
                error('illegal choice')
        end
        NmrData.referencexdata=[NmrData.reference NmrData.reference];
        NmrData.referenceydata=get(hAxes,'ylim');
        line(NmrData.referencexdata,NmrData.referenceydata,...
            'color','magenta','linewidth', 1.0,...
            'tag','Reference');
        drawnow
        set(hReferenceCheck,'Value',1)
        set(hAxes,'ButtonDownFcn',@Reference_function)
        set(hChangeEdit,'string',num2str(NmrData.reference,'%1.3f'));
        guidata(hMainFigure,NmrData);
        
    end
    function ChangeButton_Callback( ~, ~)
        set(hMainFigure,'WindowButtonDownFcn','')
        %Reference the spectrum
        NmrData=guidata(hMainFigure);
        zoom off
        pan off
        set(hReferenceCheck,'Value',1)
        set(hAxes,'ButtonDownFcn',@Reference_function)
        % Creating NmrData.reference_list points
        NmrData.reference_list = zeros(NmrData.arraydim,1);
        new_ref=inputdlg('Enter the new reference value (ppm)','Reference',1,{'0'});
        new_ref=str2double(new_ref);
        if isempty(new_ref)
            return
        end

        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end

        NmrData.pfgnmrdata=PreparePfgnmrdata();
        pfgnmrdata=NmrData.pfgnmrdata;
        for k=1:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>speclim(1))
                begin=k-1;
                k1=begin;
                break;
            end
        end
        for k=begin:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>=speclim(2))
                endrange=k;
                break;
            end
        end

        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        NmrData.new_ref=new_ref;
        NmrData.referencexdata=[NmrData.reference NmrData.reference];
        NmrData.referenceydata=get(hAxes,'ylim');
        set(hChangeEdit,'string',num2str(NmrData.reference,'%1.3f'));
        guidata(hMainFigure,NmrData);
        
        % HSR modification for spectram with chemical shift problems in the
        % reference signal 21/03/25
        if get(hReferenceFIDCheck,'value') == 0
            NmrData.sp=NmrData.sp-(NmrData.reference-new_ref);
            NmrData.Specscale=linspace...
                (NmrData.sp,...
                (NmrData.sw+NmrData.sp),...
                NmrData.fn);
            NmrData.xlim_spec=xlim(hAxes)-(NmrData.reference-new_ref);
            NmrData.ylim_spec=ylim(hAxes);
            NmrData.reference=new_ref;
            NmrData.referencexdata=[NmrData.reference NmrData.reference];
            NmrData.referenceydata=get(hAxes,'ylim');
            set(hChangeEdit,'string',num2str(NmrData.reference,'%1.3f'));
            guidata(hMainFigure,NmrData);
            PlotSpectrum();
        elseif get(hReferenceFIDCheck,'value') == 1 && get(hReferenceAutoCheck,'value') == 0
            NmrData.reference_list(NmrData.flipnr)=NmrData.reference;
            FTButton_Callback()
        elseif get(hReferenceFIDCheck,'value') == 1 && get(hReferenceAutoCheck,'value') == 1

            hp=waitbar(0,'Correcting frequencies');   
            for ii= 1:NmrData.arraydim
                waitbar(ii/(NmrData.arraydim));
                NmrData.flipnr = ii;
                NmrData.xlim_spec=xlim(hAxes);
                NmrData.ylim_spec=ylim(hAxes);
                set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
                set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))

                % axes(hAxes);
                % EditFlipSpec_Callback();
                % FindButton_Callback();

                tempspec=real(NmrData.SPECTRA(:,NmrData.flipnr));
                tempspec([1:k1 endrange:end],:)=tempspec([1:k1 endrange:end],:).*0.0;

                % Calculate the baseline as the median intensity of the spectrum
                baseline = median(tempspec);

                % Find the global maximum and minimum peaks and their indices
                [maxPeak, maxIdx] = max(tempspec);  % Maximum peak and its index
                [minPeak, minIdx] = min(tempspec);  % Minimum peak and its index

                % Calculate the absolute distances of the peaks from the baseline
                distMax = abs(maxPeak - baseline);
                distMin = abs(minPeak - baseline);

                % Determine which peak is farthest from the baseline and return its ppm position
                if distMax > distMin
                    % Return the ppm of the maximum peak
                    maxpoint=maxIdx/NmrData.fn;
                    maxpoint=maxpoint*NmrData.sw;
                    maxpoint=maxpoint + NmrData.sp;
                    NmrData.reference_list(ii)=maxpoint;
                else
                    % Return the ppm of the minimum peak // This is necessary for
                    % PARAFAC datasets when the reference signal is negative
                    minpoint=minIdx/NmrData.fn;
                    minpoint=minpoint*NmrData.sw;
                    minpoint=minpoint + NmrData.sp;
                    NmrData.reference_list(ii)=minpoint;
                end

                NmrData.referencexdata=[NmrData.reference_list(ii) NmrData.reference_list(ii)];
                NmrData.referenceydata=get(hAxes,'ylim');
                line(NmrData.referencexdata,NmrData.referenceydata,...
                    'color','magenta','linewidth', 1.0,...
                    'tag','Reference');
                drawnow

                guidata(hMainFigure,NmrData);                
            end
            close(hp)
            FTButton_Callback()
            % axes(hAxes);
            % PlotSpectrum();

        end
    end
    function ReferenceCheck_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        set(hMainFigure,'WindowButtonDownFcn','')
        if get(hReferenceCheck,'Value')
            % Toggle button is pressed-take approperiate action
            line(NmrData.referencexdata,NmrData.referenceydata,...
                'color','magenta','linewidth', 1.0,...
                'tag','Reference');
            set(hAxes,'ButtonDownFcn',@Reference_function)
            set(hChangeEdit,'string',num2str(NmrData.reference,'%1.3f'));
            drawnow
        else
            % Toggle button is not pressed-take appropriate action
            hReference=findobj(hAxes,'tag','Reference');
            delete(hReference)
            hText=findobj(hAxes,'tag','shapetext');
            delete(hText);
            set(hChangeEdit,'string','');
            set(hAxes,'ButtonDownFcn','')
        end
        guidata(hMainFigure,NmrData);
    end
%% ---------Correct Tab Callbacks
%Baseline correction
    function BaselineShow_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hBaselineShow,'Value');
        if button_state == 1
            Baseline_function();
        elseif button_state == 0
            hBaseline=findobj(hAxes,'tag','baseline');
            delete(hBaseline)  %
        end
        %PlotSpectrum();
    end
    function AutoBaselineButton_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        zoom off
        pan off
        
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        pass_data.caller=1; %baseline
        Auto_Baseline_function(pass_data);
        guidata(hMainFigure,NmrData);
        %PlotSpectrum();
        
    end
    function SetRegionsButton_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn',@Baseline_function)
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        set(hBaselineShow,'Value',1)
        hBaseline=findobj(hAxes,'tag','baseline');
        delete(hBaseline)
        Baseline_function();
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        
    end
    function ClearRegionsButton_Callback( ~, ~)
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        NmrData.BasePoints=[];
        NmrData.baselinepoints=[];
        NmrData.region=ones(1,NmrData.fn);
        set(hMainFigure,'WindowButtonDownFcn',@Baseline_function)
        hBaseline=findobj(hAxes,'tag','baseline');
        delete(hBaseline)  %
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function BaselineCorrectButton_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        %NmrData.baselinecorr=zeros(NmrData.fn,NmrData.ngrad);
        NmrData.baselinecorr=zeros(NmrData.fn,NmrData.arraydim);
        if ~isempty(NmrData.baselinepoints)
            for k=1:NmrData.arraydim
                basefit=polyfit(NmrData.Specscale(isnan(NmrData.region))'...
                    ,NmrData.SPECTRA(isnan(NmrData.region),k),NmrData.order);
                NmrData.baselinecorr(:,k)=polyval(basefit,NmrData.Specscale);
            end
        else
            NmrData.baselinecorr=0;
        end
        NmrData.SPECTRA=NmrData.SPECTRA-NmrData.baselinecorr;
        guidata(hMainFigure,NmrData);
        %ButtonAutoscale_Callback();
        PlotSpectrum();
    end
    function EditOrder_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        if NmrData.order<0
            NmrData.order=0;
            set(hEditOrder,'string',num2str(NmrData.order))
        else
            NmrData.order=round(str2double(get(hEditOrder,'string')));
        end
        guidata(hMainFigure,NmrData);
        
    end
    function OrderButtonPlus_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        NmrData.order=NmrData.order+1;
        set(hEditOrder,'string',num2str(NmrData.order))
        guidata(hMainFigure,NmrData);
    end
    function OrderButtonMinus_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        if NmrData.order<1
            NmrData.order=0;
            set(hEditOrder,'string',num2str(NmrData.order))
        else
            NmrData.order=NmrData.order-1;
            set(hEditOrder,'string',num2str(NmrData.order))
            NmrData.order=round(str2double(get(hEditOrder,'string')));
        end
        guidata(hMainFigure,NmrData);
    end
%Reference deconvolution
    function RDButtonLeft_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@RDLeft_function)
    end
    function RDButtonRight_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@RDRight_function)
    end
    function RDButtonCentre_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@RDCentre_function)
    end
    function RDButtonFind_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        NmrData=guidata(hMainFigure);
        switch NmrData.shiftunits
            case 'ppm'
                startunit='ppm';
            case 'Hz'
                NmrData.shiftunits='ppm';
                NmrData.xlim_spec=NmrData.xlim_spec./NmrData.sfrq;
                NmrData.RDcentre=NmrData.RDcentre./NmrData.sfrq;
                startunit='Hz';
            otherwise
                error('illegal choice')
        end
        
        hRDcentre=findobj(hAxes,'tag','RDcentre');
        delete(hRDcentre)
        xpoint=(NmrData.RDcentre-NmrData.sp)/NmrData.sw;
        xpoint=round(xpoint*NmrData.fn);
        ppmsearch=0.01;
        xmax=xpoint+round(ppmsearch/NmrData.sw*NmrData.fn);
        xmin=xpoint-round(ppmsearch/NmrData.sw*NmrData.fn);
        tempspec=real(NmrData.SPECTRA(:,NmrData.flipnr));
        tempspec([1:xmin xmax:end],:)=tempspec([1:xmin xmax:end],:).*0.0;
        [~, maxpoint]=max(tempspec);
        maxpoint=maxpoint-1;
        maxpoint=maxpoint/NmrData.fn;
        maxpoint=maxpoint*NmrData.sw;
        maxpoint=maxpoint + NmrData.sp;
        NmrData.RDcentre=maxpoint;
        switch startunit
            case 'ppm'
                %all fine
            case 'Hz'
                NmrData.shiftunits='Hz';
                NmrData.xlim_spec=NmrData.xlim_spec.*NmrData.sfrq;
                NmrData.RDcentre=NmrData.RDcentre.*NmrData.sfrq;
            otherwise
                error('illegal choice')
        end
        NmrData.RDcentrexdata=[NmrData.RDcentre NmrData.RDcentre];
        NmrData.RDcentreydata=get(hAxes,'ylim');
        line(NmrData.RDcentrexdata,NmrData.RDcentreydata,...
            'color','black','linewidth', 1.0,...
            'tag','RDcentre');
        %set(hReferenceCheck,'Value',1)
        guidata(hMainFigure,NmrData);
        set(hAxes,'ButtonDownFcn',@RDcentre_function)
        guidata(hMainFigure,NmrData);
        
    end
    function CheckLbRD_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        if get(hCheckLbRD,'Value')
            set(hEditLbRD,'Enable','On')
            %NmrData.lb=str2double(get(hEditLb,'string'));
        else
            set(hEditLbRD,'Enable','Off')
        end
        guidata(hMainFigure,NmrData);
    end
    function CheckGwRD_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        if get(hCheckGwRD,'Value')
            set(hEditGwRD,'Enable','On')
            %NmrData.lb=str2double(get(hEditLb,'string'));
        else
            set(hEditGwRD,'Enable','Off')
        end
        guidata(hMainFigure,NmrData);
    end
    function EditGwRD_Callback(~, ~)
%        gw=(str2double(get(hEditGwRD,'string')));
%         if gw==0
%             errordlg('gw = 0 is illegal','gw error')
%             set(hEditGwRD,'String',num2str(1))
%         end
    end
    function EditLbRD_Callback(~, ~)
        %add some safety
        % I believe that this and the previous function can be totally
        % removed from the code
    end
    function OptimizedFiddle_Callback (~, ~)
        NmrData=guidata(hMainFigure);


        

        guidata(hMainFigure,NmrData);
    end
    function RDButtonFiddle_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
            NmrData.ylim_fid=ylim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        else
            error('Illegal plot type')
        end
        %check that the limits have been set
        if isempty(NmrData.RDleft)==1
            errordlg('Please set left limit for the reference peak','Reference deconvolution error')
            return
        end
        if isempty(NmrData.RDright)==1
            errordlg('Please set right limit for the reference peak','Reference deconvolution error')
            return
        end
        if isempty(NmrData.RDcentre)==1
            errordlg('Please set centre for the reference peak','Reference deconvolution error')
            return
        end
        %check zerofilling
        if NmrData.fn<2*NmrData.np
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Warning - data should be zerofilled at least once')
        end
        %get the lineshape factor
        gw=Inf;
        lb=0;
        if strcmpi(get(hEditLbRD,'Enable'),'off')==1 && strcmpi(get(hEditGwRD,'Enable'),'off')
            errordlg('Please set a target lineshape','Reference deconvolution error')
            return
        else
            if strcmpi(get(hEditLbRD,'Enable'),'on')==1
                lb=str2double(get(hEditLbRD,'string'));
            end
            if strcmpi(get(hEditGwRD,'Enable'),'on')==1
                gw=str2double(get(hEditGwRD,'string'));
                %Moving to gaussian width
                %gw=FwHH=2*sqrt(log(2)))/(pi*gf)
                gw=2*sqrt(log(2))/(pi*gw);
                
            end
        end
        % for m=1:NmrData.ngrad
        SPECTRA=zeros(NmrData.fn/2,NmrData.arraydim);
        for m=1:NmrData.arraydim
            % create the time shifted fid
            wholespec=real(NmrData.SPECTRA(:,m));
            wholefid=ifft(flipud(fftshift(real(NmrData.SPECTRA(:,m)),1)),NmrData.fn);
            wholefid=wholefid(1:NmrData.fn/2);

%wholefid=conj(wholefid)*-1i;
%wholefid=complex(real(wholefid)*-1,imag(wholefid)*1);
            
            % create the time shifted FID of the reference peak
            speclim(2)=NmrData.RDleft;
            speclim(1)=NmrData.RDright;
%             if speclim(1)<NmrData.spCorrect(m,:)
%                 speclim(1)=NmrData.spCorrect(m,:);
%             end
%             if speclim(2)>(NmrData.sw+NmrData.spCorrect(m,:))
%                 speclim(2)=(NmrData.sw+NmrData.spCorrect(m,:));
%             end
%             speclim=NmrData.fn*(speclim-NmrData.spCorrect(m,:))/NmrData.sw;

            if speclim(1)<NmrData.sp
                speclim(1)=NmrData.sp;
            end
            if speclim(2)>(NmrData.sw+NmrData.sp)
                speclim(2)=(NmrData.sw+NmrData.sp);
            end
            speclim=NmrData.fn*(speclim-NmrData.sp)/NmrData.sw;
          
                 
            if speclim(1)<1
                speclim(1)=1;
            end
            if speclim(2)>NmrData.fn
                speclim(2)=NmrData.fn;
            end
            speclim=round(speclim);
            %speclim(1)=speclim(1)+1;
            exprefspec=wholespec;
            
            %do a baseline correction using 1/8 of the data points on the
            %extreme of each side of the reference region
            numpoints=speclim(2)-speclim(1);
            numpoints=round(numpoints/8)  ;
            refbasefit=polyfit(NmrData.Specscale...
                ([speclim(1):(speclim(1)+numpoints) (speclim(2)-numpoints):speclim(2)])',...
                exprefspec([speclim(1):(speclim(1)+numpoints) (speclim(2)-numpoints):speclim(2)]),1);
            corrline=polyval(refbasefit,NmrData.Specscale(speclim(1):speclim(2)));
            exprefspec(speclim(1):speclim(2))=exprefspec(speclim(1):speclim(2))-corrline';
            exprefspec([1:speclim(1) speclim(2):NmrData.fn])=0;
            
            %expreffid=ifft(exprefspec);
            expreffid=ifft(flipud(fftshift(exprefspec,1)),NmrData.fn);
            expreffid=expreffid(1:NmrData.fn/2);
            
            % Create a perfect reference peak
%             lft=(NmrData.RDleft-NmrData.spCorrect(m))/NmrData.sw;
%             lft=round(lft*NmrData.fn);
%             rgt=(NmrData.RDright-NmrData.spCorrect(m))/NmrData.sw;
%             rgt=round(rgt*NmrData.fn);

%             NmrData.RDright;
%             [M I] = max(real(NmrData.SPECTRA(rgt:lft,NmrData.flipnr)));
%             limits = NmrData.Specscale(:,rgt:lft);
%             NmrData.RDcentre=limits(I);
            omega= 0.5*NmrData.sw.*NmrData.sfrq-(NmrData.RDcentre-NmrData.sp).*NmrData.sfrq;
            
            peak_height=1;
            delta=NmrData.RDleft-NmrData.RDright;
            switch NmrData.shiftunits
                case 'ppm'
                    delta=delta*NmrData.sfrq;
                case 'Hz'
                    %correct delta
                otherwise
                    error('illegal choice')
            end
            
            

            %add sattelites if appropriate
            switch  get(hBGroupPeak,'SelectedObject')
                %The decaplets at +/- 59 Hz coudl be used with J of 3.1 Hz.
                %I'll code that in later
                case hRadio1Peak1 %normal singlet

                case hRadio2Peak2 %TSP
                    %MN 19 April 2024 fixed sign of J
                    if delta>120 %include satellites
                        omega(2)=omega(1)+59.25+0.00155*NmrData.sfrq;
                        omega(3)=omega(1)-59.25+0.00155*NmrData.sfrq;
                        peak_height(2)=0.00555;
                        peak_height(3)=0.00555;
                    end
                    omega(4)=omega(1)+3.31+0.00013*NmrData.sfrq;
                    omega(5)=omega(1)-3.31+0.00013*NmrData.sfrq;
                    omega(6)=omega(1)+1.37+0.0002*NmrData.sfrq;
                    omega(7)=omega(1)-1.37+0.0002*NmrData.sfrq;
                    omega(8)=omega(1)+1.16+0.0002*NmrData.sfrq;
                    omega(9)=omega(1)-1.16+0.0002*NmrData.sfrq;
                    omega(10)=omega(1)+0.95+0.0002*NmrData.sfrq;
                    omega(11)=omega(1)-0.95+0.0002*NmrData.sfrq;
                    omega(12)=omega(1)+0.74+0.0002*NmrData.sfrq;
                    omega(13)=omega(1)-0.74+0.0002*NmrData.sfrq;

                    peak_height(4)=0.0247;
                    peak_height(5)=0.0247;
                    peak_height(6)=0.0016*2/3;
                    peak_height(7)=0.0016*2/3;
                    peak_height(8)=0.0047*2/3;
                    peak_height(9)=0.0047*2/3;
                    peak_height(10)=0.0047*2/3;
                    peak_height(11)=0.0047*2/3;
                    peak_height(12)=0.0016*2/3;
                    peak_height(13)=0.0016*2/3;


                case hRadio2Peak3 %TMS
                    %MN 19 April 2024 fixed sign of J
                    if delta>120 %include satellites
                        omega(2)=omega(1)+59.25+0.00155*NmrData.sfrq;
                        omega(3)=omega(1)-59.25+0.00155*NmrData.sfrq;
                        peak_height(2)=0.00555;
                        peak_height(3)=0.00555;
                    end
                    omega(4)=omega(1)+3.31+0.00013*NmrData.sfrq;
                    omega(5)=omega(1)-3.31+0.00013*NmrData.sfrq;
                    omega(6)=omega(1)+1.37+0.0002*NmrData.sfrq;
                    omega(7)=omega(1)-1.37+0.0002*NmrData.sfrq;
                    omega(8)=omega(1)+1.16+0.0002*NmrData.sfrq;
                    omega(9)=omega(1)-1.16+0.0002*NmrData.sfrq;
                    omega(10)=omega(1)+0.95+0.0002*NmrData.sfrq;
                    omega(11)=omega(1)-0.95+0.0002*NmrData.sfrq;
                    omega(12)=omega(1)+0.74+0.0002*NmrData.sfrq;
                    omega(13)=omega(1)-0.74+0.0002*NmrData.sfrq;

                    peak_height(4)=0.0247;
                    peak_height(5)=0.0247;
                    peak_height(6)=0.0016;
                    peak_height(7)=0.0016;
                    peak_height(8)=0.0047;
                    peak_height(9)=0.0047;
                    peak_height(10)=0.0047;
                    peak_height(11)=0.0047;
                    peak_height(12)=0.0016;
                    peak_height(13)=0.0016;

                case hRadio2Peak4 %DSS
                     %MN 19 April 2024 - added DSS
                    if delta>120 %include satellites - guessed (GAM)
                        omega(2)=omega(1)+59.25+0.00155*NmrData.sfrq;
                        omega(3)=omega(1)-59.25+0.00155*NmrData.sfrq;
                        peak_height(2)=0.00555;
                        peak_height(3)=0.00555;
                    end
                    omega(4)=omega(1)+3.32+0.00008*NmrData.sfrq;
                    omega(5)=omega(1)-3.32+0.00008*NmrData.sfrq;
                    omega(6)=omega(1)+1.27+0.0002*NmrData.sfrq;
                    omega(7)=omega(1)-1.27+0.0002*NmrData.sfrq;
                    omega(8)=omega(1)+0.96+0.0002*NmrData.sfrq;
                    omega(9)=omega(1)-0.96+0.0002*NmrData.sfrq;
                    omega(10)=omega(1)+0.85+0.0002*NmrData.sfrq;
                    omega(11)=omega(1)-0.85+0.0002*NmrData.sfrq;
                    omega(12)=omega(1)+0.64+0.0002*NmrData.sfrq;
                    omega(13)=omega(1)-0.64+0.0002*NmrData.sfrq;

                    peak_height(4)=0.0251;
                    peak_height(5)=0.0251;
                    peak_height(6)=0.00146;
                    peak_height(7)=0.00146;
                    peak_height(8)=0.00439;
                    peak_height(9)=0.00439;
                    peak_height(10)=0.00439;
                    peak_height(11)=0.00439;
                    peak_height(12)=0.00146;
                    peak_height(13)=0.00146;
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown satellite shape - using pure singlet');
            end
            t=linspace(0,0.5*(NmrData.fn/NmrData.np)*NmrData.at,NmrData.fn/2);
            reffid=zeros(1,NmrData.fn/2);
            for n=1:length(omega)
                reffid=reffid+peak_height(n)*exp(1i*2*pi*omega(n)*t);
            end

            reffid=reffid.*exp(-t*pi*lb -(t/gw).^2);
            reffid=reffid(:);
            % Create the correction fid
            corrfid=expreffid./reffid;
            corrfid=corrfid/corrfid(1);
            endfid=wholefid./corrfid;
            endfid(1,:)=endfid(1,:)*NmrData.fpmult;
            SPECTRA(:,m)=endfid;
        end
        
        NmrData.SPECTRA=flipud((fftshift(fft(SPECTRA,NmrData.fn),1)));
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function RDshowCheck_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        if get(hRDshowCheck,'Value')
            line(NmrData.RDcentrexdata,NmrData.RDcentreydata,...
                'color','black','linewidth', 1.0,...
                'tag','RDcentre');
        else
            hRDcentre=findobj(hAxes,'tag','RDcentre');
            delete(hRDcentre)
            set(hAxes,'ButtonDownFcn','')
        end
        guidata(hMainFigure,NmrData);
    end
    function RDshowLRCheck_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        if get(hRDshowLRCheck,'Value')
            line(NmrData.RDleftxdata,NmrData.RDleftydata,...
                'color','red','linewidth', 1.0,...
                'tag','RDleft');
            line(NmrData.RDrightxdata,NmrData.RDrightydata,...
                'color','green','linewidth', 1.0,...
                'tag','RDright');
        else
            hRDright=findobj(hAxes,'tag','RDright');
            hRDleft=findobj(hAxes,'tag','RDleft');
            delete(hRDleft)
            delete(hRDright)
            set(hAxes,'ButtonDownFcn','')
        end
        guidata(hMainFigure,NmrData);
    end
    function RDButtonDelta_Callback( ~, ~) 
        %get the delta the spectrum
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        guidata(hMainFigure,NmrData);
        NmrData=guidata(hMainFigure);
        delta=NmrData.RDleft-NmrData.RDright;
        centre=NmrData.RDright+delta/2;
        switch NmrData.shiftunits
            case 'ppm'
                deltaorg=[delta NmrData.sfrq*delta];
                deltaorg=round(deltaorg*10000)/10000;
                delta=inputdlg({'set delta (ppm)','set delta (Hz)'},'Delta',1,{num2str(delta),num2str(NmrData.sfrq*delta)});
                delta=str2double(delta);
                delta=round(delta*10000)/10000;
                                
                if deltaorg(1)~=delta(1) && deltaorg(2)~=delta(2)
                    warndlg('Only change the ppr OR Hz value')
                    uiwait(gcf)
                    delta=deltaorg(1);
                elseif deltaorg(1)~=delta(1)
                    delta=delta(1);
                elseif deltaorg(2)~=delta(2)
                    delta=delta(2)/NmrData.sfrq;
                else
                    delta=deltaorg(1);
                end
                
                
            case 'Hz'
                deltaorg=[delta/NmrData.sfrq delta];
                deltaorg=round(deltaorg*10000)/10000;
                delta=inputdlg({'set delta (ppm)','set delta (Hz)'},'Delta',1,{num2str(delta/NmrData.sfrq),num2str(delta)});
                delta=str2double(delta);
                delta=round(delta*10000)/10000;
                               
                if deltaorg(1)~=delta(1) && deltaorg(2)~=delta(2)
                    warndlg('Only change the ppm OR Hz value')
                    uiwait(gcf)
                    delta=deltaorg(2);
                elseif deltaorg(1)~=delta(1)
                    delta=delta(1)*NmrData.sfrq;
                elseif deltaorg(2)~=delta(2)
                    delta=delta(2);
                else
                    delta=deltaorg(1);
                end
               
            otherwise
                error('illegal choice')
        end
        

        if isempty(delta) || isnan(delta)
            % do nothing
        else
            NmrData.RDleft=centre+delta/2;
            NmrData.RDright=centre-delta/2;
            NmrData.RDleftxdata=[NmrData.RDleft NmrData.RDleft];
            NmrData.RDrightxdata=[NmrData.RDright NmrData.RDright];
            NmrData.RDleftydata=get(hAxes,'ylim');
            NmrData.RDrightydata=get(hAxes,'ylim');
            guidata(hMainFigure,NmrData);
            PlotSpectrum();
        end
    end
    function whsm_Callback(~,~)
        whsm()
        PlotSpectrum()
    end 
%% ---------Array Tab callbacks
    function EditFlip_Callback(~,~)
        NmrData=guidata(hMainFigure);
        %Det which spectrum in the decay to plot
        NmrData.gradnr=round(str2double(get(hEditFlip,'String')));
        if NmrData.gradnr>NmrData.ngrad
            NmrData.gradnr=NmrData.ngrad;
        end
        if NmrData.gradnr<1
            NmrData.gradnr=1;
        end
        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        NmrData.flipnr=(NmrData.array3nr-1).*NmrData.ngrad2+(NmrData.array2nr-1).*NmrData.ngrad + NmrData.gradnr;
        set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hEditFlip,'String',num2str(NmrData.gradnr))
        guidata(hMainFigure,NmrData);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh1,'string',num2str(NmrData.lp,4))
                set(hEditPh0,'string',num2str(NmrData.rp,4))
                set(hSliderPh0,'value',NmrData.rp);
                set(hSliderPh1,'value',NmrData.lp);
            case hRadioScopeIndividual
                set(hEditPh1,'string',num2str(NmrData.lpInd(NmrData.flipnr),4))
                set(hEditPh0,'string',num2str(NmrData.rpInd(NmrData.flipnr),4))
                set(hSliderPh0,'value',NmrData.rpInd(NmrData.flipnr));
                set(hSliderPh1,'value',NmrData.lpInd(NmrData.flipnr));
            otherwise
                error('illegal choice')
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonFlipPlus_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.gradnr=NmrData.gradnr+1;
        set(hEditFlip,'String',num2str(NmrData.gradnr))
        guidata(hMainFigure,NmrData);
        EditFlip_Callback();
        
    end
    function ButtonFlipMinus_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.gradnr=NmrData.gradnr-1;
        set(hEditFlip,'String',num2str(NmrData.gradnr))
        guidata(hMainFigure,NmrData);
        EditFlip_Callback();
    end
    function EditFlip2_Callback(~,~)
        NmrData=guidata(hMainFigure);
        %Det which spectrum in the decay to plot
        NmrData.array2nr=round(str2double(get(hEditFlip2,'String')));
        if NmrData.array2nr>NmrData.narray2
            NmrData.array2nr=NmrData.narray2;
        elseif NmrData.array2nr<1
            NmrData.array2nr=1;
        end
        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        NmrData.flipnr=(NmrData.array3nr-1).*NmrData.ngrad2+(NmrData.array2nr-1).*NmrData.ngrad + NmrData.gradnr;
        set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hEditFlip2,'String',num2str(NmrData.array2nr))
        guidata(hMainFigure,NmrData);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh1,'string',num2str(NmrData.lp,4))
                set(hEditPh0,'string',num2str(NmrData.rp,4))
                set(hSliderPh0,'value',NmrData.rp);
                set(hSliderPh1,'value',NmrData.lp);
            case hRadioScopeIndividual
                set(hEditPh1,'string',num2str(NmrData.lpInd(NmrData.flipnr),4))
                set(hEditPh0,'string',num2str(NmrData.rpInd(NmrData.flipnr),4))
                set(hSliderPh0,'value',NmrData.rpInd(NmrData.flipnr));
                set(hSliderPh1,'value',NmrData.lpInd(NmrData.flipnr));
            otherwise
                error('illegal choice')
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonFlipPlus2_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.array2nr=NmrData.array2nr+1;
        set(hEditFlip2,'String',num2str(NmrData.array2nr))
        guidata(hMainFigure,NmrData);
        EditFlip2_Callback();
    end
    function ButtonFlipMinus2_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.array2nr=NmrData.array2nr-1;
        set(hEditFlip2,'String',num2str(NmrData.array2nr))
        guidata(hMainFigure,NmrData);
        EditFlip2_Callback();
    end
    function EditFlip3_Callback(~,~)
        NmrData=guidata(hMainFigure);
        %Det which spectrum in the decay to plot
        NmrData.array3nr=round(str2double(get(hEditFlip2,'String')));
        if NmrData.array3nr>NmrData.narray3
            NmrData.array3nr=NmrData.narray3;
        elseif NmrData.array3nr<1
            NmrData.array3nr=1;
        end
        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        NmrData.flipnr=(NmrData.array3nr-1).*NmrData.ngrad2+(NmrData.array2nr-1).*NmrData.ngrad + NmrData.gradnr;
        set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hEditFlip2,'String',num2str(NmrData.array2nr))
        set(hEditFlip3,'String',num2str(NmrData.array3nr))
        guidata(hMainFigure,NmrData);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh1,'string',num2str(NmrData.lp,4))
                set(hEditPh0,'string',num2str(NmrData.rp,4))
                set(hSliderPh0,'value',NmrData.rp);
                set(hSliderPh1,'value',NmrData.lp);
            case hRadioScopeIndividual
                set(hEditPh1,'string',num2str(NmrData.lpInd(NmrData.flipnr),4))
                set(hEditPh0,'string',num2str(NmrData.rpInd(NmrData.flipnr),4))
                set(hSliderPh0,'value',NmrData.rpInd(NmrData.flipnr));
                set(hSliderPh1,'value',NmrData.lpInd(NmrData.flipnr));
            otherwise
                error('illegal choice')
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonFlipPlus3_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.array3nr=NmrData.array3nr+1;
        set(hEditFlip2,'String',num2str(NmrData.array3nr))
        guidata(hMainFigure,NmrData);
        EditFlip3_Callback();
    end
    function ButtonFlipMinus3_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.array3nr=NmrData.array3nr-1;
        set(hEditFlip2,'String',num2str(NmrData.array3nr))
        guidata(hMainFigure,NmrData);
        EditFlip3_Callback();
    end
    function EditFlipSpec_Callback(~,~)
        NmrData=guidata(hMainFigure);
        %Det which spectrum in the decay to plot
        NmrData.flipnr=round(str2double(get(hEditFlipSpec,'String')));
        if NmrData.flipnr>NmrData.arraydim
            NmrData.flipnr=NmrData.arraydim;
        elseif NmrData.flipnr<1
            NmrData.flipnr=1;
        end
        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        
        NmrData.gradnr=mod((NmrData.flipnr-1),NmrData.ngrad) +1;
        set(hEditFlip,'String',num2str(NmrData.gradnr))
        
        if NmrData.ngrad2==NmrData.ngrad
            NmrData.array3nr=1;
        else
            NmrData.array3nr=(NmrData.flipnr-(mod((NmrData.flipnr-1),NmrData.ngrad2) +1))./NmrData.ngrad2 +1 ;
        end
        set(hEditFlip3,'String',num2str(NmrData.array3nr))
        
        NmrData.array2nr=(NmrData.flipnr-NmrData.gradnr-((NmrData.array3nr-1)*NmrData.ngrad2)...
            )./(NmrData.ngrad) +1 ;
        set(hEditFlip2,'String',num2str(NmrData.array2nr))
        
        guidata(hMainFigure,NmrData);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh1,'string',num2str(NmrData.lp,4))
                set(hEditPh0,'string',num2str(NmrData.rp,4))
                set(hSliderPh0,'value',NmrData.rp);
                set(hSliderPh1,'value',NmrData.lp);
            case hRadioScopeIndividual
                set(hEditPh1,'string',num2str(NmrData.lpInd(NmrData.flipnr),4))
                set(hEditPh0,'string',num2str(NmrData.rpInd(NmrData.flipnr),4))
                set(hSliderPh0,'value',NmrData.rpInd(NmrData.flipnr));
                set(hSliderPh1,'value',NmrData.lpInd(NmrData.flipnr));
            otherwise
                error('illegal choice')
        end
        set(hEditShift,'string',num2str(NmrData.fshift(NmrData.flipnr),6));
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function EditFlipSpecShort_Callback(~,~)
        NmrData=guidata(hMainFigure);
        %Det which spectrum in the decay to plot
        NmrData.flipnr=round(str2double(get(hEditFlipSpecShort,'String')));
        if NmrData.flipnr>NmrData.arraydim
            NmrData.flipnr=NmrData.arraydim;
        elseif NmrData.flipnr<1
            NmrData.flipnr=1;
        end
        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        NmrData.gradnr=mod((NmrData.flipnr-1),NmrData.ngrad) +1;
        set(hEditFlip,'String',num2str(NmrData.gradnr))
        
        if NmrData.ngrad2==NmrData.ngrad
            NmrData.array3nr=1;
        else
            NmrData.array3nr=(NmrData.flipnr-(mod((NmrData.flipnr-1),NmrData.ngrad2) +1))./NmrData.ngrad2 +1 ;
        end
        set(hEditFlip3,'String',num2str(NmrData.array3nr))
        
        NmrData.array2nr=(NmrData.flipnr-NmrData.gradnr-((NmrData.array3nr-1)*NmrData.ngrad2)...
            )./(NmrData.ngrad) +1 ;
        set(hEditFlip2,'String',num2str(NmrData.array2nr))
        
        % NmrData.ngrad; %2
        % NmrData.narray2; %3
        % NmrData.narray3; %4
        % 
        guidata(hMainFigure,NmrData);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh1,'string',num2str(NmrData.lp,4))
                set(hEditPh0,'string',num2str(NmrData.rp,4))
                set(hSliderPh0,'value',NmrData.rp);
                set(hSliderPh1,'value',NmrData.lp);
            case hRadioScopeIndividual
                set(hEditPh1,'string',num2str(NmrData.lpInd(NmrData.flipnr),4))
                set(hEditPh0,'string',num2str(NmrData.rpInd(NmrData.flipnr),4))
                set(hSliderPh0,'value',NmrData.rpInd(NmrData.flipnr));
                set(hSliderPh1,'value',NmrData.lpInd(NmrData.flipnr));
            otherwise
                error('illegal choice')
        end
        set(hEditShift,'string',num2str(NmrData.fshift(NmrData.flipnr),6));
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonFlipPlusSpec_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.flipnr=NmrData.flipnr+1;
        set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        guidata(hMainFigure,NmrData);
        EditFlipSpec_Callback();
        
    end
    function ButtonFlipMinusSpec_Callback(~,~)
        %Set which spectrum in the decay to plot
        NmrData=guidata(hMainFigure);
        NmrData.flipnr=NmrData.flipnr-1;
        set(hEditFlipSpec,'String',num2str(NmrData.flipnr))
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        guidata(hMainFigure,NmrData);
        EditFlipSpec_Callback();
    end
%-------------End of Flip panel callbacks----------------------------------
%% ---------Prune Tab callbacks
    function ExcludeShow_Callback( ~, ~)

        zoom off
        pan off
        button_state = get(hExcludeShow,'Value');
        if button_state == 1
            Excludeline_function();
            
        elseif button_state == 0
            hExcludeline=findobj(hAxes,'tag','excludeline');
            delete(hExcludeline)
        end
        
    end
    function SetExcludeButton_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','');
        guidata(hMainFigure,NmrData);
        set(hMainFigure,'WindowButtonDownFcn',@Excludeline_function);
        guidata(hMainFigure,NmrData);
        %get the delta the spectrum
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        guidata(hMainFigure,NmrData);
        %set(hAxes,'ButtonDownFcn',@Excludeline_function)
        set(hExcludeShow,'Value',1)
        guidata(hMainFigure,NmrData);
      if size(NmrData.Specscale)==size(NmrData.exclude)
        PlotSpectrum();
      else
          ClearExcludeButton_Callback
      end
        %DrawExcludeline();
    end
    function ClearExcludeButton_Callback( ~, ~)
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        NmrData.ExcludePoints=[];
        NmrData.excludelinepoints=[];
        NmrData.exclude=ones(1,NmrData.fn);
        %set(hAxes,'ButtonDownFcn',@Excludeline_function)
        set(hMainFigure,'WindowButtonDownFcn',@Excludeline_function);
        hExcludeline=findobj(hAxes,'tag','excludeline');
        delete(hExcludeline);
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        %DrawExcludeline();
    end
%% ---------Linear Prediction tab callbacks
    function linpredict(~,~)
        NmrData=guidata(hMainFigure);
        Options=zeros(1,5);
        switch get(LP.hBGroupLPOpt1,'SelectedObject') 
            case LP.hRadio1LPOpt1
                Options(2)=1;
            case LP.hRadio2LPOpt1
                Options(2)=0;
        end
         switch get(LP.hBGroupLPOpt2,'SelectedObject') 
            case LP.hRadio1LPOpt2
                Options(1)=1; % Use SVD method
            case LP.hRadio2LPOpt2
                Options(1)=2; % Use matrix pencil method
         end
         
        Options(5)=str2double(get(LP.hEditNCOEF,'String')); %Get the coefficients 
        Options(4)=str2double(get(LP.hEditNPU,'String')); %Get the coefficients 
        Options(3)=str2double(get(LP.hEditNPP,'String')); %Get the coefficients
        NmrData.FID=LP1D(NmrData.FID,Options);
        NmrData.np=length(NmrData.FID);
        set(hEditNp,'string',NmrData.np);
        guidata(hMainFigure,NmrData);
        FTButton_Callback
    end
    
  
 
%% ---------Pure shift callbacks
    function PureshiftConvert_Callback( ~, ~)
       
        tmporig=guidata(hMainFigure);  
        psdata=guidata(hMainFigure);
        nfid= str2double(get(hEditnfid,'string'));
        npoint= str2double(get(hEditnpoints,'string'));
        firstfidpoint=str2double(get(hEditnfirstfidpoints,'string'));
        droppts=str2double(get(hEditDropPoints,'string'));
        
        if isnan(nfid)||isnan(npoint)||isnan(firstfidpoint)||isnan(droppts) %Added by LC/GDP 21-09-2019 
            WriteLogDispInfo('Pure shift parameters empty. Press "Estim. Param."')
            click_msgbox('Caution','Pure shift parameters empty. Press "Estim. Param."')
            return
        end
        
        if ~isempty(psdata)
            tmp_lrfidOrg=NmrData.lrfidOrg;
            Initiate_NmrData();
            NmrData.SaveState=psdata.SaveState;
            NmrData.lrfidOrg=tmp_lrfidOrg;
            NmrData.type=psdata.type;
            NmrData.lrfid=psdata.lrfid;
            NmrData.sfrq=psdata.sfrq;
            NmrData.FID=psdata.FID;
            NmrData.filename=psdata.filename;
            NmrData.dosyconstant=psdata.dosyconstant;
            NmrData.Gzlvl=psdata.Gzlvl;
            NmrData.ngrad=psdata.ngrad;
            if (isfield(psdata,'acqus'))
                NmrData.acqus=psdata.acqus;
            end
            if (isfield(psdata,'acqus2'))
                NmrData.acqus=psdata.acqus2;
            end
            if (isfield(psdata,'procpar'))
                NmrData.procpar=psdata.procpar;
            end
            NmrData.np=psdata.np;
            NmrData.fn=NmrData.np;
            NmrData.sw=psdata.sw;
            NmrData.at=psdata.at;
            NmrData.sp=psdata.sp;
            NmrData.lp=0;
            NmrData.rp=0;
            NmrData.gamma=psdata.gamma;
            NmrData.DELTA=psdata.DELTA;
            NmrData.delta=psdata.delta;
            NmrData.narray2=1;
            if (isfield(psdata,'arraydim'))
                NmrData.arraydim=psdata.arraydim;
            else
                %not sure what this does - should not happen
                NmrData.arraydim=NmrData.ngrad;                
            end
            if isfield(psdata,'d2')
                NmrData.d2=psdata.d2;
                NmrData.d2_org=psdata.d2;
            end
            if isfield(psdata,'vclist')
                NmrData.vclist=psdata.vclist;
                NmrData.vclist_org=psdata.vclist;
            end
            if isfield(psdata,'vc_constant')
                NmrData.vc_constant=psdata.vc_constant;
                NmrData.vc_constant_org=psdata.vc_constant;
            end
            
            if strcmpi(NmrData.Gzlvl,'non existing')
                if isempty(NmrData.d2)
                    NmrData.ngrad=1;
                else
                    NmrData.ngrad=length(NmrData.d2);
                end
            end

            NmrData.ngrad2=NmrData.ngrad;   %Added by LC/GDP 21-09-2019 
            
            if NmrData.lrfidOrg>0
                %left shift the fid
                for k=1:NmrData.arraydim
                    NmrData.FID(:,k)= circshift(NmrData.FID(:,k),-NmrData.lrfidOrg);
                end
                NmrData.lrfidOrig=0;
            end
            
            psdata.narray2;
            
            if psdata.narray2==1 %2D data
                FID=zeros(NmrData.ngrad,npoint*nfid);
                psFID(1:firstfidpoint)=NmrData.FID(droppts+1:firstfidpoint+droppts);
                for k=2:nfid                   
                    psFID(firstfidpoint+(k-2)*npoint+1:firstfidpoint+(k-1)*npoint)=...
                       NmrData.FID(droppts+1:npoint+droppts,(k));     
                end
                FID(1,:)=psFID(:);
            else %nD data
            FID=zeros(NmrData.ngrad,npoint*nfid);
            for ngzlv=1:NmrData.ngrad
                FID(ngzlv,1:firstfidpoint)=NmrData.FID(droppts+1:firstfidpoint+droppts,ngzlv);
                for k=2:nfid                   
                    FID(ngzlv,firstfidpoint+(k-2)*npoint+1:firstfidpoint+(k-1)*npoint)=...
                        NmrData.FID(droppts+1:npoint+droppts,(k-1)*NmrData.ngrad+ngzlv);
                end
            end
            end
            
            
            NmrData.FID=complex(imag(FID),real(FID))';
            NmrData.arraydim=NmrData.ngrad;
            NmrData.np=length(NmrData.FID);
            NmrData.rp=0;
            NmrData.lp=0;

            clear psdata;
            figure(hMainFigure)
            guidata(hMainFigure,NmrData);
            Setup_NmrData();
             NmrData.orig=tmporig;
            guidata(hMainFigure,NmrData);
        else
            %do nothing
        end
        guidata(hMainFigure,NmrData);

    end
    function UnConvertPureshift_Callback( ~, ~)
       % NmrData=guidata(hMainFigure);
       NmrData= NmrData.orig;
        guidata(hMainFigure,NmrData);
        Setup_NmrData();
    end
    function EstimatePureshift_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        if strcmpi(NmrData.type,'bruker')
            NmrData.MessageText={'Estimating pure shift paramaters'};
            % NmrData.MessageText{end +1}=Message{k};
            if isempty(NmrData.brukerdata.acqu3s) %GDP 15 Aug 2017
                NmrData.MessageText={'2D data'};
                if isfield(NmrData.brukerdata.acqus,'CNST')
                    droppts=(NmrData.brukerdata.acqus.CNST(5));
                    set(hEditDropPoints,'string',num2str(droppts));
                else
                    warndlg('Cannot estimate drop points. No CNST 4')
                    uiwait(gcf)
                end
                if isfield(NmrData.brukerdata.acqu2s,'TD')
                    nchunk=str2double(NmrData.brukerdata.acqu2s.TD); 
                    
                    set(hEditnfid,'string',num2str(nchunk));
                else
                    warndlg('Cannot TD1')
                    uiwait(gcf)
                end
                if isfield(NmrData.brukerdata.acqu2s,'SW') && isfield(NmrData.brukerdata.acqus,'SW')
                    SW=str2double(NmrData.brukerdata.acqus.SW);
                    SW1=str2double(NmrData.brukerdata.acqu2s.SW);
                    chunkpoints=round(SW/SW1);
                    fid_duration=(1000/(SW1*NmrData.sfrq));
                    set(hEditnpoints,'string',num2str(chunkpoints));
                    set(hEditnfirstfidpoints,'string',num2str(chunkpoints));
                    set(hEditfiddur,'string',num2str(fid_duration));
                else
                    warndlg('Cannot find SW or SW1')
                    uiwait(gcf)
                end
            else
                warndlg('More that two dimensions. Estimated paramaters assuming pure shift dimension is in Array 2')
                uiwait(gcf)
                NmrData.MessageText={'3D data'};
                if isfield(NmrData.brukerdata.acqus,'CNST')
                    droppts=(NmrData.brukerdata.acqus.CNST(5));
                    set(hEditDropPoints,'string',num2str(droppts));
                else
                    warndlg('Cannot estimate drop points. No CNST 4')
                    uiwait(gcf)
                    
                end
                if isfield(NmrData.brukerdata.acqu3s,'TD')
                    nchunk=str2double(NmrData.brukerdata.acqu3s.TD); %GDP 15 Aug 2017
                    set(hEditnfid,'string',num2str(nchunk));
                else
                    warndlg('Cannot TD1')
                    uiwait(gcf)
                end
                if isfield(NmrData.brukerdata.acqu3s,'SW') && isfield(NmrData.brukerdata.acqus,'SW')
                    SW=str2double(NmrData.brukerdata.acqus.SW);
                    SW1=str2double(NmrData.brukerdata.acqu3s.SW);
                    chunkpoints=round(SW/SW1);
                    fid_duration=(1000/(SW1*NmrData.sfrq));
                    set(hEditnpoints,'string',num2str(chunkpoints));
                    set(hEditnfirstfidpoints,'string',num2str(chunkpoints));
                    set(hEditfiddur,'string',num2str(fid_duration));
                else
                    warndlg('Cannot find SW or SW1')
                    uiwait(gcf)
                end
                
            end
            NmrData.brukerdata
        else
            warndlg('Esimation only implemented for Bruker data')
            uiwait(gcf)
        end
        guidata(hMainFigure,NmrData);
        
    end
    function Editnfid_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        nfid=round(str2double(get(hEditnfid,'string')));
        set(hEditnfid,'string',num2str(nfid));
        guidata(hMainFigure,NmrData);
    end
    function Editfiddur_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        fiddur=round(str2double(get(hEditfiddur,'string')));
        set(hEditfiddur,'string',num2str(fiddur));
        guidata(hMainFigure,NmrData);
    end
    function Editnpoints_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        npoint=round(str2double(get(hEditnpoints,'string')));
        set(hEditnpoints,'string',num2str(npoint));
        guidata(hMainFigure,NmrData);
    end
    function Editfirstfidpoints_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        firstfidpoint=round(str2double(get(hEditnfirstfidpoints,'string')));
        set(hEditnfirstfidpoints,'string',num2str(firstfidpoint));
        guidata(hMainFigure,NmrData);
    end
    function EditDropPoints_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        droppts=round(str2double(get(hEditDropPoints,'string')));
        set(hEditDropPoints,'string',num2str(droppts));
        guidata(hMainFigure,NmrData);
    end
%% ---------Misc Tab (left) callbacks
    function ButtonPlayCurrentFid_Callback(~,~)
        NmrData=guidata(hMainFigure);
        str=['Playing FID nr: ' num2str(NmrData.flipnr)];
        text(0.5*NmrData.at,0.4*max(real(NmrData.FID(:,NmrData.flipnr))),str,'Color','Black','Fontweight','bold')
        soundsc(real(NmrData.FID(:,NmrData.flipnr))./max(abs(real(NmrData.FID(:,1)))),4096)
        pause(0.5)
        PlotSpectrum();
    end
    function ButtonPlayAllFid_Callback(~,~)
        NmrData=guidata(hMainFigure);
        
        startnr=NmrData.flipnr;
        for k=1:NmrData.arraydim
            NmrData.flipnr=k;
            guidata(hMainFigure,NmrData);
            PlotSpectrum();
            str=['Playing FID nr: ' num2str(k)];
            text(0.5*NmrData.at,0.4*max(real(NmrData.FID(:,1))),str,'Color','Black','Fontweight','bold');
            drawnow
            sound(real(NmrData.FID(:,k))./max(abs(real(NmrData.FID(:,1)))),4096)
            pause(0.3)
            
        end
        NmrData.flipnr=startnr;
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function SaveButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
        else
            error('Illegal plot type')
        end
        guidata(hMainFigure,NmrData);
        if isempty(NmrData.SaveState)
            NmrData.SaveState=NmrData;
        else
            choice = questdlg('Overwrite existing data?', ...
                'Data save', 'Yes','No','No');
            switch choice
                case 'Yes'
                    NmrData.SaveState=NmrData;
                case 'No'
                    %dont do anything
            end
        end
        % PlotSpectrum();
        guidata(hMainFigure,NmrData);
    end
    function RecallButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        if isempty(NmrData.SaveState)
            msgbox('No saved data available');
        else
            choice = questdlg('Recall old data (current data will be lost)?', ...
                'Data recall', 'Yes','No','No');
            switch choice
                case 'Yes'
                    tmp=NmrData.SaveState;
                    NmrData= NmrData.SaveState;
                    NmrData.SaveState=tmp;
                    set(hEditFlip,'string',num2str(NmrData.gradnr));
                    set(hEditFlip2,'string',num2str(NmrData.array2nr));
                    set(hEditFlip3,'string',num2str(NmrData.array3nr));
                    set(hEditFlipSpec,'string',num2str(NmrData.flipnr));
                    set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
                    
                case 'No'
                    return
            end
            
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
%% ---------Messages Tab  callbacks

%% ---------Diffusion Tab Callbacks

%---DOSY---
    function EditMultexp_Callback(~, ~)
        
        %add some safety here
    end
    function EditTries_Callback(~, ~)
        %add some safety here
    end
    function CheckDmax_Callback(~, ~)
        if get(hCheckDmax,'Value')
            set(hEditDmax,'Enable','Off')
        else
            set(hEditDmax,'Enable','On')
        end
    end
    function FitType_Callback(~, ~)
        if get(hBGroupDOSYOpt3,'SelectedObject')==hRadio1DOSYOpt3
            %monoexponetial fit
            set(hEditMultexp,'Enable','Off')
            set(hEditMultexp,'string',num2str(1))
            set(hEditTries,'Enable','Off')
            set(hEditTries,'string',num2str(100))
        else
            %multiexponential
            set(hEditMultexp,'Enable','On')
            set(hEditTries,'Enable','On')
        end
    end
    function Dguess_Callback (~, ~)
        if get(hBGroupSCOREOpt2,'SelectedObject')==hRadio2SCOREOpt2
            set(hRadio3SCOREOpt2,'Enable','On')
            set(hRadio5SCOREOpt2,'Enable','On')
        else
            set(hRadio3SCOREOpt2,'Enable','Off')
            set(hRadio5SCOREOpt2,'Enable','Off')
        end
    end

    function EditSCORE_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.score_alpha=str2double(get(hRadio5SCOREOpt6,'String'));
        set(hRadio4SCOREOpt6,'Value',NmrData.score_alpha);
        guidata(hMainFigure,NmrData);
        guidata(hMainFigure,NmrData);
    end

    function SliderSCORE_Callback(~,~)
        NmrData=guidata(hMainFigure);
        get(hRadio4SCOREOpt6,'Value');
        NmrData.NmrData.score_alpha=get(hRadio4SCOREOpt6,'Value');
        guidata(hMainFigure,NmrData);
        set(hRadio5SCOREOpt6,'String',num2str(NmrData.score_alpha));
        guidata(hMainFigure,NmrData);
    end

    function Alfa_Callback (~, ~)
        if get(hBGroupSCOREOpt6,'SelectedObject')==hRadio3SCOREOpt6
            set(hRadio4SCOREOpt6,'Enable','On')
            set(hRadio5SCOREOpt6,'Enable','On')
        else
            set(hRadio4SCOREOpt6,'Enable','Off')
            set(hRadio5SCOREOpt6,'Enable','Off')
        end
    end

%     function EditDmax_Callback(eventdata, handles)
%         %add some safety here
%     end
%     function EditDmin_Callback(eventdata, handles)
%         %add some safety here
%     end
%     function EditDres_Callback(eventdata, handles)
%         %add some safety here
%     end
    function EditNgrad_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        NmrData.prune=...
            round(str2num(get(hEditNgrad,'string'))); %#ok<ST2NM>
        guidata(hMainFigure,NmrData);
    end
    function EditArray3_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        NmrData.pruneArray3=...
            round(str2num(get(hEditArray3,'string'))); %#ok<ST2NM>
        guidata(hMainFigure,NmrData);
    end
    function EditArray2_Callback(~, ~)
        NmrData=guidata(hMainFigure);
        NmrData.pruneArray2=...
            round(str2num(get(hEditArray2,'string'))); %#ok<ST2NM>
        guidata(hMainFigure,NmrData);
    end
%     function NgradUse_Callback(eventdata, handles)
%         %add some safety here
%     end
    function dodosy(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        switch get(hBGroupDOSYOpt1,'SelectedObject') %Peak picking options
            case hRadio1DOSYOpt1 %Peak pick
                NmrData.DOSYopts(1)=0;
            case hRadio2DOSYOpt1 %All freq
                NmrData.DOSYopts(1)=1;
            case hRadio3DOSYOpt1 %Integrals
                NmrData.DOSYopts(1)=2;
                NmrData.pfgnmrdata.integral_peaks=NmrData.integral_peaks;
                for m=1:NmrData.pfgnmrdata.ngrad
                    RealSpec=real(NmrData.pfgnmrdata.SPECTRA(:,m));
                    for k=1:numel(NmrData.integral_peaks)
                        Offset=0; %#ok<NASGU>
                        Tilt=0; %#ok<NASGU>
                        Start=NmrData.integral_peaks(k).startIndex;
                        Stop=NmrData.integral_peaks(k).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            Offset=NmrData.integral_peaks(k).Offset;
                            Tilt=NmrData.integral_peaks(k).Tilt;
                        else
                            Offset=NmrData.integral_peaks(k).Individual(m).Offset;
                            Tilt=NmrData.integral_peaks(k).Individual(m).Tilt;
                        end
                        %spectra has been normalized in PreparePfgnmrdata()
                        Offset=Offset/ NmrData.pfgnmrdata.normfac;
                        Tilt=Tilt/ NmrData.pfgnmrdata.normfac;
                        tmp=0:(Stop-Start);
                        tmp=(Tilt*tmp)/tmp(end);
                        TiltLine=tmp(:);
                        IntPeak=sum(RealSpec(Start:Stop)-Offset - TiltLine);
                        NmrData.pfgnmrdata.integral_peaks(k).Value(m)=IntPeak;
                        
                    end
                    
                end
                
            otherwise
                error('illegal choice')
        end
        
        switch get(hBGroupDOSYOpt2,'SelectedObject')
            case hRadio1DOSYOpt2
                NmrData.DOSYopts(2)=0;
            case hRadio2DOSYOpt2
                NmrData.DOSYopts(2)=1;
            otherwise
                error('illegal choice')
        end
        NmrData.DOSYopts(3)=str2double(get(hEditMultexp,'String'));
        NmrData.DOSYopts(4)=str2double(get(hEditTries,'String'));
        NmrData.DOSYopts(5)=NmrData.FitType;
        NmrData.DOSYdiffrange(1)=str2double(get(hEditDmin,'String'));
        if get(hCheckDmax,'Value')
            NmrData.DOSYdiffrange(2)=0;
        else
            NmrData.DOSYdiffrange(2)=str2double(get(hEditDmax,'String'));
        end
        
        NmrData.DOSYdiffrange(3)=str2double(get(hEditDres,'String'));
        NmrData.pfgnmrdata.flipnr=NmrData.flipnr; % For running DOSY in 3D datasets
        NmrData.dosydata=dosy_mn(NmrData.pfgnmrdata,NmrData.th,speclim,NmrData.DOSYdiffrange,NmrData.DOSYopts,NmrData.nug);
        
        %print out statistics to file
        DTpath=which('GNAT');
        DTpath=DTpath(1:(end-6));
        statfil=fopen([DTpath 'dosystats.txt'], 'wt');
        fprintf(statfil,'%-s  \n','Fitting statistics for a 2D DOSY experiment');
        if NmrData.dosydata.Options(2)==0
            fprintf(statfil,'%-s  \n','Pure exponential fitting (Stejskal-Tanner equation)');
        elseif NmrData.dosydata.Options(2)==1
            fprintf(statfil,'\n');
            fprintf(statfil,'%-s  \n','Fitting using compensation for non-uniform field gradients (NUG). ');
        else
            fprintf(statfil,'%-s  \n','Unknown function');
        end
        
        if NmrData.dosydata.Options(3)==1
            fprintf(statfil,'%-s  \n','Monoexpoential fitting');
        elseif NmrData.dosydata.Options(3)>1
            fprintf(statfil,'%-s  \n','Multiexpoential fitting');
            fprintf(statfil,'%-s %i \n','Max number of component per peak: ',NmrData.dosydata.Options(3));
        else
            fprintf(statfil,'%-s  \n','error in the number of exponentials (Options(3) in dosy_mn.m)');
        end
        fitsize=size(NmrData.dosydata.FITSTATS);
        fprintf(statfil,'\n');
        fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
        fprintf(statfil,'\n');
        fprintf(statfil,'%-10s  ','Frequency');
        for m=1:fitsize(2)/4
            % fprintf(statfil,'%-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Amplitude',m,'error','Diff coef',m,'error');
            if m==1
                fprintf(statfil,'%-10s  %-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Exp. Ampl','Fit. Ampl',m,'error','Diff coef',m,'error');
            else
                fprintf(statfil,'%-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Fit. Ampl',m,'error','Diff coef',m,'error');
            end
        end
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-10.5f  ',NmrData.dosydata.freqs(k));
            fprintf(statfil,'%-10.5f  ',NmrData.dosydata.ORIGINAL(k,1));
            for m=1:fitsize(2)
                fprintf(statfil,'%-10.5f  ',NmrData.dosydata.FITSTATS(k,m));
            end
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s%s%s \n','Squared gradient amplitudes [', num2str(numel(NmrData.dosydata.Gzlvl)), ']  (T^2 m^-2)');
        for g=1:numel(NmrData.dosydata.Gzlvl)
            fprintf(statfil,'%-10.5e  \n',NmrData.dosydata.Gzlvl(g));
        end
        
        if NmrData.DOSYopts(1)==2 %Integrals
            fprintf(statfil,'\n%s%s%s \n','*******Integral Regions Set *******');
            fprintf(statfil,'\n');
            fprintf(statfil,'%-10s  %-10s  %-10s  \n','Start','Stop','Centre');
            
            for g=1:numel(NmrData.pfgnmrdata.integral_peaks)
                fprintf(statfil,'%-10.5f  %-10.5f %-10.5f \n',NmrData.pfgnmrdata.integral_peaks(g).start,...
                    NmrData.pfgnmrdata.integral_peaks(g).stop, NmrData.pfgnmrdata.integral_peaks(g).max);
            end
        end
        fprintf(statfil,'\n%s%s%s \n','*******Residuals*******');
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-10s %-10.0f %-10s %-10.5f \n','Peak Nr: ', k, 'Frequency (ppm): ',NmrData.dosydata.freqs(k));
            fprintf(statfil,'%-10s   %-10s   %-10s  \n','Exp. Ampl','Fit. Ampl','Diff');
            for m=1:numel(NmrData.dosydata.Gzlvl)
                fprintf(statfil,'%-10.5e  %-10.5e  %-10.5e  \n',NmrData.dosydata.ORIGINAL(k,m),NmrData.dosydata.FITTED(k,m),NmrData.dosydata.RESIDUAL(k,m));
            end
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
        fprintf(statfil,'\n');
        fprintf(statfil,'%-10s  ','Frequency');
        for m=1:fitsize(2)/4
            if m==1
                fprintf(statfil,'%-10s  %-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Exp. Ampl','Fit. Ampl',m,'error','Diff coef',m,'error');
            else
                fprintf(statfil,'%-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Fit. Ampl',m,'error','Diff coef',m,'error');
            end
        end
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-10.5f  ',NmrData.dosydata.freqs(k));
            fprintf(statfil,'%-10.5f  ',NmrData.dosydata.ORIGINAL(k,1));
            for m=1:fitsize(2)
                fprintf(statfil,'%-10.5f  ',NmrData.dosydata.FITSTATS(k,m));
            end
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s\n%s\n','This information can be found in:',[DTpath 'dosystats.txt']);
        fclose(statfil);
        type([DTpath 'dosystats.txt']);
        guidata(hMainFigure,NmrData);
    end
    function plotdosy(~,~)
        dosyplot_gui(NmrData.dosydata);
    end
%----SCORE (diffusion)----
    function doscore(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        NmrData.SCOREopts=[0 0 0 0 0 0 0 0 0]; 
        switch get(hBGroupSCOREOpt1,'SelectedObject')
            case hRadio1SCOREOpt1
                NmrData.SCOREopts(3)=0;
            case hRadio2SCOREOpt1
                NmrData.SCOREopts(3)=1;
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupSCOREOpt2,'SelectedObject')
            case hRadio1SCOREOpt2
                NmrData.SCOREopts(1)=0;
            case hRadio2SCOREOpt2
                NmrData.SCOREopts(1)=1;
                if NmrData.SCOREopts(1)==1
                    NmrData.SCOREopts(7)=str2double(get(hRadio3SCOREOpt2,'String'));
                    NmrData.SCOREopts(9)=str2double(get(hRadio5SCOREOpt2,'String'));
                end
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupSCOREOpt3,'SelectedObject')
            case hRadio1SCOREOpt3
                NmrData.SCOREopts(2)=0;
            case hRadio2SCOREOpt3
                NmrData.SCOREopts(2)=1;
            case hRadio4SCOREOpt3
                NmrData.SCOREopts(2)=3;
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupSCOREOpt6,'SelectedObject')
            case hRadio1SCOREOpt6
                NmrData.SCOREopts(6)=0;
            case hRadio2SCOREOpt6
                NmrData.SCOREopts(6)=1;
                  case hRadio3SCOREOpt6
                NmrData.SCOREopts(6)=2;
                if NmrData.SCOREopts(6)==2
                    NmrData.SCOREopts(8)=str2double(get(hRadio5SCOREOpt6,'String'));
                end
            otherwise
                error('illegal choice')
        end
        button_state = get(hPlotDiag,'Value');
        if button_state==1
            NmrData.SCOREopts(4)=1;
        end
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        speclim(3)=str2double(get(hEditDmax,'string'));
        NmrData.ncomp=str2double(get(hEditNcompSCORE,'String'));
%           if str2num(get(hRadio4SCOREOpt2,'String'))>0
%            fixed=str2num(get(hRadio4SCOREOpt2,'String'));         
%         else
        fixed=[]; 
%         end
        NmrData.scoredata=score_mn(NmrData.pfgnmrdata,NmrData.ncomp,speclim,NmrData.SCOREopts,NmrData.nug,fixed);
      
        guidata(hMainFigure,NmrData);
    end
    function plotscore(~,~)
        NmrData=guidata(hMainFigure);
        scoreplot(NmrData.scoredata);
    end
    function pubplotscore(~,~)
        NmrData=guidata(hMainFigure);
        scoreplotpub(NmrData.scoredata);
    end
%     function EditNcompSCORE_Callback(eventdata, handles)
%         %add some safety here
%     end
%----locodosy----
    function LRInclude_Callback( ~, ~)
        zoom off
        pan off
        set(hLRWindowsShow,'Value',1)
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@Includeline_function);
        DrawIncludeline();
    end
    function LRClear_Callback( ~, ~)
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        NmrData.includelinepoints=[];
        NmrData.IncludePoints=[];
        for k=1:NmrData.fn
            NmrData.include(k)=NaN;
        end
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@Includeline_function)
        hIncludeline=findobj(hAxes,'tag','includeline');
        delete(hIncludeline);
        hPeakclustline=findobj(hAxes,'tag','peakclustline');
        delete(hPeakclustline);
        NmrData.startORend=0;
        NmrData.numcomp=[];
        NmrData.winstart=[];
        NmrData.winend=[];
        NmrData.nwin=[];
        NmrData.LRRegionData=ones(length(NmrData.winstart));
        set(hRegionsTable,'Data', NmrData.LRRegionData)
        guidata(hMainFigure,NmrData);
    end
    function LRDoSVDButton_Callback( ~,~)
        if isempty(NmrData.winstart)
            errordlg('Please select some windows to do SVD on.')
        else
            NmrData=guidata(hMainFigure);
            GetSVDcutoff()
            NmrData.pfgnmrdata=PreparePfgnmrdata();
            %             switch get(hSVDplotsShow,'Value')
            %                 case 1
            %                     SVDoptions=1;
            %                 case 0
            %                     SVDoptions=0;
            %             end
            SVDoptions=0;
            NmrData.numcomp=locodosySVD(NmrData.pfgnmrdata,NmrData.winstart,NmrData.winend,...
                NmrData.nwin,NmrData.fn,SVDoptions,NmrData.SVDcutoff);
            for k=1:length(NmrData.numcomp)
                if NmrData.numcomp(k)>3
                    NmrData.numcomp(k)=3;
                end
            end
            NmrData.LRRegionData=NmrData.numcomp';
            set(hRegionsTable,'Data', NmrData.LRRegionData)
            guidata(hMainFigure,NmrData);
            
        end
    end
    function LRAutorun( ~, ~)
        if isempty(NmrData.winstart)
            errordlg('Please select some windows to do LOCODOSY on')
        else
            NmrData=guidata(hMainFigure);
            NmrData.pfgnmrdata=PreparePfgnmrdata();
            SVDoptions=0;
            NmrData.numcomp=locodosySVD(NmrData.pfgnmrdata,NmrData.winstart,NmrData.winend,...
                NmrData.nwin,NmrData.fn,SVDoptions,NmrData.SVDcutoff);
            for k=1:length(NmrData.numcomp)
                if NmrData.numcomp(k)>3
                    NmrData.numcomp(k)=3;
                end
            end
            NmrData.LRRegionData=NmrData.numcomp';
            set(hRegionsTable,'Data', NmrData.LRRegionData)
            NmrData.locodosyopts(4)=1;
            guidata(hMainFigure,NmrData);
            GetDlimit()
            Getminpercent()
            dolocodosy()
            NmrData.locodosyopts(4)=0;
            guidata(hMainFigure,NmrData);
        end
    end
    function LRRun_Callback( ~, ~)
        switch get(hBGroupRunType,'selectedobject')
            case hRadio1RunType
                % Process with current parameters
                NmrData.locodosyopts(5)=0;
                guidata(hMainFigure,NmrData);
                dolocodosy();
            case hRadio2RunType
                % Auto SVD, Reduce and Process
                NmrData.locodosyopts(5)=1;
                guidata(hMainFigure,NmrData);
                LRAutorun()
        end
    end
    function LRRegionsTable_Callback( ~, ~)
        NmrData.LRRegionData=get(hRegionsTable,'Data');
        NmrData.numcomp=NmrData.LRRegionData';
        guidata(hMainFigure,NmrData);
    end
    function LRAlgorithmChange_Callback( ~, ~)
        switch get(hBGrouplocodosyalg,'SelectedObject')
            case hRadio1locodosyalg
                set(hRadio2locodosyOpt1,'Enable','On')
                set(hRadio2RunType,'Enable','On')
            case hRadio2locodosyalg
                set(hRadio2RunType,'Enable','On')
                set(hBGrouplocodosyOpt1, 'SelectedObject',hRadio1locodosyOpt1)
                set(hRadio2locodosyOpt1,'Enable','Off')
            case hRadio3locodosyalg
                set(hRadio2locodosyOpt1,'Enable','On')
                set(hBGroupRunType, 'SelectedObject',hRadio1RunType)
                set(hRadio2RunType,'Enable','Off')
        end
    end
    function LRWindowsShow_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hLRWindowsShow,'Value');
        if button_state == 1
            hPeakclustline=findobj(hAxes,'tag','peakclustline');
            set(hPeakclustline,'Visible','On')
            hIncludeline=findobj(hAxes,'tag','includeline');
            set(hIncludeline,'Visible','On')
        elseif button_state == 0
            hPeakclustline=findobj(hAxes,'tag','peakclustline');
            set(hPeakclustline,'Visible','Off')
            hIncludeline=findobj(hAxes,'tag','includeline');
            set(hIncludeline,'Visible','Off')
        end
        %PlotSpectrum();
    end
    function Getsderrmultiplier(~,~)
        NmrData=guidata(hMainFigure);
        %retrieves the diffusion value error margin from the toolbox gui.
        NmrData.sderrmultiplier=...
            str2double(get(hEditsderrmultiplier,'string'));
        guidata(hMainFigure,NmrData);
    end
    function GetSVDcutoff(~,~)
        NmrData=guidata(hMainFigure);
        %retrieves the diffusion value error margin from the toolbox gui.
        NmrData.SVDcutoff=...
            str2double(get(hEditSVDcutoff,'string'));
        guidata(hMainFigure,NmrData);
    end
    function GetDlimit(~,~)
        NmrData=guidata(hMainFigure);
        % retrieves the upper limit on diffusion coefficient for judging wether a
        % component is to be discarded or not.
        NmrData.Dlimit=...
            str2double(get(hEditDlimit,'string'));
        guidata(hMainFigure,NmrData);
    end
    function Getminpercent(~,~)
        NmrData=guidata(hMainFigure);
        % retrieves the upper limit on diffusion coefficient for judging wether a
        % component is to be discarded or not.
        NmrData.minpercent=...
            str2double(get(hEditVlimit,'string'));
        guidata(hMainFigure,NmrData);
    end
    function GetDiffRes(~,~)
        NmrData=guidata(hMainFigure);
        % retrieves the upper limit on diffusion coefficient for judging wether a
        % component is to be discarded or not.
        NmrData.DiffRes=...
            str2double(get(hEditDiffRes,'string'));
        guidata(hMainFigure,NmrData);
    end
    function dolocodosy(~,~)
        % retrieve diffusion error margin before loading NmrData structure so as to
        % prevent problems with overwriting.
        Getsderrmultiplier()
        GetDlimit()
        Getminpercent()
        GetDiffRes()
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        if isempty(NmrData.nwin)
            errordlg('The spectrum needs segmenting')
        else
            % see if NUG are being used
            switch get(hBGrouplocodosyOpt1,'SelectedObject')
                case hRadio1locodosyOpt1
                    NmrData.locodosyopts(1)=0;
                case hRadio2locodosyOpt1
                    NmrData.locodosyopts(1)=1;
                otherwise
                    error('illegal choice')
            end
            %
            switch get(hBGrouplocodosyalg,'SelectedObject')
                case hRadio1locodosyalg
                    %SCORE
                    NmrData.locodosyopts(3)=0;
                    guidata(hMainFigure,NmrData);
                    NmrData.pfgnmrdata=PreparePfgnmrdata(); %AC
                case hRadio2locodosyalg
                    %DECRA
                    NmrData.locodosyopts(3)=1;
                    guidata(hMainFigure,NmrData);
                    NmrData.pfgnmrdata=PreparePfgnmrdata(); %AC
                case hRadio3locodosyalg
                    %OUTSCORE
                    NmrData.locodosyopts(3)=2;
                    guidata(hMainFigure,NmrData);
                    NmrData.pfgnmrdata=PreparePfgnmr3Ddata(); %AC
                otherwise
                    error('illegal choice')
            end
            % Individual plots?
            switch get(hLRmethodplots,'value')
                case 1
                    NmrData.locodosyopts(4)=1;
                case 0
                    NmrData.locodosyopts(4)=0;
            end
            % find the dimensions of the spectrum
            speclim=xlim(hAxes);
            if speclim(1)<NmrData.sp
                speclim(1)=NmrData.sp;
            end
            if speclim(2)>(NmrData.sw+NmrData.sp)
                speclim(2)=(NmrData.sw+NmrData.sp);
            end
            NmrData.LRRegionData=get(hRegionsTable,'Data');
            NmrData.numcomp=NmrData.LRRegionData';
            NmrData.xlim(1)=speclim(1);
            NmrData.xlim(2)=speclim(2);
            %call the locodosy_mn m-file to perform LRSCORE on each window selected
            NmrData.locodosydata=locodosy(NmrData.pfgnmrdata,NmrData.numcomp,...
                NmrData.nwin,speclim,NmrData.locodosyopts,NmrData.th,NmrData.nug,...
                NmrData.winstart,NmrData.winend,NmrData.Dlimit,NmrData.minpercent,...
                NmrData.DiffRes);
            NmrData.LRRegionData=NmrData.locodosydata.newnumcomp;
            set(hRegionsTable,'Data', NmrData.LRRegionData)
            % call the combine1dscore m-file to find similarly diffusing species between
            % windows and build component spectra

            %MN 28 Mar 2025. CLusetring not working and I don't have time to fix (not important) so I disable for now. 

            % UseClustering=get(hUseClustering,'value');
            % if UseClustering==1
            %     NmrData.locodosydata=combine1dlocodosy(NmrData.locodosydata...
            %         .components,NmrData.nwin,NmrData.fn,NmrData.locodosydata...
            %         ,NmrData.winstart,NmrData.winend,NmrData.locodosydata.sderrcell...
            %         ,NmrData.sderrmultiplier);
            %     % call the locodosyplot m-file to plot these 1D spectra in one figure and a
            %     % pseudo 2d plot in another figure. This returns data on which windows are
            %     % used in which spectrum for the highlighting of where a synthetic 0
            %     % baseline has been added to component spectra.
            %     NmrData.locodosydata.zerolines=locodosyplot(NmrData.locodosydata,NmrData.fn);
            %     guidata(hMainFigure,NmrData);
            % else
            %     %don't use clustering
            % end
        end
        
    end
    function plotlocodosy(~,~)
        NmrData=guidata(hMainFigure);
        dosyplot_gui(NmrData.locodosydata);
    end
%----ILT-----
    function DoILT(~,~)
        %Prepare the data for ILT analysis
        NmrData=guidata(hMainFigure);
        
       % RegLambda=1;
        %ILTOpts=[0 0 0 0];
        RegLambda = str2double(get(hEditLamda,'String'));
        switch get(hBGroupILTRegMet,'SelectedObject')
            case hRadio1ILTRegMet
                RegularisationMethod=0;
            case hRadio2ILTRegMet
                RegularisationMethod=1;
            otherwise
                error('illegal choice')
        end
        
        switch get(hBGroupILTOptimLambda,'SelectedObject')
            case hRadio1ILTILTOptimLambd
                OptimLambda=0; %manual
            case hRadio2ILTILTOptimLambd
                OptimLambda=1; %l-curve
            case hRadio3ILTILTOptimLambd
                OptimLambda=2; %gcv
            otherwise
                error('illegal choice')
        end
        
        switch get(hBGroupILTSmooth,'SelectedObject')
            case hRadio1ILTILTSmooth
                Smooth=0; %No smoothing
            case hRadio2ILTILTOptiSmooth
                Smooth=1; %first derivative
            case hRadio3ILTILTOptimSmooth
                Smooth=2; %second derivative
            otherwise
                error('illegal choice')
        end
        
        switch get(hBGroupILTConstrain,'SelectedObject')
            case hRadio1ILTConstrain
                Constraint=0; %No constraint
            case hRadio2ILTConstrain
                Constraint=1; %Non-negativity
            otherwise
                error('illegal choice')
        end
        ILTOpts=[RegularisationMethod OptimLambda Smooth Constraint RegLambda];
        diffrange=[0 20 256];
        diffrange(1)=str2double(get(hEditDminILT,'String'));
        diffrange(2)=str2double(get(hEditDmaxILT,'String'));
        diffrange(3)=str2double(get(hEditDresILT,'String'));
        
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        switch get(hBGroupILTOpt1,'SelectedObject')
            case hRadio1ILTOpt1
                PeakPick=0; %all data points
            case hRadio2ILTOpt1
                PeakPick=1; %peak picking
            case hRadio3ILTOpt1 %
                PeakPick=2; %Integrals
                NmrData.pfgnmrdata.integral_peaks=NmrData.integral_peaks;
                for m=1:NmrData.pfgnmrdata.ngrad
                    RealSpec=real(NmrData.pfgnmrdata.SPECTRA(:,m));
                    for k=1:numel(NmrData.integral_peaks)
                        Start=NmrData.integral_peaks(k).startIndex;
                        Stop=NmrData.integral_peaks(k).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            Offset=NmrData.integral_peaks(k).Offset;
                            Tilt=NmrData.integral_peaks(k).Tilt;
                        else
                            Offset=NmrData.integral_peaks(k).Individual(m).Offset;
                            Tilt=NmrData.integral_peaks(k).Individual(m).Tilt;
                        end
                        %spectra has been normalized in PreparePfgnmrdata()
                        Offset=Offset/ NmrData.pfgnmrdata.normfac;
                        Tilt=Tilt/ NmrData.pfgnmrdata.normfac;
                        tmp=0:(Stop-Start);
                        tmp=(Tilt*tmp)/tmp(end);
                        TiltLine=tmp(:);
                        IntPeak=sum(RealSpec(Start:Stop)-Offset - TiltLine);
                        NmrData.pfgnmrdata.integral_peaks(k).Value(m)=IntPeak;
                        
                    end
                end
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupDOSYOpt2,'SelectedObject')
            case hRadio1DOSYOpt2
                nugflag=0;
            case hRadio2DOSYOpt2
                nugflag=1;
            otherwise
                error('illegal choice')
        end
        
        
        NmrData.ILTdata=ILT_mn(NmrData.pfgnmrdata,PeakPick,NmrData.th,speclim,diffrange,ILTOpts,nugflag,NmrData.nug);
        
        %print out statistics to file
        DTpath=which('GNAT');
        DTpath=DTpath(1:(end-6));
        statfil=fopen([DTpath 'dosystats.txt'], 'wt');
        fprintf(statfil,'%-s  \n','Fitting statistics for a 2D DOSY ILT experiment');
        if nugflag==0
            fprintf(statfil,'%-s  \n','Pure exponential fitting (Stejskal-Tanner equation)');
        elseif nugflag==1
            fprintf(statfil,'\n');
            fprintf(statfil,'%-s  \n','Fitting using compensation for non-uniform field gradients (NUG). ');
        else
            fprintf(statfil,'%-s  \n','Unknown function');
        end
        
        switch RegularisationMethod
            case 0
                fprintf(statfil,'%-s  \n','Not regularised');
            case 1
                fprintf(statfil,'%-s  \n','Tikhonov regularisation');
            otherwise
                fprintf(statfil,'%-s  \n','Unknown regularisation');
        end
        
        switch OptimLambda
            case 0
                fprintf(statfil,'%-s  \n','manual lambda'); %manual
            case 1
                fprintf(statfil,'%-s  \n','lambda estimated by l-curve'); %manual %l-curve
            case 2
                fprintf(statfil,'%-s  \n','lambda estimated by gcv'); %manual; %gcv
            otherwise
                fprintf(statfil,'%-s  \n','Unknown lambda estimation'); %second derivative
        end
        
        
        switch Smooth
            case 0
                fprintf(statfil,'%-s  \n','No smoothing');
                %No smoothing
            case 1
                fprintf(statfil,'%-s  \n','First derivative smoothing'); %first derivative
            case 2
                fprintf(statfil,'%-s  \n','Second derivative smoothing'); %second derivative
            otherwise
                fprintf(statfil,'%-s  \n','Unknown smoothing'); %second derivative
        end
        
        
        
        switch Constraint
            case 0
                fprintf(statfil,'%-s  \n','No constraint');  %No constraint
            case 1
                fprintf(statfil,'%-s  \n','Non-negativity constraint') ; %Non-negativity
            otherwise
                fprintf(statfil,'%-s  \n','Unknown constraint') ; %Non-negativity
        end
        
        fitsize=size(NmrData.ILTdata.FITSTATS);
        fprintf(statfil,'\n');
        fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
        fprintf(statfil,'\n');
        fprintf(statfil,'%-10s  ','Frequency');
        fprintf(statfil,'%-10s  %-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Exp. Ampl','Fit. Ampl');
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.freqs(k));
            fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.ORIGINAL(k,1));
            fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.FITTED(k,1));
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s%s%s \n','Gradient amplitudes [', num2str(numel(NmrData.ILTdata.Gzlvl)), ']  (T m^-2)');
        for g=1:numel(NmrData.ILTdata.Gzlvl)
            fprintf(statfil,'%-10.5e  \n',NmrData.ILTdata.Gzlvl(g));
        end
        fprintf(statfil,'\n%s%s%s \n','*******Residuals*******');
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-10s %-10.0f %-10s %-10.5f \n','Peak Nr: ', k, 'Frequency (ppm): ',NmrData.ILTdata.freqs(k));
            fprintf(statfil,'%-10s   %-10s   %-10s  \n','Exp. Ampl','Fit. Ampl','Diff');
            for m=1:numel(NmrData.ILTdata.Gzlvl)
                fprintf(statfil,'%-10.5e  %-10.5e  %-10.5e  \n',NmrData.ILTdata.ORIGINAL(k,m),NmrData.ILTdata.FITTED(k,m),NmrData.ILTdata.RESIDUAL(k,m));
            end
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
        fprintf(statfil,'\n');
        fprintf(statfil,'%-10s  ','Frequency');
        fprintf(statfil,'\n');
        fprintf(statfil,'%-10s  ','Frequency');
        fprintf(statfil,'%-10s  %-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Exp. Ampl','Fit. Ampl');
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.freqs(k));
            fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.ORIGINAL(k,1));
            fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.FITTED(k,1));
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s\n%s\n','This information can be found in:',[DTpath 'dosystats.txt']);
        fclose(statfil);
        
        guidata(hMainFigure,NmrData)
    end
    function plotILT(~,~)
        dosyplot_gui(NmrData.ILTdata);
    end
    function CheckDmaxILT_Callback(~, ~)
        if get(hCheckDmaxILT,'Value')
            set(hEditDmaxILT,'Enable','Off')
        else
            set(hEditDmaxILT,'Enable','On')
        end
    end
%----DECRA-------
    function dodecra(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        NmrData.ncomp=str2double(get(hEditNcompDECRA,'String'));
        str2double(get(hEditNcompDECRA,'String'))
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        NmrData.decradata=decra_mn(NmrData.pfgnmrdata,NmrData.ncomp,speclim);
        guidata(hMainFigure,NmrData);
    end
    function plotdecra(~,~)
        NmrData=guidata(hMainFigure);
        decraplot(NmrData.decradata);
    end



%% ---------Relaxation Tab Callbacks

%----T1/T2-----
    function doT1(~,~)
        NmrData=guidata(hMainFigure);
        pfgnmrdata=PreparePfgnmrdata();
        Opts=[ 0 0 0 0];
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        %pfgnmrdata.flipnr=NmrData.flipnr;
        button_state = get(hCheckT1limits,'Value');
        T1range=[0 10 256];
        T1range(3)=str2double(get(hEditT1res,'String'));
        if button_state == 1
            T1range(1)=0;
            T1range(2)=0;
        elseif button_state == 0
            T1range(1)=str2double(get(hEditT1min,'String'));
            T1range(2)=str2double(get(hEditT1max,'String'));
        end
        switch get(hBGroupT1Opt1,'SelectedObject') %Peak picking options
            case hRadio1T1Opt1 %Peak pick
                Opts(1)=0;
            case hRadio2T1Opt1 %All freq
                Opts(1)=1;
            case hRadio3T1Opt1 %Integrals
                %GDP 15 August 2017
                Opts(1)=2;
                pfgnmrdata.integral_peaks=NmrData.integral_peaks;
                for m=1:pfgnmrdata.ngrad
                    RealSpec=real(pfgnmrdata.SPECTRA(:,m));
                    for k=1:numel(pfgnmrdata.integral_peaks)
                        %Offset=0;
                        %Tilt=0;
                        Start=pfgnmrdata.integral_peaks(k).startIndex;
                        Stop=pfgnmrdata.integral_peaks(k).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            Offset=pfgnmrdata.integral_peaks(k).Offset;
                            Tilt=pfgnmrdata.integral_peaks(k).Tilt;
                        else
                            Offset=pfgnmrdata.integral_peaks(k).Individual(m).Offset;
                            Tilt=pfgnmrdata.integral_peaks(k).Individual(m).Tilt;
                        end
                        Offset=Offset/ pfgnmrdata.normfac;
                        Tilt=Tilt/ pfgnmrdata.normfac;
                        tmp=0:(Stop-Start);
                        tmp=(Tilt*tmp)/tmp(end);
                        TiltLine=tmp(:);
                        IntPeak=sum(RealSpec(Start:Stop)-Offset - TiltLine);
                        pfgnmrdata.integral_peaks(k).Value(m)=IntPeak;                       
                    end
                    
                end
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupT1Opt2,'SelectedObject')
            case hRadio1T1Opt2
                %T1
                guidata(hMainFigure,NmrData); WriteLogDispInfo('T1 (Inversion recovery 3 parameter fit)')
                FitType=1;
                if (NmrData.flipnr<NmrData.arraydim)
                    SVAR=inputdlg('It is normally advisable to use the last spectrum for threshold: do you want to continue with the current one?','Spectrum choice', 1, {'No'});
                    if strcmpi(SVAR,'Yes')
                        %continue
                    elseif isempty(SVAR) || strcmpi(SVAR,'No')|| strcmpi(SVAR,'')
                        WriteLogDispInfo('Aborting T1 fitting')
                        return
                    else
                        error('Aborting T1 fitting')
                    end
                end
            case hRadio2T1Opt2
                %T1
                guidata(hMainFigure,NmrData); WriteLogDispInfo('T1 (Saturation recovery 3 parameter fit)')
                FitType=2;
                if (NmrData.flipnr<NmrData.arraydim)
                    SVAR=inputdlg('It is normally advisable to use the last spectrum for threshold: do you want to continue with the current one?','Spectrum choice', 1, {'No'});
                    
                    if strcmpi(SVAR,'Yes')
                        %continue
                    else
                        error('Aborting T1 fitting')
                    end
                end
            case hRadio3T1Opt2
                %T2
                guidata(hMainFigure,NmrData); WriteLogDispInfo('T2 (2 parameter fit)')
                FitType=3;
            otherwise
                guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown selection of relaxation fitting')
        end
        % a=NmrData.th
        NmrData.t1data.FitType=FitType;
        NmrData.pfgnmrdata=pfgnmrdata;
        if get(hBGroupT1Opt3,'SelectedObject')==hRadio1T1Opt3
        else
            Opts(2)=1;
            Opts(3)=str2double(get(hEditMultexpR,'String'));
            Opts(4)=str2double(get(hEditTriesR,'String'));
        end
        


        NmrData.t1data=t1_mn(pfgnmrdata,NmrData.th,speclim,T1range,FitType,Opts);
        dosyplot_gui(NmrData.t1data);
        %print out statistics to file
        DTpath=which('GNAT');
        DTpath=DTpath(1:(end-6));
        if FitType==1
            %statfil=fopen([DTpath 't1stats.txt'], 'wt');
            relaxfil=[DTpath 'relaxationstats.txt'];
        elseif FitType==2
            relaxfil=[DTpath 'relaxationstats.txt'];
        elseif FitType==3
            % statfil=fopen([DTpath 't2stats.txt'], 'wt');
            relaxfil=[DTpath 'relaxationstats.txt'];
        else
            error('unknown FitType')
        end
        statfil=fopen(relaxfil,'wt');
        
        fprintf(statfil,'%-s  \n','********************************************************');
        fprintf(statfil,'%-s  \n','Fitting statistics for a T1/T2 experiment');
        if FitType==1
            fprintf(statfil,'%-s  \n','T1 inversion recovery');
            fprintf(statfil,'%-s  \n','T1 exponential fitting M(t) = (M(0) - M0)*exp(-t/T1)');
        elseif FitType==2
            fprintf(statfil,'%-s  \n','T1 saturation recovery');
            fprintf(statfil,'%-s  \n','T1 exponential fitting M(t) = (M(0) - M0)*exp(-t/T1)');
        elseif FitType==3
            fprintf(statfil,'%-s  \n','T2 CPMG or PROJECT');
            fprintf(statfil,'%-s  \n','T2 exponential fitting M(t) = M(0)*exp(-t/T2);');
        else
            error('unknown FitType')
        end
        fitsize=size(NmrData.t1data.FITSTATS);
        fprintf(statfil,'\n');
        fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
        fprintf(statfil,'\n');
        fprintf(statfil,'%-13s  ','Frequency');
        fprintf(statfil,'%-13s','Exp. M(0)');
        
        if FitType==1
            fprintf(statfil,'%-13s  %-17s  %-13s  %-13s %-13s  %-13s ','Fit. -M0','error','Fit. M0','error','T1','error');
        elseif FitType==2
            fprintf(statfil,'%-13s  %-13s  %-13s  %-13s ','Fit. M0','error','T1','error');
        elseif FitType==3
             for m=1:fitsize(2)/4
                fprintf(statfil,'%-8s%-5i  %-15s  %-3s%-10i  %-13s','Fit. M0',m,'error','T2',m,'error');
            end
        else
            error('unknown FitType')
        end
        %  fprintf(statfil,'%-13s  %-13s  %-13s  %-13s  %-13s %-13s %-13s ','Exp. M(0)','Fit. M(0)','error','Fit. M0','error','T1/T2','error');
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-13.5f  ',NmrData.t1data.freqs(k));
            fprintf(statfil,'%-13.5f  ',NmrData.t1data.ORIGINAL(k,1));
            for m=1:fitsize(2)
                fprintf(statfil,'%-13.5f  ',NmrData.t1data.FITSTATS(k,m));
            end
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s%s%s \n','Tau values [', num2str(numel(NmrData.t1data.d2)), ']  (s)');
        for g=1:numel(NmrData.t1data.d2)
            fprintf(statfil,'%-10.5f  \n',NmrData.t1data.d2(g));
        end
        if Opts(1)==2 %Integrals
            fprintf(statfil,'\n%s%s%s \n','*******Integral Regions Set *******');
            fprintf(statfil,'\n');
            fprintf(statfil,'%-10s  %-10s  %-10s  \n','Start','Stop','Centre');
            
            for g=1:numel(NmrData.pfgnmrdata.integral_peaks)
                fprintf(statfil,'%-10.5f  %-10.5f %-10.5f \n',NmrData.pfgnmrdata.integral_peaks(g).start,...
                    NmrData.pfgnmrdata.integral_peaks(g).stop, NmrData.pfgnmrdata.integral_peaks(g).max);
            end
        end
        fprintf(statfil,'\n%s%s%s \n','*******Residuals*******');
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-10s %-10.0f %-10s %-10.5f \n','Peak Nr: ', k, 'Frequency (ppm): ',NmrData.t1data.freqs(k));
            fprintf(statfil,'%-10s   %-10s   %-10s  \n','Exp. Ampl','Fit. Ampl','Diff');
            for m=1:numel(NmrData.t1data.d2)
                fprintf(statfil,'%-10.5e  %-10.5e  %-10.5e  \n',NmrData.t1data.ORIGINAL(k,m),NmrData.t1data.FITTED(k,m),NmrData.t1data.RESIDUAL(k,m));
            end
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
        fprintf(statfil,'\n');
        fprintf(statfil,'%-13s  ','Frequency');
        fprintf(statfil,'%-13s','Exp. M(0)');
        
         if FitType==1
            fprintf(statfil,'%-13s  %-17s  %-13s  %-13s %-13s  %-13s ','Fit. -M0','error','Fit. M0','error','T1','error');
        
        elseif FitType==2
            fprintf(statfil,'%-13s  %-13s  %-13s  %-13s ','Fit. M0','error','T1','error');
        elseif FitType==3
             for m=1:fitsize(2)/4
                fprintf(statfil,'%-8s%-5i  %-15s  %-3s%-10i  %-13s','Fit. M0',m,'error','T2',m,'error');
            end
        else
            error('unknown FitType')
        end
        %  fprintf(statfil,'%-13s  %-13s  %-13s  %-13s  %-13s %-13s %-13s ','Exp. M(0)','Fit. M(0)','error','Fit. M0','error','T1/T2','error');
        fprintf(statfil,'\n');
        for k=1:fitsize(1)
            fprintf(statfil,'%-13.5f  ',NmrData.t1data.freqs(k));
            fprintf(statfil,'%-13.5f  ',NmrData.t1data.ORIGINAL(k,1));
            for m=1:fitsize(2)
                fprintf(statfil,'%-13.5f  ',NmrData.t1data.FITSTATS(k,m));
            end
            fprintf(statfil,'\n');
        end
        fprintf(statfil,'%-s  \n','********************************************************');
        fprintf(statfil,'%-s  \n','Fitting statistics for a T1/T2 experiment');
        if FitType==1
            fprintf(statfil,'%-s  \n','T1 inversion recovery');
            fprintf(statfil,'%-s  \n','T1 exponential fitting M(t) = (M(0) - M0)*exp(-t/T1)');
        elseif FitType==2
            fprintf(statfil,'%-s  \n','T1 saturation recovery');
            fprintf(statfil,'%-s  \n','T1 exponential fitting M(t) = (M(0) - M0)*exp(-t/T1)');
        elseif FitType==3
            fprintf(statfil,'%-s  \n','T2 CPMG or PROJECT');
            fprintf(statfil,'%-s  \n','T2 exponential fitting M(t) = M(0)*exp(-t/T2);');
        else
            error('unknown FitType')
        end
        fprintf(statfil,'\n%s\n%s\n','This information can be found in:',relaxfil);
        fclose(statfil);
        type(relaxfil);
        guidata(hMainFigure,NmrData);
    end

    function plotT1(~,~)
        dosyplot_gui(NmrData.t1data);
    end
    function CheckT1limits_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hCheckT1limits,'Value');
        if button_state == 1
            set(hEditT1max,'Enable','Off')
            set(hEditT1min,'Enable','Off')
        elseif button_state == 0
            set(hEditT1max,'Enable','On')
            set(hEditT1min,'Enable','On')
        end
    end
%     function EditT1res_Callback( eventdata, handles)
%     end
%     function EditT1max_Callback( eventdata, handles)
%     end
%     function EditT1min_Callback( eventdata, handles)
%     end
    function FitTypeROSY_Callback(~, ~)
        if get(hBGroupT1Opt3,'SelectedObject')==hRadio1T1Opt3
            %monoexponetial fit
            set(hEditMultexpR,'Enable','Off')
            set(hEditMultexpR,'string',num2str(1))
            set(hEditTriesR,'Enable','Off')
            set(hEditTriesR,'string',num2str(100))
        else
            %multiexponential
            set(hEditMultexpR,'Enable','On')
            set(hEditTriesR,'Enable','On')
        end
    end
%----SCORE (relaxation) ------------------
    function dorscore(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        NmrData.RSCOREopts=[0 0 0 0 0 0];
        switch get(hBGroupRSCOREOpt1,'SelectedObject')
            case hRadio1RSCOREOpt1
                NmrData.RSCOREopts(3)=0;
            case hRadio2RSCOREOpt1
                NmrData.RSCOREopts(3)=1;
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupRSCOREOpt2,'SelectedObject')
            case hRadio1RSCOREOpt2
                NmrData.RSCOREopts(1)=0;
            case hRadio2RSCOREOpt2
                NmrData.RSCOREopts(1)=1;
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupRSCOREOpt3,'SelectedObject')
            case hRadio1RSCOREOpt3
                NmrData.RSCOREopts(2)=0;
            case hRadio2RSCOREOpt3
                NmrData.RSCOREopts(2)=1;
            case hRadio4RSCOREOpt3
                NmrData.RSCOREopts(2)=3;
            otherwise
                error('illegal choice')
        end
        switch get(hBGroupRSCOREOpt6,'SelectedObject')
            case hRadio1RSCOREOpt6
                NmrData.RSCOREopts(6)=0;
            case hRadio2RSCOREOpt6
                NmrData.RSCOREopts(6)=1;
            otherwise
                error('illegal choice')
        end
        
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        
        NmrData.ncomp=str2double(get(hEditNcompRSCORE,'String'));
        
        NmrData.rscoredata=rscore_mn(NmrData.pfgnmrdata, NmrData.ncomp, speclim,NmrData.RSCOREopts);
        guidata(hMainFigure,NmrData);
    end
    function plotrscore(~,~)
        NmrData=guidata(hMainFigure);
        rscoreplot(NmrData.rscoredata);
    end
    function pubplotrscore(~,~)
        NmrData=guidata(hMainFigure);
        rscoreplotpub(NmrData.rscoredata);
    end
%----RILT-----
%     function DoRILT(source,eventdata)
%         %Prepare the data for ILT analysis
%         NmrData=guidata(hMainFigure);
%         
%         % RegLambda=1;
%         %ILTOpts=[0 0 0 0];
%         RegLambda = str2double(get(hEditRLamda,'String'));
%         switch get(hBGroupRILTRegMet,'SelectedObject')
%             case hRadio1RILTRegMet
%                 RegularisationMethod=0;
%             case hRadio2RILTRegMet
%                 RegularisationMethod=1;
%             otherwise
%                 error('illegal choice')
%         end
%         
%         switch get(hBGroupRILTOptimLambda,'SelectedObject')
%             case hRadio1RILTILTOptimLambd
%                 OptimLambda=0; %manual
%             case hRadio2RILTILTOptimLambd
%                 OptimLambda=1; %l-curve
%             case hRadio3RILTILTOptimLambd
%                 OptimLambda=2; %gcv
%             otherwise
%                 error('illegal choice')
%         end
%         
%         switch get(hBGroupRILTSmooth,'SelectedObject')
%             case hRadio1RILTILTSmooth
%                 Smooth=0; %No smoothing
%             case hRadio2RILTILTOptiSmooth
%                 Smooth=1; %first derivative
%             case hRadio3RILTILTOptimSmooth
%                 Smooth=2; %second derivative
%             otherwise
%                 error('illegal choice')
%         end
%         
%         switch get(hBGroupRILTConstrain,'SelectedObject')
%             case hRadio1RILTConstrain
%                 Constraint=0; %No constraint
%             case hRadio2RILTConstrain
%                 Constraint=1; %Non-negativity
%             otherwise
%                 error('illegal choice')
%         end
%         ILTOpts=[RegularisationMethod OptimLambda Smooth Constraint RegLambda];
%         diffrange=[0 20 256];
%         diffrange(1)=str2double(get(hEditRminRILT,'String'));
%         diffrange(2)=str2double(get(hEditRmaxRILT,'String'));
%         diffrange(3)=str2double(get(hEditRresRILT,'String'));
%         
%         speclim=xlim(hAxes);
%         if speclim(1)<NmrData.sp
%             speclim(1)=NmrData.sp;
%         end
%         if speclim(2)>(NmrData.sw+NmrData.sp)
%             speclim(2)=(NmrData.sw+NmrData.sp);
%         end
%         NmrData.pfgnmrdata=PreparePfgnmrdata();
%         switch get(hBGroupRILTOpt2,'SelectedObject')
%             case hRadio1RILTOpt2
%                 fittype=0; %T1 inv rec
%             case hRadio2RILTOpt2
%                 fittype=1; %T1 sat rec
%             case hRadio3RILTOpt2 %
%                 fittype=2; %T2 cpmg/proj
%         end
%         switch get(hBGroupRILTOpt1,'SelectedObject')
%             case hRadio1RILTOpt1
%                 PeakPick=0; %all data points
%             case hRadio2RILTOpt1
%                 PeakPick=1; %peak picking
%             case hRadio3RILTOpt1 %
%                 PeakPick=2; %Integrals
%                 NmrData.pfgnmrdata.integral_peaks=NmrData.integral_peaks;
%                 for m=1:NmrData.pfgnmrdata.ngrad
%                     RealSpec=real(NmrData.pfgnmrdata.SPECTRA(:,m));
%                     for k=1:numel(NmrData.integral_peaks)
%                         Start=NmrData.integral_peaks(k).startIndex;
%                         Stop=NmrData.integral_peaks(k).stopIndex;
%                         if get(hRadioScopeGlobalInt,'Value')
%                             Offset=NmrData.integral_peaks(k).Offset;
%                             Tilt=NmrData.integral_peaks(k).Tilt;
%                         else
%                             Offset=NmrData.integral_peaks(k).Individual(m).Offset;
%                             Tilt=NmrData.integral_peaks(k).Individual(m).Tilt;
%                         end
%                         %spectra has been normalized in PreparePfgnmrdata()
%                         Offset=Offset/ NmrData.pfgnmrdata.normfac;
%                         Tilt=Tilt/ NmrData.pfgnmrdata.normfac;
%                         tmp=0:(Stop-Start);
%                         tmp=(Tilt*tmp)/tmp(end);
%                         TiltLine=tmp(:);
%                         IntPeak=sum(RealSpec(Start:Stop)-Offset - TiltLine);
%                         NmrData.pfgnmrdata.integral_peaks(k).Value(m)=IntPeak;
%                         
%                     end
%                 end
%             otherwise
%                 error('illegal choice')
%         end
%         switch get(hBGroupDOSYOpt2,'SelectedObject')
%             case hRadio1DOSYOpt2
%                 nugflag=0;
%             case hRadio2DOSYOpt2
%                 nugflag=1;
%             otherwise
%                 error('illegal choice')
%         end
%         
%         
%         NmrData.ILTdata=ILT_mn(NmrData.pfgnmrdata,PeakPick,NmrData.th,speclim,diffrange,ILTOpts,nugflag,NmrData.nug);
%         
%         %print out statistics to file
%         DTpath=which('GNAT');
%         DTpath=DTpath(1:(end-6));
%         statfil=fopen([DTpath 'relaxationstats.txt'], 'wt');
%         fprintf(statfil,'%-s  \n','Fitting statistics for a 2D ROSY ILT experiment');
%         if nugflag==0
%             fprintf(statfil,'%-s  \n','Pure exponential fitting (Stejskal-Tanner equation)');
%         elseif nugflag==1
%             fprintf(statfil,'\n');
%             fprintf(statfil,'%-s  \n','Fitting using compensation for non-uniform field gradients (NUG). ');
%         else
%             fprintf(statfil,'%-s  \n','Unknown function');
%         end
%         
%         switch RegularisationMethod
%             case 0
%                 fprintf(statfil,'%-s  \n','Not regularised');
%             case 1
%                 fprintf(statfil,'%-s  \n','Tikhonov regularisation');
%             otherwise
%                 fprintf(statfil,'%-s  \n','Unknown regularisation');
%         end
%         
%         switch OptimLambda
%             case 0
%                 fprintf(statfil,'%-s  \n','manual lambda'); %manual
%             case 1
%                 fprintf(statfil,'%-s  \n','lambda estimated by l-curve'); %manual %l-curve
%             case 2
%                 fprintf(statfil,'%-s  \n','lambda estimated by gcv'); %manual; %gcv
%             otherwise
%                 fprintf(statfil,'%-s  \n','Unknown lambda estimation'); %second derivative
%         end
%         
%         
%         switch Smooth
%             case 0
%                 fprintf(statfil,'%-s  \n','No smoothing');
%                 %No smoothing
%             case 1
%                 fprintf(statfil,'%-s  \n','First derivative smoothing'); %first derivative
%             case 2
%                 fprintf(statfil,'%-s  \n','Second derivative smoothing'); %second derivative
%             otherwise
%                 fprintf(statfil,'%-s  \n','Unknown smoothing'); %second derivative
%         end
%         
%         
%         
%         switch Constraint
%             case 0
%                 fprintf(statfil,'%-s  \n','No constraint');  %No constraint
%             case 1
%                 fprintf(statfil,'%-s  \n','Non-negativity constraint') ; %Non-negativity
%             otherwise
%                 fprintf(statfil,'%-s  \n','Unknown constraint') ; %Non-negativity
%         end
%         
%         fitsize=size(NmrData.ILTdata.FITSTATS);
%         fprintf(statfil,'\n');
%         fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
%         fprintf(statfil,'\n');
%         fprintf(statfil,'%-10s  ','Frequency');
%         fprintf(statfil,'%-10s  %-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Exp. Ampl','Fit. Ampl');
%         fprintf(statfil,'\n');
%         for k=1:fitsize(1)
%             fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.freqs(k));
%             fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.ORIGINAL(k,1));
%             fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.FITTED(k,1));
%             fprintf(statfil,'\n');
%         end
%         fprintf(statfil,'\n%s%s%s \n','Gradient amplitudes [', num2str(numel(NmrData.ILTdata.Gzlvl)), ']  (T m^-2)');
%         for g=1:numel(NmrData.ILTdata.Gzlvl)
%             fprintf(statfil,'%-10.5e  \n',NmrData.ILTdata.Gzlvl(g));
%         end
%         fprintf(statfil,'\n%s%s%s \n','*******Residuals*******');
%         fprintf(statfil,'\n');
%         for k=1:fitsize(1)
%             fprintf(statfil,'%-10s %-10.0f %-10s %-10.5f \n','Peak Nr: ', k, 'Frequency (ppm): ',NmrData.ILTdata.freqs(k));
%             fprintf(statfil,'%-10s   %-10s   %-10s  \n','Exp. Ampl','Fit. Ampl','Diff');
%             for m=1:numel(NmrData.ILTdata.Gzlvl)
%                 fprintf(statfil,'%-10.5e  %-10.5e  %-10.5e  \n',NmrData.ILTdata.ORIGINAL(k,m),NmrData.ILTdata.FITTED(k,m),NmrData.ILTdata.RESIDUAL(k,m));
%             end
%             fprintf(statfil,'\n');
%         end
%         fprintf(statfil,'\n%s%s%s \n','*******Fit Summary*******');
%         fprintf(statfil,'\n');
%         fprintf(statfil,'%-10s  ','Frequency');
%         fprintf(statfil,'\n');
%         fprintf(statfil,'%-10s  ','Frequency');
%         fprintf(statfil,'%-10s  %-9s%-1.1i  %-10s  %-9s%-1.1i  %-10s  ','Exp. Ampl','Fit. Ampl');
%         fprintf(statfil,'\n');
%         for k=1:fitsize(1)
%             fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.freqs(k));
%             fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.ORIGINAL(k,1));
%             fprintf(statfil,'%-10.5f  ',NmrData.ILTdata.FITTED(k,1));
%             fprintf(statfil,'\n');
%         end
%         fprintf(statfil,'\n%s\n%s\n','This information can be found in:',[DTpath 'dosystats.txt']);
%         fclose(statfil);
%         
%         guidata(hMainFigure,NmrData)
%     end
%     function plotRILT(source,eventdata)
%         dosyplot_gui(NmrData.RILTdata);
%     end
%     function CheckRmaxRILT_Callback(eventdata, handles)
%         if get(hCheckRmaxRILT,'Value')
%             set(hEditRmaxRILT,'Enable','Off')
%         else
%             set(hEditRmaxRILT,'Enable','On')
%         end
%     end
%% ---------Analysis Tab Callbacks
%----Analyze-----
    function AnalyzeFreqButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        input.thresflag=1;
        analyzedata=PrepareAnalyzeData(input);
        
        freq=zeros(1,analyzedata.arraydim);
        for narray=1:analyzedata.arraydim
            th=100*NmrData.thresydata(1)/max(real(analyzedata.SPECTRA(:,analyzedata.increments(narray))));
            [peaks]=peakpick_mn(real(analyzedata.SPECTRA(:,analyzedata.increments(narray))),th);
            if isempty(peaks)
                freq(narray)=0;
            else
                amp=analyzedata.SPECTRA(peaks(1).max,analyzedata.increments(narray));
                ampmax=1;
                for k=1:length(peaks)
                    testamp=analyzedata.SPECTRA(peaks(k).max,analyzedata.increments(narray));
                    if testamp>amp
                        ampmax=k;
                    end
                end
                freq(narray)=analyzedata.Ppmscale(peaks(ampmax).max);
            end
        end
        
        analyze.type='Frequency';
        analyze.title={'','Analyse frequency',''};
        analyze.data=freq;
        analyze.xscale=analyzedata.increments;
        analyze.xlabel='Increment number';
        switch NmrData.shiftunits
            case 'ppm'
                analyze.data= analyze.data.*NmrData.sfrq;
            case 'Hz'
                             
            otherwise
                error('illegal choice')
        end
        
        analyze.ylabel='Frequency / Hz';
        clear analyzedata
        
        PlotAnalyze(analyze);
        guidata(hMainFigure,NmrData);
    end
    function AnalyzeAmpButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        input.thresflag=1;
        analyzedata=PrepareAnalyzeData(input);
        
        freq=zeros(1,analyzedata.arraydim);
        amparray=zeros(1,analyzedata.arraydim);
        for narray=1:analyzedata.arraydim
            th=100*NmrData.thresydata(1)/max(real(analyzedata.SPECTRA(:,analyzedata.increments(narray))));
            [peaks]=peakpick_mn(real(analyzedata.SPECTRA(:,analyzedata.increments(narray))),th);
            if isempty(peaks)
                freq(narray)=0;
                amparray(narray)=0;
            else
                amp=analyzedata.SPECTRA(peaks(1).max,analyzedata.increments(narray));
                ampmax=1;
                
                for k=1:length(peaks)
                    testamp=analyzedata.SPECTRA(peaks(k).max,analyzedata.increments(narray));
                    if testamp>amp
                        ampmax=k;
                    end
                end
                freq(narray)=analyzedata.Ppmscale(peaks(ampmax).max);
                amparray(narray)=real(analyzedata.SPECTRA(peaks(ampmax).max,analyzedata.increments(narray)));
            end
        end
        
        analyze.type='Apmlitude';
        analyze.title={'','Analyse amplitude',''};
        analyze.data=amparray;
        analyze.xscale=analyzedata.increments;
        analyze.xlabel='Increment number';
        analyze.ylabel='Peak amplitude';
        clear analyzedata
        NmrData.analyze=analyze;
        PlotAnalyze(analyze);
        guidata(hMainFigure,NmrData);
    end
    function AnalyzeTempButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        TempCoeff=(str2double(get(hEditTempCoeff,'string')));
        input.thresflag=1;
        analyzedata=PrepareAnalyzeData(input);
        freq=zeros(1,analyzedata.arraydim);
        Temp=zeros(1,analyzedata.arraydim);
        for narray=1:analyzedata.arraydim
            
            [peaks]=peakpick_mn(analyzedata.SPECTRA(:,analyzedata.increments(narray)),NmrData.th)  ;
            amp=analyzedata.SPECTRA(peaks(1).max,analyzedata.increments(narray));
            ampmax=1;
            for k=1:length(peaks)
                testamp=analyzedata.SPECTRA(peaks(k).max,analyzedata.increments(narray));
                if testamp>amp
                    ampmax=k;
                end
            end
            freq(narray)=analyzedata.Ppmscale(peaks(ampmax).max);
            Temp(narray)=(freq(narray)-freq(1))/TempCoeff;
        end
        analyze.type='Temperature';
        analyze.title={'','Temperaure stability',''};
        analyze.data=Temp;
        analyze.xscale=analyzedata.increments;
        analyze.xlabel='Increment number';
        analyze.ylabel='Temperature change / Kelvin';
        clear analyzedata
        
        PlotAnalyze(analyze);
        guidata(hMainFigure,NmrData);
    end
    function EditTempCoeff_Callback(~,~)
        NmrData=guidata(hMainFigure);
        tmp=(str2double(get(hEditTempCoeff,'string')));
        if isnan(tmp)
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Must be a number defaulting to 1.14e-2')
            set(hEditTempCoeff,'String',num2str(-0.0102))
        end
        guidata(hMainFigure,NmrData);
    end
    function TempTSPButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        set(hEditTempCoeff,'String',num2str(-0.0102))
        guidata(hMainFigure,NmrData);
    end
    function AnalyzeResButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        input.thresflag=1;
        analyzedata=PrepareAnalyzeData(input);
        
        freq=zeros(1,analyzedata.arraydim);
        freqnr=zeros(1,analyzedata.arraydim);
        for narray=1:analyzedata.arraydim
            [peaks]=peakpick_mn(analyzedata.SPECTRA(:,analyzedata.increments(narray)),NmrData.th);
            amp=analyzedata.SPECTRA(peaks(1).max,analyzedata.increments(narray));
            ampmax=1;
            for k=1:length(peaks)
                testamp=analyzedata.SPECTRA(peaks(k).max,analyzedata.increments(narray));
                if testamp>amp
                    ampmax=k;
                end
            end
            freq(narray)=analyzedata.Ppmscale(peaks(ampmax).max);
            freqnr(narray)=peaks(ampmax).max;
        end
        PeakWidth=zeros(1,analyzedata.arraydim);
        for narray=1:analyzedata.arraydim
            PeakWidth(narray)=EstimatePeakshape(analyzedata.SPECTRA(:,analyzedata.increments(narray)),0);
        end
        AveragePeakWidth=sum(PeakWidth)/narray %#ok<NASGU,NOPRT>
        BiggestPeakWidth=max(PeakWidth) %#ok<NASGU,NOPRT>
        LowestPeakWidth=min(PeakWidth) %#ok<NASGU,NOPRT>

                
        analyze.type='Resolution';
        analyze.title={'','Analyse peakshape',''};
        analyze.data=PeakWidth;
        analyze.xscale=analyzedata.increments;
        analyze.xlabel='Increment number';
        analyze.ylabel='Peak width at half height / Hz';
        clear analyzedata
        
        PlotAnalyze(analyze);
        guidata(hMainFigure,NmrData);
    end
    function AnalyzePhaseButton_Callback(~,~)
        %The sum of the positive and negative peaks of a pure Lorentzian close to dispersion mode
        %divided by the difference is approximately equal to the phase deviation from pure dispersion
        %in radians. (Recipe from Ad Bax).
                
        NmrData=guidata(hMainFigure);
        
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh0,'string',num2str(NmrData.rp+90,4))
            case hRadioScopeIndividual
                set(hEditPh0,'string',num2str(NmrData.rpInd+90,4))
        end
        
        EditPh0_Callback();
        input.thresflag=1;
        analyzedata=PrepareAnalyzeData(input);
        freq=zeros(1,analyzedata.arraydim);
        amparray1=zeros(1,analyzedata.arraydim);
        for narray=1:analyzedata.arraydim
            [peaks]=peakpick_mn(analyzedata.SPECTRA(:,analyzedata.increments(narray)),NmrData.th)  ;
            amp=analyzedata.SPECTRA(peaks(1).max,analyzedata.increments(narray));
            ampmax=1;
            for k=1:length(peaks)
                testamp=analyzedata.SPECTRA(peaks(k).max,analyzedata.increments(narray));
                if testamp>amp
                    ampmax=k;
                end
            end
            freq(narray)=analyzedata.Ppmscale(peaks(ampmax).max);
            amparray1(narray)=real(analyzedata.SPECTRA(peaks(ampmax).max,analyzedata.increments(narray)));
        end
        
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh0,'string',num2str(NmrData.rp-180,4))
            case hRadioScopeIndividual
                set(hEditPh0,'string',num2str(NmrData.rpInd-180,4))
        end

        EditPh0_Callback();
        input.thresflag=1;
        analyzedata=PrepareAnalyzeData(input);
        amparray2=zeros(1,analyzedata.arraydim);
        for narray=1:analyzedata.arraydim
            [peaks]=peakpick_mn(analyzedata.SPECTRA(:,analyzedata.increments(narray)),NmrData.th)  ;
            amp=analyzedata.SPECTRA(peaks(1).max,analyzedata.increments(narray));
            ampmax=1;
            for k=1:length(peaks)
                testamp=analyzedata.SPECTRA(peaks(k).max,analyzedata.increments(narray));
                if testamp>amp
                    ampmax=k;
                  %  testamp=amp;
                end
            end
            amparray2(narray)=real(analyzedata.SPECTRA(peaks(ampmax).max,analyzedata.increments(narray)));
        end
        
        tmp1= (amparray2+(-amparray1));
        tmp2=(amparray2-(-amparray1));
        
        phasearray=tmp1./tmp2;
        phasearray=phasearray*180/pi;
                
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                set(hEditPh0,'string',num2str(NmrData.rp+90,4))
            case hRadioScopeIndividual
                set(hEditPh0,'string',num2str(NmrData.rpInd+90,4))
        end
       
        EditPh0_Callback()
        
        analyze.type='Phase';
        analyze.title={'','Analyse phase',''};
        analyze.data=phasearray;
        analyze.xscale=analyzedata.increments;
        analyze.xlabel='Increment number';
        analyze.ylabel='Phase change / Degrees';
        clear analyzedata
        
        PlotAnalyze(analyze);
        
        guidata(hMainFigure,NmrData)
    end
    function AnalyzeIntButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
         input.thresflag=1;
        analyzedata=PrepareAnalyzeData(input);
        
        if numel(NmrData.integral_peaks)~=1
            errordlg('Set one integral region only (using the INTEGRATE controls)');
            return;
        end
        intarray=zeros(1,analyzedata.arraydim);
        for n=1:analyzedata.arraydim
            RealSpec=real(NmrData.SPECTRA(:,n));
            
            Start=NmrData.integral_peaks(1).startIndex;
            Stop=NmrData.integral_peaks(1).stopIndex;
            if get(hRadioScopeGlobalInt,'Value')
                Offset=NmrData.integral_peaks(1).Offset;
                Tilt=NmrData.integral_peaks(1).Tilt;
            else
                Offset=NmrData.integral_peaks(1).Individual(n).Offset;
                Tilt=NmrData.integral_peaks(1).Individual(n).Tilt;
            end
            tmp=0:(Stop-Start);
            tmp=(Tilt*tmp)/tmp(end);
            TiltLine=tmp(:);
            IntPeak=sum(RealSpec(Start:Stop)- Offset - TiltLine);
            intarray(n)=IntPeak;
        end
        
        analyze.type='Integral';
        analyze.title={'','Analyse integral',''};
        analyze.data=intarray;
        analyze.xscale=analyzedata.increments;
        analyze.xlabel='Increment number';
        analyze.ylabel='Integral';
        clear analyzedata
        
        PlotAnalyze(analyze);
        guidata(hMainFigure,NmrData);
    end
    function DSSButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        input.thresflag=0;
        analyzedata=PrepareAnalyzeData(input);

        VertOff=str2double(get(hEditVerticalOffset,'String'));
        HorizOff=str2double(get(hEditHorizontalOffset,'String'));
        Horiz=round(HorizOff*analyzedata.np/100);
        
        plotspec=nan(analyzedata.np+abs(Horiz)*analyzedata.arraydim,analyzedata.arraydim);

        ylimit=ylim();
        for k=1:analyzedata.arraydim
            analyzedata.SPECTRA(analyzedata.SPECTRA(:,k)>ylimit(2),k)=nan;
            analyzedata.SPECTRA(analyzedata.SPECTRA(:,k)<ylimit(1),k)=nan;
        end
        if Horiz<0
            for k=1:analyzedata.arraydim
                plotspec((k-1)*abs(Horiz)+1:analyzedata.np+(k-1)*abs(Horiz),k)=real(analyzedata.SPECTRA(:,analyzedata.increments(k)));
            end
        else
            for k=1:analyzedata.arraydim
                plotspec((k-1)*abs(Horiz)+1:analyzedata.np+(k-1)*abs(Horiz),analyzedata.arraydim-k+1)=real(analyzedata.SPECTRA(:,analyzedata.increments(analyzedata.arraydim-k+1)));
            end
        end
        VertIncr=VertOff*max(max(plotspec))/100;
        for k=1:analyzedata.arraydim
            plotspec(:,k)=plotspec(:,k)+(k-1)*VertIncr;
        end
        
        tmp=isnan(plotspec(:,1));        
        start=find(tmp==0,1,'first');
        plotscale=plotspec(:,1);
        
        plotscale(start:(start+analyzedata.np-1))=analyzedata.Ppmscale;
        text(analyzedata.arraydim,min(min(real(analyzedata.SPECTRA(:,analyzedata.increments(k))))),num2str(analyzedata.increments(k)))

        %hFigDSS=
        DSSFigure=figure(...
            'Name','Spectra array plot',...
            'MenuBar','none',...
            'Toolbar','Figure',...
            'NumberTitle','Off');
        
        %Clean up the Toolbar, removing things we don't need
        tmp = findall(DSSFigure,'ToolTipString','New Figure');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Open File');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Link Plot');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Insert Legend');
        set(tmp,'Visible','Off')
%         tmp = findall(DSSFigure,'ToolTipString','Edit Plot');
%         set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Rotate 3D');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Brush/Select Data');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Hide Plot Tools');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Data Cursor');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Insert Colorbar');
        set(tmp,'Visible','Off')
        tmp = findall(DSSFigure,'ToolTipString','Show Plot Tools and Dock Figure');
        set(tmp,'Visible','Off')
        
        %hPlotDSS= 
       plot(plotscale,plotspec,'Color','black');
       %plot(plotspec,'Color','black');
        
        hold on
        % if Horiz<0
        %     for k=1:analyzedata.arraydim
        %        %text(1-k*Horiz,min(min(plotspec(:,k))),num2str(analyzedata.increments(k)),'Color','Blue');
        % 
        %     end
        % else
        %     for k=1:analyzedata.arraydim
        %        %text(DSSFigure,analyzedata.arraydim*Horiz-k*Horiz,min(min(plotspec(:,k))),num2str(analyzedata.increments(k)),'Color','Blue');
        %     end
        % end
        hold off
        set(gca,'Xdir','reverse');
        xlabel('Chemical shift','FontSize',10, 'FontWeight','bold');
        text(analyzedata.arraydim,min(min(real(analyzedata.SPECTRA(:,analyzedata.increments(k))))),num2str(analyzedata.increments(k)))

        guidata(hMainFigure,NmrData);
    end
    function EditStart_Callback(~,~)
        NmrData=guidata(hMainFigure);
        
        guidata(hMainFigure,NmrData);
    end
    function EditStop_Callback(~,~)
        NmrData=guidata(hMainFigure);
        
        guidata(hMainFigure,NmrData);
    end
    function EditStep_Callback(~,~)
        NmrData=guidata(hMainFigure);
        
        guidata(hMainFigure,NmrData);
    end
    function EditHorizontalOffset_Callback(~,~)
        NmrData=guidata(hMainFigure);
        
        guidata(hMainFigure,NmrData);
    end
    function EditVerticalOffset_Callback(~,~)
        NmrData=guidata(hMainFigure);
        
        guidata(hMainFigure,NmrData);
    end
    function PlotAnalyze(analyzedata)
        %hAnalyzeFig=
        AnalFigure=figure(...
            'Name','Analysis plot',...
            'MenuBar','none',...
            'Toolbar','Figure',...
            'NumberTitle','Off');
        
        %Clean up the Toolbar, removing things we don't need
        tmp = findall(AnalFigure,'ToolTipString','New Figure');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Open File');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Link Plot');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Insert Legend');
        set(tmp,'Visible','Off')
%         tmp = findall(AnalFigure,'ToolTipString','Edit Plot');
%         set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Rotate 3D');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Brush/Select Data');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Hide Plot Tools');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Data Cursor');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Insert Colorbar');
        set(tmp,'Visible','Off')
        tmp = findall(AnalFigure,'ToolTipString','Show Plot Tools and Dock Figure');
        set(tmp,'Visible','Off')
        
        %hPlotAnalyze= 
        plot(analyzedata.xscale,analyzedata.data,'-x','Color','black','MarkerEdgeColor','r');
        xlabel(analyzedata.xlabel)
        ylabel(analyzedata.ylabel)
        title(analyzedata.title)
        axis(gca,'tight')
        tmp=ylim();
        tmpdiff=tmp(2) -tmp(1);
        tmp(1)=tmp(1)-0.2*tmpdiff;
        tmp(2)=tmp(2)+0.2*tmpdiff;
        ylim(tmp)
        
    end
    function analyzedata=PrepareAnalyzeData(input)
        if input.thresflag==1
            if get(hThreshButton,'Value') == 0
                warndlg('Please set a threshold')
                uiwait(gcf)
            end
        end
        NmrData=guidata(hMainFigure);
        analyzedata=NmrData;
        analyzedata.wp=NmrData.sw;
        analyzedata.Ppmscale=NmrData.Specscale;
        analyzedata.SPECTRA=NmrData.SPECTRA;
        
        switch NmrData.shiftunits
            case 'ppm'
                            
            case 'Hz'
                analyzedata.sp=NmrData.sp.*NmrData.sfrq;
                analyzedata.wp=NmrData.sw.*NmrData.sfrq;
                
            otherwise
                error('illegal choice')
        end
        
        Specrange=xlim(hAxes);
        if Specrange(1)<analyzedata.sp
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Analyze: Specrange(1) is too low. The minumum will be used')
            Specrange(1)=analyzedata.sp;
        end
        if Specrange(2)>(analyzedata.wp+analyzedata.sp)
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Analyze: Specrange(2) is too high. The maximum will be used')
            Specrange(2)=analyzedata.wp+analyzedata.sp;
        end
        for k=1:length(analyzedata.Ppmscale)
            if (analyzedata.Ppmscale(k)>Specrange(1))
                begin=k-1;
                k1=begin;
                break;
            end
        end
        
        for k=begin:length(analyzedata.Ppmscale)
            if (analyzedata.Ppmscale(k)>=Specrange(2))
                endrange=k;
                break;
            end
        end
        %make a new stucture
        analyzedata.sp=analyzedata.Ppmscale(k1);
        analyzedata.wp=analyzedata.Ppmscale(endrange)-analyzedata.Ppmscale(k1);
        analyzedata.Ppmscale=analyzedata.Ppmscale(k1:endrange);
        analyzedata.SPECTRA=analyzedata.SPECTRA(k1:endrange,:);
        analyzedata.np=length(analyzedata.Ppmscale);
        analyzedata.increments=1:NmrData.arraydim;
        
        
        k=str2double(get(hEditStart,'String'));
        step=str2double(get(hEditStep,'String'));
        stop=str2double(get(hEditStop,'String'));
        incrit=1;
        
        while k<=NmrData.arraydim && k<=stop
            
            incr(incrit)=analyzedata.increments(k);  %#ok<AGROW>
            k=k+step;
            incrit=incrit+1;
        end
        
        analyzedata.increments=incr;
        analyzedata.arraydim=length(analyzedata.increments);
        
        guidata(hMainFigure,NmrData);
    end
    function MeasureButton_Callback( ~, ~)
        zoom off
        pan off
        hText=findobj(hAxes,'tag','shapetext');
        delete(hText);
        set(hMeasureCheck,'Value',1)
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@Measure_function)
    end
    function MeasureCheck_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        set(hMainFigure,'WindowButtonDownFcn','')
        if get(hMeasureCheck,'Value')
            % Toggle button is pressed-take approperiate action
            line(NmrData.referencexdata,NmrData.referenceydata,...
                'color','magenta','linewidth', 1.0,...
                'tag','Reference');
            set(hAxes,'ButtonDownFcn',@Measure_function)
            drawnow
        else
            % Toggle button is not pressed-take appropriate action
            hReference=findobj(hAxes,'tag','Reference');
            delete(hReference)
            hText=findobj(hAxes,'tag','shapetext');
            delete(hText);
            set(hChangeEdit,'string','');
            set(hAxes,'ButtonDownFcn','')
        end
        guidata(hMainFigure,NmrData);
    end
    function FindMeasure_Callback( ~, ~)
        set(hMainFigure,'WindowButtonDownFcn','')
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        switch NmrData.shiftunits
            case 'ppm'
                startunit='ppm';
            case 'Hz'
                NmrData.shiftunits='ppm';
                NmrData.xlim_spec=NmrData.xlim_spec./NmrData.sfrq;
                NmrData.reference=NmrData.reference./NmrData.sfrq;
                startunit='Hz';
            otherwise
                error('illegal choice')
        end
        
        hReference=findobj(hAxes,'tag','Reference');
        delete(hReference)
        xpoint=(NmrData.reference-NmrData.sp)/NmrData.sw;
        xpoint=round(xpoint*NmrData.fn);
        ppmsearch=0.005;
        xmax=xpoint+round(ppmsearch/NmrData.sw*NmrData.fn);
        xmin=xpoint-round(ppmsearch/NmrData.sw*NmrData.fn);
        tempspec=real(NmrData.SPECTRA(:,NmrData.flipnr));
        tempspec([1:xmin xmax:end],:)=tempspec([1:xmin xmax:end],:).*0.0;
        [~, maxpoint]=max(tempspec);
        maxpoint=maxpoint-1;
        maxpoint=maxpoint/NmrData.fn;
        maxpoint=maxpoint*NmrData.sw;
        maxpoint=maxpoint + NmrData.sp;
        NmrData.reference=maxpoint;
        switch startunit
            case 'ppm'
              
            case 'Hz'
                NmrData.shiftunits='Hz';
                NmrData.xlim_spec=NmrData.xlim_spec.*NmrData.sfrq;
                NmrData.reference=NmrData.reference.*NmrData.sfrq;
            otherwise
                error('illegal choice')
        end
        NmrData.referencexdata=[NmrData.reference NmrData.reference];
        NmrData.referenceydata=get(hAxes,'ylim');
        line(NmrData.referencexdata,NmrData.referenceydata,...
            'color','magenta','linewidth', 1.0,...
            'tag','Reference');
        drawnow
        set(hMeasureCheck,'Value',1)
        set(hAxes,'ButtonDownFcn',@Measure_function)
        guidata(hMainFigure,NmrData);
        
    end
    function ShapeButton_Callback(~, ~)
        % find the peak width at half height
        % find the max point
        FindMeasure_Callback();
        PeakMax=(NmrData.reference-NmrData.sp)/NmrData.sw;
        PeakMax=round(PeakMax*NmrData.fn);
        StartSpec=real(NmrData.SPECTRA(:,NmrData.flipnr));
        amp=StartSpec(PeakMax);
        k=1;
        while StartSpec(PeakMax+k)>amp/2
            k=k+1;
            if PeakMax+k>length(StartSpec)
                break
            end
        end
        
        RightSpecPoint=k;
        if PeakMax+10*RightSpecPoint>length(StartSpec)
            RightSpecPoint= length(StartSpec)-PeakMax;
        else
            RightSpecPoint=10*RightSpecPoint;
        end
        
        k=1;
        while StartSpec(PeakMax-k)>amp/2
            k=k+1;
            if PeakMax-k<1
                break
            end
        end
        
        LeftSpecPoint=k;
        if PeakMax-10*LeftSpecPoint<1
            LeftSpecPoint= 1-PeakMax;
        else
            LeftSpecPoint=10*LeftSpecPoint;
        end
        OutSpec=StartSpec(PeakMax-LeftSpecPoint:PeakMax+RightSpecPoint);
        PeakMaxOut=LeftSpecPoint+2;
        PeakWidth=EstimatePeakshape(OutSpec,PeakMaxOut);
        guidata(hMainFigure,NmrData); WriteLogDispInfo(['Peak width at half height is: ' num2str(PeakWidth,3) ' Hz'])
        plotval=ylim();
        plotval=plotval(2)/2;
        hText=findobj(hAxes,'tag','shapetext');
        delete(hText);
        text(NmrData.reference,plotval,['Peak width at half height is: ' num2str(PeakWidth,3) ' Hz'],'tag','shapetext')
        
        return
    end
    function DeltaButton_Callback( ~, ~)
    %get the distance between between right and left limit
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        
%         guidata(hMainFigure,NmrData);
        NmrData=guidata(hMainFigure);
        
        hDeltaleft=findobj(hAxes,'tag','Deltaleft');
        hDeltaright=findobj(hAxes,'tag','Deltaright');

        if isempty(hDeltaleft) || isempty(hDeltaright)
            msgbox('Left and right limits are not defined');
        else
            delta=NmrData.Deltaleft-NmrData.Deltaright;
            centre=NmrData.Deltaright+(delta/2);
                      
            switch NmrData.shiftunits
                case 'ppm'
                    deltaorg=[delta NmrData.sfrq*delta];
                    deltaorg=round(deltaorg*10000)/10000;
                    delta=inputdlg({'Set delta (ppm)','Set delta (Hz)','Set centre (ppm)'},'Delta',1,{num2str(delta),num2str(NmrData.sfrq*delta),num2str(centre)});
                    if isempty(delta)
                        return
                    end
                    
                    delta=str2double(delta);
                    delta=round(delta*10000)/10000;
                    centre=(delta(3));
                    
                    if deltaorg(1)~=delta(1) && deltaorg(2)~=delta(2)
                        warndlg('Only change the ppm or Hz value')
                        uiwait(gcf)
                        delta=deltaorg(1);
                    elseif deltaorg(1)~=delta(1)
                        delta=delta(1);
                    elseif deltaorg(2)~=delta(2)
                        delta=delta(2)/NmrData.sfrq;
                    else
                        delta=deltaorg(1);
                    end
                    
                    
                case 'Hz'
                    deltaorg=[delta/NmrData.sfrq delta];
                    deltaorg=round(deltaorg*10000)/10000;
                    delta=inputdlg({'Set delta (ppm)','Set delta (Hz)','Set centre (ppm)'},'Delta',1,{num2str(delta/NmrData.sfrq),num2str(delta),num2str(centre)});
                    delta=str2double(delta);
                    delta=round(delta*10000)/10000;
                    centre=(delta(3));
                    if deltaorg(1)~=delta(1) && deltaorg(2)~=delta(2)
                        warndlg('Only change the ppm or Hz value')
                        uiwait(gcf)
                        delta=deltaorg(2);
                    elseif deltaorg(1)~=delta(1)
                        delta=delta(1)*NmrData.sfrq;
                    elseif deltaorg(2)~=delta(2)
                        delta=delta(2);
                    else
                        delta=deltaorg(1);
                    end
                    
                otherwise
                    error('illegal choice')
            end
            
            
            if isempty(delta) || isnan(delta) || isempty(centre) || isnan(centre)
              % do nothing  
            else
                NmrData.Deltaleft=centre+delta/2;
                NmrData.Deltaright=centre-delta/2;
                NmrData.Deltaleftxdata=[NmrData.Deltaleft NmrData.Deltaleft];
                NmrData.Deltarightxdata=[NmrData.Deltaright NmrData.Deltaright];
                NmrData.Deltaleftydata=get(hAxes,'ylim');
                NmrData.Deltarightydata=get(hAxes,'ylim');
                guidata(hMainFigure,NmrData);
                PlotSpectrum();
            end
        end
    end
    function DeltashowLRCheck_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        hDeltaright=findobj(hAxes,'tag','Deltaright');
        hDeltaleft=findobj(hAxes,'tag','Deltaleft');
        
        if get(hDeltashowLRCheck,'Value')
            if isempty(hDeltaright) || isempty(hDeltaleft)
                msgbox('Left and right limits are not defined');
            else
                line(NmrData.Deltaleftxdata,NmrData.Deltaleftydata,...
                    'color','red','linewidth', 1.0,...
                    'tag','Deltaleft');
                line(NmrData.Deltarightxdata,NmrData.Deltarightydata,...
                    'color','green','linewidth', 1.0,...
                    'tag','Deltaright');
            end
        else
            delete(hDeltaleft)
            delete(hDeltaright)
            set(hAxes,'ButtonDownFcn','')
        end
        guidata(hMainFigure,NmrData);
    end
    function DeltaleftButton_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@DeltaLeft_function)
    end
    function DeltarigthButton_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        set(hAxes,'ButtonDownFcn',@DeltaRight_function)
    end
%----Align spectra ------------------
    function AutoAlignButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        input.thresflag=0;
        analyzedata=PrepareAnalyzeData(input);
        %         analyzedata.Ppmscale(1)
        %         analyzedata.Ppmscale(end)
        FS=1;
        hp=waitbar(0,'Finding frequencies');
        for p=NmrData.flipnr:(NmrData.arraydim-NmrData.flipnr)
            waitbar(p/(NmrData.arraydim-NmrData.flipnr+1));
            th=100*NmrData.thresydata(1)/max(real(analyzedata.SPECTRA(:,p)));
            [peaks]=peakpick_mn(real(analyzedata.SPECTRA(:,p)),th);
            
            if isempty(peaks)
                %do nothing
            else
                amp=real(analyzedata.SPECTRA(peaks(1).max,p));
                ampmax=1;
                for k=1:length(peaks)
                    testamp=analyzedata.SPECTRA(peaks(k).max,p);
                    if testamp>amp
                        ampmax=k;
                    end
                end
                %size(analyzedata.Ppmscale)
                switch NmrData.shiftunits
                    case 'ppm'
                        NmrData.fshift(p)=analyzedata.Ppmscale(peaks(ampmax).max)*NmrData.sfrq;
                    case 'Hz'
                        NmrData.fshift(p)=analyzedata.Ppmscale(peaks(ampmax).max);
                    otherwise
                        error('illegal choice')
                end
                if FS==1
                    FirstSPec=NmrData.fshift(p);
                    FS=0;
                end
                NmrData.fshift(p)=NmrData.fshift(p)-FirstSPec;
            end
        end
        
        % NmrData.fshift=NmrData.fshift/2;
        
        close(hp)
        
        guidata(hMainFigure,NmrData);
    end
    function ZeroAlignButton_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.fshift=zeros(1,NmrData.arraydim);
        set(hSliderShift,'value',NmrData.fshift(NmrData.flipnr));
        guidata(hMainFigure,NmrData);
        set(hEditShift,'String',num2str(NmrData.fshift(NmrData.flipnr)));
        msgbox('Align shifts cleared')
    end
    function EditShift_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.fshift(NmrData.flipnr)=str2double(get(hEditShift,'String'));
        set(hSliderShift,'Value',NmrData.fshift(NmrData.flipnr));
        guidata(hMainFigure,NmrData);
        if get(hCheckAutoApply,'Value')
            if get(hCheckApplyFT,'Value')
                FTButton_Callback();
            else
                set(hCheckApplyFT,'Value',1)
                FTButton_Callback();
                set(hCheckApplyFT,'Value',0)
            end
        end
        guidata(hMainFigure,NmrData);
    end
    function ButtonPlusShift_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.fshift(NmrData.flipnr)= NmrData.fshift(NmrData.flipnr)+0.1;
        set(hEditShift,'String',num2str(NmrData.fshift(NmrData.flipnr)));
        guidata(hMainFigure,NmrData);
        set(hSliderShift,'value',NmrData.fshift(NmrData.flipnr));
        if get(hCheckAutoApply,'Value')
            if get(hCheckApplyFT,'Value')
                FTButton_Callback();
            else
                set(hCheckApplyFT,'Value',1)
                FTButton_Callback();
                set(hCheckApplyFT,'Value',0)
            end
        end
    end
    function ButtonMinusShift_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.fshift(NmrData.flipnr)= NmrData.fshift(NmrData.flipnr)-0.1;
        set(hEditShift,'String',num2str(NmrData.fshift(NmrData.flipnr)));
        guidata(hMainFigure,NmrData);
        set(hSliderShift,'value',NmrData.fshift(NmrData.flipnr));
        if get(hCheckAutoApply,'Value')
            if get(hCheckApplyFT,'Value')
                FTButton_Callback();
            else
                set(hCheckApplyFT,'Value',1)
                FTButton_Callback();
                set(hCheckApplyFT,'Value',0)
            end
        end
    end
    function SliderShift_Callback(~,~)
        NmrData=guidata(hMainFigure);
        get(hSliderShift,'Value')
        NmrData.fshift(NmrData.flipnr)=get(hSliderShift,'Value');
        guidata(hMainFigure,NmrData);
        set(hEditShift,'String',num2str(NmrData.fshift(NmrData.flipnr)));
        if get(hCheckAutoApply,'Value')
            if get(hCheckApplyFT,'Value')
                FTButton_Callback();
            else
                set(hCheckApplyFT,'Value',1)
                FTButton_Callback();
                set(hCheckApplyFT,'Value',0)
            end
        end
        
        guidata(hMainFigure,NmrData);
    end
    function ButtonPlusShift2_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.fshift(NmrData.flipnr)= NmrData.fshift(NmrData.flipnr)+0.01;
        set(hEditShift,'String',num2str(NmrData.fshift(NmrData.flipnr)));
        guidata(hMainFigure,NmrData);
        set(hSliderShift,'value',NmrData.fshift(NmrData.flipnr));
        if get(hCheckAutoApply,'Value')
            if get(hCheckApplyFT,'Value')
                FTButton_Callback();
            else
                set(hCheckApplyFT,'Value',1)
                FTButton_Callback();
                set(hCheckApplyFT,'Value',0)
            end
        end
        
    end
    function ButtonMinusShift2_Callback(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.fshift(NmrData.flipnr)= NmrData.fshift(NmrData.flipnr)-0.01;
        set(hEditShift,'String',num2str(NmrData.fshift(NmrData.flipnr)));
        guidata(hMainFigure,NmrData);
        set(hSliderShift,'value',NmrData.fshift(NmrData.flipnr));
        if get(hCheckAutoApply,'Value')
            if get(hCheckApplyFT,'Value')
                FTButton_Callback();
            else
                set(hCheckApplyFT,'Value',1)
                FTButton_Callback();
                set(hCheckApplyFT,'Value',0)
            end
        end
    end
%----INTEGRAL-----
    function IntegralsShow_Callback( ~, ~)
        zoom off
        pan off
        button_state = get(hIntegralsShow,'Value');
        if button_state == 1
            DrawIntLine();
        elseif button_state == 0
            hIntLine=findobj(hAxes,'tag','IntLine');
            delete(hIntLine);
        end
        PlotSpectrum();
        guidata(hMainFigure,NmrData);
    end
    function SetIntegralsButton_Callback( ~, ~)
        zoom off
        pan off
        %get the delta the spectrum
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        IntLine_function();
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        set(hMainFigure,'WindowButtonDownFcn',@IntLine_function)
        set(hIntegralsShow,'Value',1)
    end
    function ClearIntegralsButton_Callback( ~, ~)
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        NmrData.integral_peaks=[];
        NmrData.IntPoint=[];
        % NmrData.IntPoint=[NmrData.sp];
        %NmrData.IntPoint=[NmrData.sp+NmrData.sw];
        NmrData.IntPointSort=[];
        NmrData.IntPointIndex=[];
        NmrData.Integral=ones(1, NmrData.fn);
        set(hMainFigure,'WindowButtonDownFcn','')
        hIntLine=findobj(hAxes,'tag','IntLine');
        delete(hIntLine);
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        set(hIntegralsShow,'Value',0)
    end
    function PeakpickButton_Callback(~,~)

        ClearIntegralsButton_Callback();
        % VERSION USING PEAK PICKING
        [peak]=peakpick_mn(NmrData.SPECTRA(:,NmrData.flipnr),NmrData.th);
        [npeaks]=length(peak);


        integral_peaks=[];
        spectmp=real(NmrData.SPECTRA(:,NmrData.flipnr));
        for k=1:npeaks
            integral_peaks(k).startIndex=peak(k).start; %#ok<AGROW>
            integral_peaks(k).start=NmrData.Specscale(peak(k).start);%#ok<AGROW>
            integral_peaks(k).stopIndex=peak(k).stop;%#ok<AGROW>
            integral_peaks(k).stop=NmrData.Specscale(peak(k).stop);%#ok<AGROW>
            integral_peaks(k).maxIndex=peak(k).max;%#ok<AGROW>
            integral_peaks(k).max=NmrData.Specscale(peak(k).max);%#ok<AGROW>
            integral_peaks(k).Offset=0; %#ok<AGROW>
            integral_peaks(k).Tilt=0; %#ok<AGROW>
            integral_peaks(k).ValueRaw=sum(spectmp(integral_peaks(k).startIndex:...
                integral_peaks(k).stopIndex)); %#ok<AGROW>
            for m=1:NmrData.arraydim
                integral_peaks(k).Individual(m).Offset=0;
                integral_peaks(k).Individual(m).Tilt=0;
            end
        end
        NmrData.integral_peaks=integral_peaks;
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        set(hIntegralsShow,'Value',1)
        IntegralsShow_Callback()
    end
    function EditFlipPeak_Callback(~,~)
        
        intpeak=round(str2double(get(hEditFlipPeak,'String'))); 
        if isempty(intpeak)
            warndlg('peak number must be numeric')
            uiwait(gcf)
            set(hEditFlipPeak,'String',num2str(1));
        else
            intpeak=round(intpeak);
            if intpeak<1
                intpeak=1;
            end
            if intpeak>numel(NmrData.integral_peaks)
                intpeak=numel(NmrData.integral_peaks);
            end
            
            set(hEditFlipPeak,'String',num2str(intpeak));
        end
        
        if isempty(NmrData.integral_peaks)
        else
            hIntPeakLine=findobj(hAxes,'tag','IntPeakLine');
            delete(hIntPeakLine);
            if get(hIntegralsShowPeak,'Value')
                line_tmp=NmrData.integral_peaks(intpeak).start + NmrData.integral_peaks(intpeak).stop;
                line_tmp=line_tmp/2;
                
                line(hAxes,[line_tmp line_tmp], ylim,'Color', 'r','tag','IntPeakLine');
            end
        end
    end
    function IntegralsShowPeak_Callback(~,~)
        EditFlipPeak_Callback();
    end
    function GtoIButtonInt_Callback(~,~)
        for k=1:1:numel(NmrData.integral_peaks)
            for m=1:NmrData.arraydim
                NmrData.integral_peaks(k).Individual(m).Offset=...
                    NmrData.integral_peaks(k).Offset;
                NmrData.integral_peaks(k).Individual(m).Tilt=...
                    NmrData.integral_peaks(k).Tilt;
            end
        end
        
    end
    function RadioScopeGlobalInt_Callback(~,~)
        
        if get(hRadioScopeGlobalInt,'Value')
            set(hRadioScopeIndividualInt,'Value',0)
        else
            set(hRadioScopeIndividualInt,'Value',1)
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function RadioScopeIndividualInt_Callback(~,~)
        if get(hRadioScopeIndividualInt,'Value')
            set(hRadioScopeGlobalInt,'Value',0)
        else
            set(hRadioScopeGlobalInt,'Value',1)
        end
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function ButtonFlipPlusPeak_Callback(~,~)
        intpeak=round(str2double(get(hEditFlipPeak,'String'))); 
        set(hEditFlipPeak,'String',num2str(intpeak +1));
        EditFlipPeak_Callback();
    end
    function ButtonFlipMinusPeak_Callback(~,~)
        intpeak=round(str2double(get(hEditFlipPeak,'String'))); 
        set(hEditFlipPeak,'String',num2str(intpeak-1));
        EditFlipPeak_Callback();
    end
    function EditOffset_Callback(~,~)
        Offset=round(str2double(get(hEditOffset,'String'))); 
        Mult=round(str2double(get(hEditOffsetMult,'String'))); 
        if isempty(Offset)
            warndlg('Offset  must be numeric')
            uiwait(gcf)
            set(hEditOffset,'String',num2str(0));
            set(hSliderOffset,'Value',0);
        else
            peakNr= str2double(get(hEditFlipPeak,'String')); 
            if isempty((NmrData.integral_peaks))
            else
                if  get(hRadioScopeGlobalInt,'Value')
                    NmrData.integral_peaks(peakNr).Offset=Offset*Mult ;
                else
                    NmrData.integral_peaks(peakNr).Individual(NmrData.flipnr).Offset=Offset*Mult;
                end
                
                guidata(hMainFigure,NmrData);
                set(hSliderOffset,'Value',Offset);
                guidata(hMainFigure,NmrData);
                PlotSpectrum();
            end
        end
        set(hSliderOffset,'Value',Offset);
        guidata(hMainFigure,NmrData);
    end
    function EditOffsetMult_Callback(~,~)
        Mult=round(str2double(get(hEditOffsetMult,'String'))); 
        if isempty(Mult)
            warndlg('Offset  must be numeric')
            uiwait(gcf)
            set(hEditOffsetMult,'String',num2str(1));
        else
            guidata(hMainFigure,NmrData);
        end
        EditOffset_Callback();
    end
    function ButtonPlusOffset_Callback(~,~)
        Mult=round(str2double(get(hEditOffsetMult,'String'))); 
        set(hEditOffsetMult,'String',num2str(Mult*2));
        EditOffsetMult_Callback();
    end
    function ButtonMinusOffset_Callback(~,~)
        Mult=round(str2double(get(hEditOffsetMult,'String'))); 
        set(hEditOffsetMult,'String',num2str(Mult/2));
        EditOffsetMult_Callback();
    end
    function SliderOffset_Callback(~,~)
        NmrData=guidata(hMainFigure);
        Offset=get(hSliderOffset,'Value');
        Mult=round(str2double(get(hEditOffsetMult,'String'))); 
        set(hEditOffset,'String',num2str(Offset));
        % EditOffset_Callback();
        guidata(hMainFigure,NmrData);
        peakNr= str2double(get(hEditFlipPeak,'String'));
        if isempty((NmrData.integral_peaks))
        else
            
            if  get(hRadioScopeGlobalInt,'Value')
                NmrData.integral_peaks(peakNr).Offset=Offset*Mult ;
            else
                NmrData.integral_peaks(peakNr).Individual(NmrData.flipnr).Offset=Offset*Mult;
            end
            guidata(hMainFigure,NmrData);
            PlotSpectrum();
        end
    end
    function EditTilt_Callback(~,~)
        Tilt=round(str2double(get(hEditTilt,'String'))); 
        Mult=round(str2double(get(hEditTiltMult,'String'))); 
        if isempty(Tilt)
            warndlg('Tilt  must be numeric')
            uiwait(gcf)
            set(hEditTilt,'String',num2str(0));
            set(hSliderTilt,'Value',0);
        else
            peakNr= str2double(get(hEditFlipPeak,'String')); 
            if isempty((NmrData.integral_peaks))
            else
                if  get(hRadioScopeGlobalInt,'Value')
                    NmrData.integral_peaks(peakNr).Tilt=Tilt*Mult ;
                else
                    NmrData.integral_peaks(peakNr).Individual(NmrData.flipnr),Tilt=Tilt*Mult ;
                end
                guidata(hMainFigure,NmrData);
                set(hSliderTilt,'Value',Tilt);
                PlotSpectrum();
            end
        end
        set(hSliderTilt,'Value',Tilt);
        guidata(hMainFigure,NmrData);
    end
    function EditTiltMult_Callback(~,~)
        Mult=round(str2double(get(hEditTiltMult,'String'))); 
        if isempty(Mult)
            warndlg('Offset  must be numeric')
            uiwait(gcf)
            set(hEditTiltMult,'String',num2str(1));
        else
            guidata(hMainFigure,NmrData);
        end
        EditTilt_Callback();
    end
    function ButtonPlusTilt_Callback(~,~)
        Mult=round(str2double(get(hEditTiltMult,'String'))); 
        set(hEditTiltMult,'String',num2str(Mult*2));
        EditTilt_Callback();
    end
    function ButtonMinusTilt_Callback(~,~)
        Mult=round(str2double(get(hEditTiltMult,'String'))); 
        set(hEditTiltMult,'String',num2str(Mult/2));
        EditTilt_Callback();
    end
    function SliderTilt_Callback(~,~)
        NmrData=guidata(hMainFigure);
        Tilt=get(hSliderTilt,'Value');
        Mult=round(str2double(get(hEditTiltMult,'String')));
        set(hEditTilt,'String',num2str(Tilt));
        guidata(hMainFigure,NmrData);
        peakNr= str2double(get(hEditFlipPeak,'String')); 
        if isempty((NmrData.integral_peaks))
        else
            if  get(hRadioScopeGlobalInt,'Value')
                NmrData.integral_peaks(peakNr).Tilt=Tilt*Mult ;
            else
                NmrData.integral_peaks(peakNr).Individual(NmrData.flipnr).Tilt=Tilt*Mult ;
            end
            guidata(hMainFigure,NmrData);
            PlotSpectrum();
        end
    end
    function EditNorm_Callback( ~, ~)
        zoom off
        pan off
        tmp=round(str2double(get(hEditNorm,'string')));
        if isnan(tmp)
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Norm must be a number; defaulting to 100')
            set(hEditNorm,'String',num2str(100))
        end
        
        guidata(hMainFigure,NmrData);
        set(hIntegralsShow,'Value',1)
        PlotSpectrum();
    end
    function EditNormPeak_Callback( ~, ~)
        zoom off
        pan off
        tmp=round(str2double(get(hEditNormPeak,'string')));
        if isnan(tmp)
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Norm must be a number defaulting to 1')
            set(hEditNormPeak,'String',num2str(1))
        end
        guidata(hMainFigure,NmrData);
        set(hIntegralsShow,'Value',1)
        PlotSpectrum();
    end
    function GroupNormalise_Callback( ~, ~)
        zoom off
        pan off
        switch get(hBGroupNormalise,'SelectedObject')
            case hRadio1Normalise
                set(hEditNormPeak,'Enable','On')
                set(hEditNorm,'Enable','On')
            case hRadio2Normalise
                set(hEditNormPeak,'Enable','Off')
                set(hEditNorm,'Enable','On')
            case hRadio3Normalise
                set(hEditNormPeak,'Enable','Off')
                set(hEditNorm,'Enable','Off')
            otherwise
                error('illegal choice')
        end
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        set(hIntegralsShow,'Value',1)
    end
    function ExportIntegralButton_Callback( ~, ~)
        %export the integral data
        filter={'*.xlsx','Excel format (*.xlsx)';'*.txt','GNAT format (*.txt)'};
        [filename, pathname,idx] = uiputfile(filter,'Export integrals');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end

        %get the integral regions
        Int_reg=zeros(numel(NmrData.integral_peaks),2);
        for k=1:numel(NmrData.integral_peaks)
            Int_reg(k,:)= [NmrData.integral_peaks(k).start,NmrData.integral_peaks(k).stop];
        end

        %get the inegral values
        tmpflip= NmrData.flipnr;
        IntPeak=zeros(numel(NmrData.integral_peaks),NmrData.arraydim);
        for n=1:NmrData.arraydim
            NmrData.flipnr=n;
            guidata(hMainFigure,NmrData);
            PlotSpectrum();
            RealSpec=real(NmrData.SPECTRA(:,NmrData.flipnr));
            %fprintf(statfil,'%-s\t\t\t\t %-d \n','# Integrals for spectrum (integer)',...
            %    NmrData.flipnr);
            CumSum=0;
            for k=1:numel(NmrData.integral_peaks)
                Start=NmrData.integral_peaks(k).startIndex;
                Stop=NmrData.integral_peaks(k).stopIndex;
                if get(hRadioScopeGlobalInt,'Value')
                    Offset=NmrData.integral_peaks(k).Offset;
                    Tilt=NmrData.integral_peaks(k).Tilt;
                else
                    Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                    Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                end
                tmp=0:(Stop-Start);
                tmp=(Tilt*tmp)/tmp(end);
                TiltLine=tmp(:);
                CumSum=sum(RealSpec(Start:Stop)-Offset-TiltLine) + CumSum;
            end
            %Calculate normalisation
            intnorm=str2double(get(hEditNorm,'String'));
            intpeak=round(str2double(get(hEditNormPeak,'String')));
            switch get(hBGroupNormalise,'SelectedObject')

                case hRadio1Normalise %Peak
                    for k=1:numel(NmrData.integral_peaks)
                        if numel(NmrData.integral_peaks)<intpeak
                            set(hEditNormPeak,'String', num2str(1));
                            intpeak=1;
                        end
                        StartRef=NmrData.integral_peaks(intpeak).startIndex;
                        StopRef=NmrData.integral_peaks(intpeak).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            OffsetRef=NmrData.integral_peaks(k).Offset;
                            TiltRef=NmrData.integral_peaks(k).Tilt;
                        else
                            OffsetRef=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                            TiltRef=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                        end
                        tmp=0:(StopRef-StartRef);
                        tmp=(TiltRef*tmp)/tmp(end);
                        TiltLineRef=tmp(:);
                        RefInt=sum(RealSpec(StartRef:StopRef)-OffsetRef - TiltLineRef);

                        Start=NmrData.integral_peaks(k).startIndex;
                        Stop=NmrData.integral_peaks(k).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            Offset=NmrData.integral_peaks(k).Offset;
                            Tilt=NmrData.integral_peaks(k).Tilt;
                        else
                            Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                            Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                        end
                        tmp=0:(Stop-Start);
                        tmp=(Tilt*tmp)/tmp(end);
                        TiltLine=tmp(:);
                        IntPeak(k,n)=intnorm*sum(RealSpec(Start:Stop)-Offset - TiltLine)/RefInt;
                        %text(NmrData.integral_peaks(k).max,yp2,num2str(IntPeak));
                        %fprintf(statfil,'%-s %-d %-s %-f \n','Peak ',k, ': (double)', IntPeak);
                    end

                case hRadio2Normalise %Total
                    for k=1:numel(NmrData.integral_peaks)
                        Start=NmrData.integral_peaks(k).startIndex;
                        Stop=NmrData.integral_peaks(k).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            Offset=NmrData.integral_peaks(k).Offset;
                            Tilt=NmrData.integral_peaks(k).Tilt;
                        else
                            Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                            Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                        end
                        tmp=0:(Stop-Start);
                        tmp=(Tilt*tmp)/tmp(end);
                        TiltLine=tmp(:);
                        IntPeak(k,n)=intnorm*sum(RealSpec(Start:Stop)-Offset -TiltLine)/CumSum;
                        %text(NmrData.integral_peaks(k).max,yp2,num2str(IntPeak));
                        %fprintf(statfil,'%-s %-d %-s %-f \n','Peak ',k, ': (double)', IntPeak);
                    end

                case hRadio3Normalise %Absolute
                    for k=1:numel(NmrData.integral_peaks)
                        Start=NmrData.integral_peaks(k).startIndex;
                        Stop=NmrData.integral_peaks(k).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            Offset=NmrData.integral_peaks(k).Offset;
                            Tilt=NmrData.integral_peaks(k).Tilt;
                        else
                            Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                            Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                        end
                        tmp=0:(Stop-Start);
                        tmp=(Tilt*tmp)/tmp(end);
                        TiltLine=tmp(:);
                        IntPeak(k,n)=sum(RealSpec(Start:Stop)-Offset - TiltLine);
                        % text(NmrData.integral_peaks(k).max,yp2,num2str(IntPeak));
                        %fprintf(statfil,'%-s %-d %-s %-f \n','Peak ',k, ': (double)', IntPeak);
                    end

                otherwise
                    error('illegal choice')
            end
        end
        NmrData.flipnr=tmpflip;


        switch idx %what type of file to export
            case 1 %Spreadsheet
                %Export the integral regions
                Regions=["Start";"Stop"];
                RegTab=table(Regions);
                for k=1:numel(NmrData.integral_peaks)
                    RegTab=[RegTab,table(Int_reg(k,:)')]; %#ok<AGROW>
                    RegTab.Properties.VariableNames{k+1}=num2str(k);
                end
                writetable(RegTab,filename,'Sheet','Integral Regions')

                %Export the integral values

                IntTab=array2table(IntPeak');
                for k=1:numel(NmrData.integral_peaks)
                    IntTab.Properties.VariableNames{k}=num2str(k);
                end
                writetable(IntTab,filename,'Sheet','Integral Values')


            case 2 %print GNAT text file
                filepath=[pathname filename];
                statfil=fopen(filepath, 'wt');
                %print out FID data to file
                if isunix()==1
                    slashindex=find(NmrData.filename=='/');
                else
                    slashindex=find(NmrData.filename=='\');
                end

                %print mandatory fields
                fprintf(statfil,'%-s  \n','## GNAT data file');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s \n','#Title (string) ' , NmrData.filename(slashindex(end)+1:end) );
                fprintf(statfil,'%-s\t\t\t\t\t\t\t %-s \n','#Date (string) ' , string(datetime) );
                fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#GNAT version (string) ', NmrData.version);
                fprintf(statfil,'%-s\t\t\t\t %-s  \n','#GNAT format version (double) ', '0.1');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', 'Integrals');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Origin (string) ', 'DOSY Toolbox');
                fprintf(statfil,'%-s\t\t\t\t %-s  \n','#Spectrometer/Data System (string)', NmrData.type);
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', 'Integrals');
                fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Observe Nucleus (string) ', '1-H');
                fprintf(statfil,'%-s\t\t\t\t %-f  \n','#Observe frequency (double ; MHz) ', NmrData.sfrq);
                fprintf(statfil,'%-s\t\t\t\t \n','#Y axis definition (null) ');
                fprintf(statfil,'%-s\t\t\t\t \n','#Binary file name (null) ');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', 'No');
                %print peak regions
                fprintf(statfil,'%-s %-d %-s \n','#Integral Regions [',floor(length(NmrData.IntPointSort)/2),'] (string)');

                for k=1:numel(NmrData.integral_peaks)
                    fprintf(statfil,'%-s %-d %-s %-f %-f \n','Peak ',k, ': (double ; ppm)',...
                        NmrData.integral_peaks(k).start,NmrData.integral_peaks(k).stop);
                end
                %print peak data
                intnorm=str2double(get(hEditNorm,'String'));
                intpeak=round(str2double(get(hEditNormPeak,'String')));
                switch get(hBGroupNormalise,'SelectedObject')
                    case hRadio1Normalise
                        fprintf(statfil,'%-s\t\t\t\t\t %-d \n','# Normalised to Peak: (integer)',intpeak);
                    case hRadio2Normalise
                        fprintf(statfil,'%-s\t\t\t\t %-f \n','# Total area normalised to (double) ',intnorm);
                    case hRadio3Normalise
                        fprintf(statfil,'%-s \n','# No normalisation (null)');
                    otherwise
                        fprintf(statfil,'%-s \n','# Unknown normalisation (null)');
                end
                tmpflip= NmrData.flipnr;
                for n=1:NmrData.arraydim
                    NmrData.flipnr=n;
                    guidata(hMainFigure,NmrData);
                    PlotSpectrum();
                    RealSpec=real(NmrData.SPECTRA(:,NmrData.flipnr));
                    fprintf(statfil,'%-s\t\t\t\t %-d \n','# Integrals for spectrum (integer)',...
                        NmrData.flipnr);
                    CumSum=0;
                    for k=1:numel(NmrData.integral_peaks)
                        Start=NmrData.integral_peaks(k).startIndex;
                        Stop=NmrData.integral_peaks(k).stopIndex;
                        if get(hRadioScopeGlobalInt,'Value')
                            Offset=NmrData.integral_peaks(k).Offset;
                            Tilt=NmrData.integral_peaks(k).Tilt;
                        else
                            Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                            Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                        end
                        %TiltLine=zeros(1,Stop-Start);
                        tmp=0:(Stop-Start);
                        tmp=(Tilt*tmp)/tmp(end);
                        TiltLine=tmp(:);
                        %IntSpec(Start:Stop)=cumsum(RealSpec(Start:Stop)-Offset -TiltLine) + CumSum ;
                        CumSum=sum(RealSpec(Start:Stop)-Offset-TiltLine) + CumSum;
                    end

                    for k=1:numel(NmrData.integral_peaks)
                        fprintf(statfil,'%-s %-d %-s %-f \n','Peak ',k, ': (double)', IntPeak(k,n));
                    end
                end
                fclose(statfil);
                type(filepath);
                NmrData.flipnr=tmpflip;
                guidata(hMainFigure,NmrData);
                set(hMainFigure,'WindowButtonDownFcn','')
                %  IntLine_function();


            otherwise
        end
        PlotSpectrum();
    end
    function ExportIntegralSetButton_Callback( ~, ~)
        %export the integral regions
        [filename, pathname] = uiputfile('*.txt','Export integral regions');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'wt');
        if isunix()==1
            slashindex=find(NmrData.filename=='/');
        else
            slashindex=find(NmrData.filename=='\');
        end

        %print mandatory fields
        fprintf(statfil,'%-s  \n','## DOSY Toolbox data file');
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s \n','#Title (string) ' , NmrData.filename(slashindex(end)+1:end) );
        fprintf(statfil,'%-s\t\t\t\t\t\t\t %-s \n','#Date (string) ' , string(datetime) );
        fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#DOSY Toolbox version (string) ', NmrData.version);
        fprintf(statfil,'%-s\t\t\t\t %-s  \n','#DOSY Toolbox format version (double) ', '0.1');
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', 'Integrals Settings');
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Origin (string) ', 'DOSY Toolbox');
        fprintf(statfil,'%-s\t\t\t\t %-s  \n','#Spectrometer/Data System (string)', NmrData.type);
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', 'Integrals');
        fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Observe Nucleus (string) ', '1-H');
        fprintf(statfil,'%-s\t\t\t\t %-f  \n','#Observe frequency (double ; MHz) ', NmrData.sfrq);
        fprintf(statfil,'%-s\t\t\t\t \n','#Y axis definition (null) ');
        fprintf(statfil,'%-s\t\t\t\t \n','#Binary file name (null) ');
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', 'No');
        %print peak regions
        fprintf(statfil,'%-s%-d%-s \n','#Integral Regions [',floor(length(NmrData.IntPointSort)/2),'] (string)');
        for k=1:length(NmrData.IntPointSort)/2
            fprintf(statfil,'%-s %-d %-s %-f %-f \n','Peak ',k, ': (double;ppm)', NmrData.IntPointSort(2*k-1),NmrData.IntPointSort(2*k));
        end
        
        fclose(statfil);
        type(filepath);
        
    end
    function ImportIntegralSetButton_Callback( ~, ~)
        %export the integral regions
        [filename, pathname] = uigetfile('*.*','Import integral regions');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        filepath=[pathname filename];
        statfil=fopen(filepath, 'rt');
        
        [ImportData]=ImportToolboxFormat(statfil);
     
        if isfield(ImportData,'DataType')
            guidata(hMainFigure,NmrData); WriteLogDispInfo(['File of type ' ImportData.DataType.Value])
        else
            guidata(hMainFigure,NmrData); WriteLogDispInfo(['Unknown file type ' ImportData.DataType])
        end
        if isfield(ImportData,'IntegralRegions')
            guidata(hMainFigure,NmrData); WriteLogDispInfo('Importing integral regions')
            NmrData.IntPoint=[];
            for k=1:length(ImportData.IntegralRegions.Value)
                ParmIndexTwo=strfind(ImportData.IntegralRegions.Value{k},')');
                StrTmp=ImportData.IntegralRegions.Value{k}(ParmIndexTwo+1:end);
                NmrData.IntPoint=[NmrData.IntPoint ; sscanf(StrTmp,'%f %f')];
            end
        else
            error('DOSY Toolbox: File import. integral regions does not exists (or import failed)')
        end
        NmrData.IntPoint= NmrData.IntPoint' ;
        set(hIntegralsShow,'Value',1);
        
        guidata(hMainFigure,NmrData);
                
        set(hMainFigure,'WindowButtonDownFcn','')
                       
        NmrData.IntPointSort=unique(NmrData.IntPoint);
        NmrData.IntPointSort=sort(NmrData.IntPointSort);
        IntPointIndex=[];
        for k=1:length(NmrData.IntPointSort)
            IntPointIndex=[IntPointIndex round(NmrData.fn*...
                (NmrData.IntPointSort(k)-NmrData.sp)/NmrData.sw)]; %#ok<AGROW>
        end
        IntPointIndex=unique(IntPointIndex);
        IntPointIndex=sort(IntPointIndex);
        if bitand(1,length(IntPointIndex)) %odd
            IntPointIndex=[1 IntPointIndex];
            NmrData.Integral=ones(1,NmrData.fn);
            for k=1:length(IntPointIndex)/2
                NmrData.Integral(IntPointIndex(2*k-1):IntPointIndex(2*k)+1)=NaN;
            end
        else %even
            NmrData.Integral=ones(1,NmrData.fn).*NaN;
            for k=1:length(IntPointIndex)/2
                
                NmrData.Integral((IntPointIndex(2*k-1)):(IntPointIndex(2*k)))=1;
                %NmrData.Integral(IntPointIndex(kk):IntPointIndex(kk+1))=NaN;
            end
        end
        NmrData.IntPointIndex=IntPointIndex;
        %make integral regions for fitting
        spectmp=real(NmrData.SPECTRA(:,NmrData.flipnr));
        integral_peaks=[];
        for m=1:length(NmrData.IntPointSort)/2
            integral_peaks(m).start=NmrData.IntPointSort(2*m-1); %#ok<AGROW>
            integral_peaks(m).startIndex=NmrData.IntPointIndex(2*m-1); %#ok<AGROW>
            integral_peaks(m).stop=NmrData.IntPointSort(2*m); %#ok<AGROW>
            integral_peaks(m).stopIndex=NmrData.IntPointIndex(2*m); %#ok<AGROW>
            [~, Index]=max(spectmp(NmrData.IntPointIndex(2*m-1): NmrData.IntPointIndex(2*m)));
            SpecIndex=NmrData.IntPointIndex(2*m-1)+ Index;
            integral_peaks(m).max=NmrData.Specscale(SpecIndex); %#ok<AGROW>
            integral_peaks(m).maxIndex=SpecIndex; %#ok<AGROW>
            integral_peaks(m).ValueRaw=sum(spectmp(integral_peaks(m).startIndex:...
                integral_peaks(m).stopIndex)); %#ok<AGROW>
            integral_peaks(m).Offset=0; %#ok<AGROW>
            integral_peaks(m).Tilt=0; %#ok<AGROW>
            for k=1:NmrData.arraydim
                integral_peaks(m).Individual(k).Offset=0;
                integral_peaks(m).Individual(k).Tilt=0;
            end
            %integral_peaks(m).ValueCorrected=integral_peaks(m).ValueRaw; %#ok<AGROW>
            %Will need value and Value corrected for export. DOSY etc.
        end
        NmrData.integral_peaks=integral_peaks;
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
            
    end
%----SIGNAL-TO-NOISE -------------
    function NoiseShow_Callback( ~, ~)
        zoom off
        pan off
        set(hExcludeShow,'Value',0);
        button_state = get(hSNRShow,'Value');
        if button_state == 1
            DrawIntLine();
        elseif button_state == 0
            hNoiseLine=findobj(hAxes,'tag','NoiseLine');
            delete(hNoiseLine);
        end
        guidata(hMainFigure,NmrData);
    end
    function ClearNoiseButton_Callback( ~, ~)
        zoom off
        pan off
        NmrData=guidata(hMainFigure);
        NmrData.ExcludePoints=[];
        NmrData.excludelinepoints=[];
        NmrData.exclude=ones(1,NmrData.fn);
        %set(hAxes,'ButtonDownFcn',@Excludeline_function)
        set(hMainFigure,'WindowButtonDownFcn',@Excludeline_function);
        hNoiseLine=findobj(hAxes,'tag','NoiseLine');
        delete(hNoiseLine);
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function SetNoiseButton_Callback( ~, ~)
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','');
        guidata(hMainFigure,NmrData);
        set(hMainFigure,'WindowButtonDownFcn',@NoiseLine_function);
        guidata(hMainFigure,NmrData);
        %get the delta the spectrum
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        guidata(hMainFigure,NmrData);
        set(hExcludeShow,'Value',0)
        set(hSNRShow,'Value',1)
        guidata(hMainFigure,NmrData);
        ClearExcludeButton_Callback();
      if size(NmrData.Specscale)==size(NmrData.exclude)
        PlotSpectrum();
      else
          ClearNoiseButton_Callback();
      end
    end
    function doSNR(~,~)
        NmrData=guidata(hMainFigure);
        if isempty(NmrData.ExcludePoints)
            disp('No noise region to fit')
            return
        end
        if size(NmrData.ExcludePoints,2)>2
            disp('Select only one noise region')
            return
        end
        
        noisearray=NmrData.exclude;
        noisearray(isnan(noisearray))=0;
        noise_lim1 = find(noisearray~=0, 1, 'first');
        noise_lim2 = find(noisearray~=0, 1, 'last');
        square=(real(NmrData.SPECTRA)).^2;
        rms_noise=sqrt((sum(square(noise_lim1:noise_lim2,NmrData.flipnr)))/(noise_lim2-noise_lim1+1));
        
        switch get(hBGroupSNR,'SelectedObject') %Peak picking options
            case hRadio1SNR %Maximum
                th=NmrData.th;
                
                %make a new stucture
                speclim=xlim(hAxes);
                if speclim(1)<NmrData.sp
                    speclim(1)=NmrData.sp;
                end
                if speclim(2)>(NmrData.sw+NmrData.sp)
                    speclim(2)=(NmrData.sw+NmrData.sp);
                end
                for k=1:length(NmrData.Specscale)
                    if (NmrData.Specscale(k)>speclim(1))
                        begin=k-1;
                        k1=begin;
                        break;
                    end
                end
                
                for k=begin:length(NmrData.Specscale)
                    if (NmrData.Specscale(k)>=speclim(2))
                        endrange=k;
                        break;
                    end
                end
                
                used_Specscale=NmrData.Specscale(k1:endrange);
                used_SPEC=real(NmrData.SPECTRA(k1:endrange,NmrData.flipnr));
                used_SPEC=used_SPEC.*(used_SPEC>NmrData.thresydata(1));
                [peak]=peakpick_mn(used_SPEC./max(used_SPEC),th);
                [npeaks]=length(peak);
                peakSNR=zeros(npeaks,1);
                freqs=zeros(npeaks,1);
                
                % Calculate signal intensity
                fprintf('\n%s%s%s \n','******* SNR for current spectrum [',num2str(NmrData.flipnr),'] *******');
                fprintf('\n');
                fprintf('%-10s  ','Peak number');
                fprintf('%-10s   %-10s   %-10s  %-10s  %-10s ','Frequency','SNR');
                fprintf('\n');
                for peaknr =1:npeaks
                    
                    P=real(used_SPEC(peak(peaknr).max));
                    freqs(peaknr)=used_Specscale(peak(peaknr).max);
                    
                    % Calculate SNR
                    SNR=(P/(2*rms_noise));
                    peakSNR(peaknr)=SNR;
                    
                    fprintf('   %-10.0f',peaknr);
                    fprintf('%-10.5f  ',freqs(peaknr));
                    fprintf('%-10.2f ',peakSNR(peaknr));
                    fprintf('\n');
                end
                fprintf('\n');
            case hRadio2SNR %Integrals
                num_int=size(NmrData.integral_peaks,2);
                if num_int==0
                    disp('No integrals to fit')
                    return
                end
                
                % Calculate signal intensity
                fprintf('\n%s%s%s \n','******* SNR for current spectrum [',num2str(NmrData.flipnr),'] *******');
                fprintf('\n');
                fprintf('%-10s  ','Peak number');
                fprintf('%-10s   %-10s   %-10s  %-10s  %-10s ','SNR');
                fprintf('\n');
                peakSNR=zeros(size(NmrData.integral_peaks,2),1);
                for peaknr =1:size(NmrData.integral_peaks,2)
                    index=2*peaknr-1;
                    lim1=NmrData.IntPointIndex(index);
                    index=2*peaknr;
                    lim2=NmrData.IntPointIndex(index);
                    
                    P=(sum(real(NmrData.SPECTRA(lim1:lim2,NmrData.flipnr)))) ;
                    
                    % Calculate SNR
                    SNR=(P/(2*rms_noise));
                    peakSNR(peaknr)=SNR;
                    
                    fprintf('   %-10.0f',peaknr);
                    fprintf('%-10.2f',peakSNR(peaknr));
                    fprintf('\n');
                end
                fprintf('\n');
            otherwise
                error('illegal choice')
        end
    end
%----SEGWE(D2MW) -----------------
    function start_segwe(~,~)
        segwe_gnat();
    end
% %----ICOSHIFT ------------------
    function ButtonICOAlign_Callback( ~, ~)
        NmrData=guidata(hMainFigure);
        
        %defaults
        target='average'; %#ok<NASGU>
        mode='whole';%#ok<NASGU>
        fit='b';
        options=0;
        
        switch get(hBGroupIcoshiftTarget,'SelectedObject')
            case hRadio1IcoshiftTarget
                target='average';
            case hRadio2IcoshiftTarget
                target='median';
            case hRadio3IcoshiftTarget
                target='max';
            case hRadio4IcoshiftTarget
                target='average2';
            otherwise
                error('illegal choice')
        end
        
        switch get(hBGroupIcoshiftMode,'SelectedObject')
            case hRadio1IcoshiftMode
                %Interactive
                nPoint=numel(NmrData.baselinepoints);
                if mod(nPoint,2)
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('odd')
                    Nreg=ceil(nPoint/2); %number of spectral regions to process
                else
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('even')
                    Nreg=round(nPoint/2); %number of spectral regions to process
                    %number of processed regions
                end
                Nproc=0;
                m=1;
                while Nreg > Nproc
                    region=ones(1,NmrData.fn)*NaN;
                    while  isnan(NmrData.region(m)) %go to first region
                        m=m+1;
                        if m >= NmrData.fn
                            guidata(hMainFigure,NmrData); WriteLogDispInfo('WARNING. region goes beyond spectra width')
                            break;
                        end
                    end
                    while  ~isnan(NmrData.region(m))
                        region(m)=NmrData.region(m);
                        m=m+1;
                        if m >= NmrData.fn
                            guidata(hMainFigure,NmrData); WriteLogDispInfo('WARNING. region goes beyond spectra width')
                            break;
                        end
                    end
                    rawspec=real(NmrData.SPECTRA(~isnan(region),:));
                    %Now I need to convert to complex and replace that spectral
                    [corrspec] = icoshift (target, rawspec', 'whole', fit, options);
                    corrspec=corrspec';
                    np=length(corrspec(:,1));
                    aspec=fft(corrspec);
                    bspec=aspec(1:(round(np/2)),:);
                    bspec(1,:)=bspec(1,:)*0.5; %remove baseline error
                    cspec=ifft(bspec,np)/0.5; %scale to match original;
                    NmrData.SPECTRA(~isnan(region),:)=cspec;
                    Nproc=Nproc+1;
                end
            case hRadio2IcoshiftMode
                % intervals
                %get intervals
                intervals=round(str2double(get(hEditIntervals,'string')));
                rawspec=real(NmrData.SPECTRA);
                %Now I need to convert to complex and replace that spectral
                
                [corrspec] = icoshift (target, rawspec', intervals, fit, options);
                corrspec=corrspec';
                np=length(corrspec(:,1));
                aspec=fft(corrspec);
                bspec=aspec(1:(round(np/2)),:);
                bspec(1,:)=bspec(1,:)*0.5; %remove baseline error
                cspec=ifft(bspec,np)/0.5; %scale to match original;
                NmrData.SPECTRA=cspec;
                
            case hRadio3IcoshiftMode
                %whole
                
                rawspec=real(NmrData.SPECTRA);
                %Now I need to convert to complex and replace that spectral
                [corrspec] = icoshift (target, rawspec', 'whole', fit, options);
                corrspec=corrspec';
                np=length(corrspec(:,1));
                aspec=fft(corrspec);
                bspec=aspec(1:(round(np/2)),:);
                bspec(1,:)=bspec(1,:)*0.5; %remove baseline error
                cspec=ifft(bspec,np)/0.5; %scale to match original;
                NmrData.SPECTRA=cspec;
                
            otherwise
                error('illegal choice')
        end
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function GroupIcoshiftMode_Callback( ~, ~)
        zoom off
        pan off
        switch get(hBGroupIcoshiftMode,'SelectedObject')
            case hRadio1IcoshiftMode
                set(hEditIntervals,'Enable','Off')
            case hRadio2IcoshiftMode
                set(hEditIntervals,'Enable','On')
            case hRadio3IcoshiftMode
                set(hEditIntervals,'Enable','Off')
            otherwise
                error('illegal choice')
        end
        guidata(hMainFigure,NmrData);
    end
%----CLASS CONSTRUCTION-----------    
    function addClass(~,~)
        NmrData=guidata(hMainFigure);
        Tab = get(hTabGroupChemometrics,'SelectedTab');
        switch Tab
            case hTabPCA
                Class = round(str2double(get(hEditClassPCA,'string')));
                if isnan(Class)
                    Class = get(hEditClassPCA,'string');
                end
                Beginning = round(str2double(get(hEditBeginningClassPCA,'string')));
                End = round(str2double(get(hEditEndClassPCA,'string')));
            case hTabPLSDA 
                Class = round(str2double(get(hEditClassPLSDA,'string')));
                if isnan(Class)
                    Class = get(hEditClassPLSDA,'string');
                end                
                Beginning = round(str2double(get(hEditBeginningClassPLSDA,'string')));
                End = round(str2double(get(hEditEndClassPLSDA,'string')));         
            case hTabOPLSDA 
                Class = round(str2double(get(hEditClassOPLSDA,'string')));
                if isnan(Class)
                    Class = get(hEditClassOPLSDA,'string');
                end                
                Beginning = round(str2double(get(hEditBeginningClassOPLSDA,'string')));
                End = round(str2double(get(hEditEndClassOPLSDA,'string')));                   
        end
            
        OldData = get(hClassTable,'data');
        NewData = [Class Beginning End];
        
        if strcmpi(Class,'import') % import case (temporary solution to import from txt or workspace)        
%             Class organization to Fay's data
            SequenceTable = evalin('base','Classes');
            set(hClassTable,'Data',SequenceTable);  
            set(hClassTablePLSDA,'Data',SequenceTable);
            set(hClassTableOPLSDA,'Data',SequenceTable);
            NmrData.Classes.SequenceTable = SequenceTable;
            if isfield(NmrData.Classes,'Labels')
                NmrData.Classes = rmfield(NmrData.Classes,'Labels');
            end     
        elseif isnan(Class) || isnan(Beginning) || isnan(End)   
            % ---- PCA
            set(hEditClassPCA,'string',num2str(1))
            set(hEditBeginningClassPCA,'string',num2str(1))
            set(hEditEndClassPCA,'string',num2str(1))
            % ---- PLSDA
            set(hEditClassPLSDA,'string',num2str(1))
            set(hEditBeginningClassPLSDA,'string',num2str(1))
            set(hEditEndClassPLSDA,'string',num2str(1))            
            % ---- OPLSDA
            set(hEditClassOPLSDA,'string',num2str(1))
            set(hEditBeginningClassOPLSDA,'string',num2str(1))
            set(hEditEndClassOPLSDA,'string',num2str(1))            
            warndlg('Class, Beginning or End must be a number','Warning');           
            return
        elseif Class < 1
            set(hEditClassPCA,'string',num2str(1))
            set(hEditClassPLSDA,'string',num2str(1))
            set(hEditClassOPLSDA,'string',num2str(3))
            warndlg('Number of classes must be greater than 0','Warning');
            return
        elseif Class > NmrData.arraydim
            set(hEditClassPCA,'string',num2str(1))
            set(hEditClassPLSDA,'string',num2str(1))
            set(hEditClassOPLSDA,'string',num2str(1))
            warndlg('Number of class must be less than the number of samples','Warning');
            return
        elseif Beginning > NmrData.arraydim
            set(hEditBeginningClassPCA,'string',num2str(1))
            set(hEditBeginningClassPLSDA,'string',num2str(1))
            set(hEditBeginningClassOPLSDA,'string',num2str(1))
            warndlg('The beginning number must be less than the number of samples','Warning');
            return
        elseif End > NmrData.arraydim
            set(hEditEndClassPCA,'string',num2str(1))
            set(hEditEndClassPLSDA,'string',num2str(1))
            set(hEditEndClassOPLSDA,'string',num2str(1))
            warndlg('The end number must be less than the number of samples','Warning');
            return            
        elseif Beginning > End
            set(hEditBeginningClassPCA,'string',num2str(1))
            set(hEditEndClassPCA,'string',num2str(1))
            set(hEditBeginningClassPLSDA,'string',num2str(1))
            set(hEditEndClassPLSDA,'string',num2str(1))   
            set(hEditBeginningClassOPLSDA,'string',num2str(1))
            set(hEditEndClassOPLSDA,'string',num2str(1))               
            warndlg('Make sure the new class sample string is in ascending order','Warning');
            return
        elseif ~isempty(OldData)            
            if any(ismember(OldData(:,1),Class))
                answer = questdlg('The new class has been registered before. Do you want to merge this class with the old one', ...
                    'Creating a new ', ...
                    'Merge','Overwrite','Cancel','Merge');
                % Handle response
                switch answer
                    case 'Merge'
                        NewData = [OldData;NewData];            
                        NewData = sortrows(NewData,[1 2]);
                        set(hClassTable,'Data',NewData);
                        set(hClassTablePLSDA,'Data',NewData);
                        set(hClassTableOPLSDA,'Data',NewData);
                        NmrData.Classes.SequenceTable = NewData;
                        if isfield(NmrData.Classes,'Labels')
                            NmrData.Classes = rmfield(NmrData.Classes,'Labels');
                        end
                    case 'Overwrite'
                        c = ismember(OldData(:,1),Class);
                        OldData(c,:) = [];
                        NewData = [OldData;NewData]; 
                        NewData = sortrows(NewData,[1 2]);
                        set(hClassTable,'Data',NewData);
                        set(hClassTablePLSDA,'Data',NewData);
                        set(hClassTableOPLSDA,'Data',NewData);
                        NmrData.Classes.SequenceTable = NewData;
                        if isfield(NmrData.Classes,'Labels')
                            NmrData.Classes = rmfield(NmrData.Classes,'Labels');
                        end
                    case 'Cancel'
                        return
                end            
            else
                NewData = [OldData;NewData];            
                NewData = sortrows(NewData,[1 2]);
                set(hClassTable,'Data',NewData);  
                set(hClassTablePLSDA,'Data',NewData);
                set(hClassTableOPLSDA,'Data',NewData); 
                NmrData.Classes.SequenceTable = NewData;
                if isfield(NmrData.Classes,'Labels')
                    NmrData.Classes = rmfield(NmrData.Classes,'Labels');
                end
            end
        else
            NewData = [OldData;NewData];            
            NewData = sortrows(NewData,[1 2]);
            set(hClassTable,'Data',NewData);  
            set(hClassTablePLSDA,'Data',NewData);
            set(hClassTableOPLSDA,'Data',NewData);
            NmrData.Classes.SequenceTable = NewData;
            if isfield(NmrData.Classes,'Labels')
                NmrData.Classes = rmfield(NmrData.Classes,'Labels');
            end
        end       
        guidata(hMainFigure,NmrData);
    end
    function deleteClass(~,~)
        NmrData=guidata(hMainFigure);
        Tab = get(hTabGroupChemometrics,'SelectedTab');
        switch Tab
            case hTabPCA
                Class = round(str2double(get(hEditClassPCA,'string')));
                Beginning = round(str2double(get(hEditBeginningClassPCA,'string')));
                End = round(str2double(get(hEditEndClassPCA,'string')));                
            case hTabPLSDA 
                Class = round(str2double(get(hEditClassPLSDA,'string')));
                Beginning = round(str2double(get(hEditBeginningClassPCA,'string')));
                End = round(str2double(get(hEditEndClassPCA,'string')));    
            case hTabOPLSDA 
                Class = round(str2double(get(hEditClassOPLSDA,'string')));
                Beginning = round(str2double(get(hEditBeginningClassOPLSDA,'string')));
                End = round(str2double(get(hEditEndClassOPLSDA,'string')));                    
        end        
               
        OldData = get(hClassTable,'data');
        if isnan(Class)
            Class = OldData(end,1);
            OldData(end,:) = [];
            set(hClassTable,'Data',OldData);
            set(hClassTablePLSDA,'Data',OldData);
            set(hClassTableOPLSDA,'Data',OldData);
            if isfield(NmrData.Classes,'Labels')
                NmrData.Classes = rmfield(NmrData.Classes,'Labels');
            end
        elseif Class < 1
            set(hEditClassPCA,'string',num2str(1))
            warndlg('Number of classes must be greater than 0','Warning');
            return
        elseif Beginning < 1
            set(hEditBeginningClassPCA,'string',num2str(1))
            set(hEditBeginningClassPLSDA,'string',num2str(1))
            set(hEditBeginningClassOPLSDA,'string',num2str(1))
            warndlg('Number of sample must be greater than 0','Warning');
            return            
        elseif Class > NmrData.arraydim
            set(hEditClassPCA,'string',num2str(1))
            warndlg('Number of class must be less than the number of samples','Warning');
            return
        elseif Beginning > NmrData.arraydim
            set(hEditBeginningClassPCA,'string',num2str(1))
            set(hEditBeginningClassPLSDA,'string',num2str(1))
            set(hEditBeginningClassOPLSDA,'string',num2str(1))
            warndlg('The beginning number must be less than the number of samples','Warning');
            return
        elseif End > NmrData.arraydim
            set(hEditEndClassPCA,'string',num2str(1))
            set(hEditEndClassPLSDA,'string',num2str(1))
            set(hEditEndClassOPLSDA,'string',num2str(1))
            warndlg('The end number must be less than the number of samples','Warning');
            return            
        elseif any(ismember(OldData(:,1),Class)) && (isempty(Beginning) || isnan(Beginning))
            c = ismember(OldData(:,1),Class);
            OldData(c,:) = [];
            set(hClassTable,'Data',OldData); 
            set(hClassTablePLSDA,'Data',OldData);
            set(hClassTableOPLSDA,'Data',OldData);
            if isfield(NmrData.Classes,'Labels')
                NmrData.Classes = rmfield(NmrData.Classes,'Labels');
            end
        elseif any(ismember(OldData(:,1),Class)) && ~isempty(Beginning)
            a = ismember(OldData(:,1),Class);
            b = ismember(OldData(:,2),Beginning);
            if sum((b & a)) > 0
                c = (a & b); % both rows are true
                OldData(c,:) = [];
                set(hClassTable,'Data',OldData); 
                set(hClassTablePLSDA,'Data',OldData);
                set(hClassTableOPLSDA,'Data',OldData);
                if isfield(NmrData.Classes,'Labels')
                    NmrData.Classes = rmfield(NmrData.Classes,'Labels');
                end
            else
                set(hEditBeginningClassPCA,'string',num2str(0))
                warndlg('There is no sample associated with this class','Warning');
            end
        else
        end
        NmrData.Classes.SequenceTable = OldData;
        
        if isfield(NmrData.Classes,'Labels')
            Labels = '';
            if isnan(Class)
                Class = OldData(end,1);
            end
            row = find(NmrData.Classes.Labels.Classes==NmrData.Classes.Labels.NClasses(Class,:)); 
            NmrData.Classes.Labels.UserData(row,end) = cellstr(Labels);                
        else            
        end
        guidata(hMainFigure,NmrData);
    end
    function labelClass(~,~)
        NmrData=guidata(hMainFigure);

        if ~isfield(NmrData,'Classes')
            warndlg('It is necessary at least one class to open the label options','Warning');
            return
        elseif sum(unique(NmrData.Classes.SequenceTable(:,1))) == 0
            warndlg('It is necessary at least one class to open the label options','Warning');
            return            
        else
            Classes = NmrData.Classes.SequenceTable(:,1);
        end   
 
        % Checking if the user tried to open another figure to generate labels
        hClassFigure = findobj('Type','figure','Tag','ClassGUI');
        if ~isempty(hClassFigure)
            close(hClassFigure) % close previous figure
        end

        % Create the GUI to visualize the classes
        if ~isfield(NmrData.Classes,'Labels')
            NmrData.Classes.Labels = ClassGUI(Classes,NmrData.Classes.SequenceTable,NmrData.arraydim);
        elseif size(unique(NmrData.Classes.Labels.UserData(:,3)),1) == 2 || size(NmrData.Classes.Labels.UserData(:,1),1) ~= NmrData.arraydim
            if size(NmrData.Classes.Labels.UserData,2) == 4
                NmrData.Classes.Labels = ClassGUI(Classes,NmrData.Classes.SequenceTable,NmrData.arraydim,NmrData.Classes.Labels.Modified(:,4),NmrData.Classes.Labels.Modified);
            else
                NmrData.Classes.Labels = ClassGUI(Classes,NmrData.Classes.SequenceTable,NmrData.arraydim,[],NmrData.Classes.Labels.Modified);
            end            
        elseif size(NmrData.Classes.Labels.UserData,2) == 3 && size(NmrData.Classes.Labels.UserData,2) ~= 4
            NmrData.Classes.Labels = ClassGUI(Classes,NmrData.Classes.SequenceTable,NmrData.arraydim);
        else
            NmrData.Classes.Labels = ClassGUI(Classes,NmrData.Classes.SequenceTable,NmrData.arraydim,NmrData.Classes.Labels.UserData(:,4));
        end

        % Check if all labels were deleted by the user
%         if size(NmrData.Classes.Labels.UserData,2) == 4
            

        guidata(hMainFigure,NmrData);
    end
%----BIN----- --------------------
    function doBin(source,~)
         NmrData=guidata(hMainFigure);
         NmrData.pfgnmrdata=PreparePfgnmrdata();
         pfgnmrdata=NmrData.pfgnmrdata;   
         % Checking the chemometric method used for binning
         if strcmpi(source.Tag,'PCA analysis v 1.0')
            NmrData.pca.info = source.Tag;
            method = 'PCA';
            temp = NmrData.pca;
         elseif strcmpi(source.Tag,'PLSDA analysis v 1.0')
            NmrData.plsda.info = source.Tag;
            method = 'PLSDA';
            temp = NmrData.plsda;
         elseif strcmpi(source.Tag,'OPLSDA analysis')
            NmrData.oplsda.info = source.Tag;
            method = 'OPLSDA';
            temp = NmrData.oplsda;
         elseif strcmpi(source.Tag,'STOCSY analysis v 1.0')
            NmrData.stocsy.info = source.Tag;
            method = 'STOCSY';
            temp = NmrData.stocsy;
         end
            
         % Checking the active area of the spectrum
         speclim=xlim(hAxes);
         if speclim(1)<NmrData.sp
             speclim(1)=NmrData.sp;
         end
         if speclim(2)>(NmrData.sw+NmrData.sp)
             speclim(2)=(NmrData.sw+NmrData.sp);
         end

         % Getting the data matrix
         if ~isfield(temp,'TypeModel') % For a new Model
             % Determining the active area of the spectrum open in GNAT based on the ppm scale 
             for k=1:length(pfgnmrdata.Ppmscale)
                 if (pfgnmrdata.Ppmscale(k)>speclim(1))
                    begin=k-1;
                    k1=begin;
                    break;
                 end
             end            
             for k=begin:length(pfgnmrdata.Ppmscale)
                if (pfgnmrdata.Ppmscale(k)>=speclim(2))
                    endrange=k;
                    break;
                end
             end             

             % Making a a new stucture for the new ppm scale
             pfgnmrdata.sp=pfgnmrdata.Ppmscale(k1);
             pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(k1);
             pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(k1:endrange);
             pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(k1:endrange,:);
             pfgnmrdata.np=length(pfgnmrdata.Ppmscale);
    
             % Saving the new matrix depending on the method (PCA,PLSDA or OPLSDA) used by the user
             matrix = pfgnmrdata.SPECTRA';
             ppscale = pfgnmrdata.Ppmscale;  
             input.thresflag=0;
             analyzedata=PrepareAnalyzeData(input); 
         else % For a imported Model
             % Determining the active area of the spectrum open in GNAT based on the ppm scale 
             for k=1:length(pfgnmrdata.Ppmscale)
                 if (pfgnmrdata.Ppmscale(k)>speclim(1))
                    begin=k-1;
                    k1=begin;
                    break;
                 end
             end
            
             for k=begin:length(pfgnmrdata.Ppmscale)
                if (pfgnmrdata.Ppmscale(k)>=speclim(2))
                    endrange=k;
                    break;
                end
             end

             % Checking if Normalization was applied
             if isfield(NmrData,'Normalised')
                 pfgnmrdata.SPECTRA = NmrData.Normalised.matrix';
             end

             % Making a a new stucture for the new ppm scale
             pfgnmrdata.sp=pfgnmrdata.Ppmscale(k1);
             pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(k1);
             pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(k1:endrange);
             pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(k1:endrange,:);
             pfgnmrdata.np=length(pfgnmrdata.Ppmscale);      

            % Saving the new matrix depending on the method (PCA,PLSDA, OPLSDA and STOCSY) used by the user
             if strcmpi(method,'PCA')
                 matrix = NmrData.pca.raw_matrix;
                 ppscale = NmrData.pca.Ppmscale;        
                 analyzedata=NmrData.pca.ExportInf.analyzedata;     
             elseif strcmpi(method,'PLSDA')
                 matrix = NmrData.plsda.raw_matrix;
                 ppscale = NmrData.plsda.Ppmscale;        
                 analyzedata=NmrData.plsda.ExportInf.analyzedata;                   
             elseif strcmpi(method,'OPLSDA')
                 matrix = NmrData.oplsda.raw_matrix;
                 ppscale = NmrData.oplsda.Ppmscale;        
                 analyzedata=NmrData.oplsda.ExportInf.analyzedata;  
             elseif strcmpi(method,'STOCSY')
                 matrix = NmrData.stocsy.raw_matrix;
                 ppscale = NmrData.stocsy.Ppmscale;        
                 analyzedata=NmrData.stocsy.ExportInf.analyzedata;                   
             end
         end     
         
         % Checking if the user tried to open another figure to bin data
         hBinFigure = findobj('Type','figure','Tag','Bin');
         if ~isempty(hBinFigure)
             close(hBinFigure) % close previous figure
         end
         BinningModel=BinPCA(ppscale,matrix,analyzedata);

         % Saving the binning model
         if strcmpi(method,'PCA')
             NmrData.pca.BinPCA=BinningModel;
         elseif strcmpi(method,'PLSDA')             
             NmrData.plsda.BinPCA=BinningModel;              
         elseif strcmpi(method,'OPLSDA')
             NmrData.oplsda.BinPCA=BinningModel; 
         elseif strcmpi(method,'STOCSY')
             NmrData.stocsy.BinPCA=BinningModel;              
         end
         guidata(hMainFigure,NmrData);
    end
%----NORMALIZATION ---------------    
    function normalize_GUI(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata(); 
        pfgnmrdata=NmrData.pfgnmrdata; 

        % Checking if the binning limits was calculated
        hBinFigure = findobj('Type','figure','Tag','Bin');
        if ~isempty(hBinFigure)
            BinPCA = guidata(hBinFigure);
            if isempty(BinPCA.non_normalized_buckets)
                return
            end 
            NmrData.Normalised.GNAT_matrix=real(BinPCA.normalized_buckets');
        else
            % Clipping the matrix based on the active spectrum showed in GNAT
             % Checking the active area of the spectrum
             speclim=xlim(hAxes);
             if speclim(1)<NmrData.sp
                 speclim(1)=NmrData.sp;
             end
             if speclim(2)>(NmrData.sw+NmrData.sp)
                 speclim(2)=(NmrData.sw+NmrData.sp);
             end
            for k=1:length(pfgnmrdata.Ppmscale)
               if (pfgnmrdata.Ppmscale(k)>speclim(1))
                  begin=k-1;
                  k1=begin;
                  break;
               end
            end       
            for k=begin:length(pfgnmrdata.Ppmscale)
               if (pfgnmrdata.Ppmscale(k)>=speclim(2))
                   endrange=k;
                   break;
               end
            end

            button_state = get(hExcludeShow,'Value');
            if button_state == 1
                lft=(NmrData.excludelinepoints-NmrData.sp)/NmrData.sw;
                lft=round(lft*NmrData.fn);
                outp = [];
                for m = 1:2:size(lft,2)
                    out = lft(1,m):lft(1,m+1);
                    outp = [outp  out];
                end
            else
                outp =[];
            end

            SPECTRA = NmrData.SPECTRA;
            SPECTRA(outp,:) = 0;

            NmrData.Normalised.GNAT_matrix=real(SPECTRA(k1:endrange,:));
            NmrData.Normalised.GNAT_raw_matrix=real(NmrData.SPECTRA);
        end
        guidata(hMainFigure,NmrData);

        % Checking if the user tried to open another figure to Normalize data
        NormFig = findobj('Type','figure','Tag','NormGUI');
        if ~isempty(NormFig)
            close(NormFig) % close previous figure
        end
        normalizeGUI()

        guidata(hMainFigure,NmrData);
    end
%----PCA----- --------------------
    function doPCA(~,~)
        % Getting data from GNAT
        NmrData=guidata(hMainFigure);

        NmrData.pca.info = 'PCA analysis v 1.0';

        % Checking the active area of the spectrum
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
             speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
             speclim(2)=(NmrData.sw+NmrData.sp);
        end

        % Clipping the matrix based on the active spectrum in GNAT
        if ~isfield(NmrData.pca,'TypeModel') % New model case
            input.thresflag=0;
            analyzedata=PrepareAnalyzeData(input);              
            NmrData.pfgnmrdata=PreparePfgnmrdata();
            pfgnmrdata=NmrData.pfgnmrdata; 
             for k=1:length(pfgnmrdata.Ppmscale)
                 if (pfgnmrdata.Ppmscale(k)>speclim(1))
                    begin=k-1;
                    k1=begin;
                    break;
                 end
             end
            
             for k=begin:length(pfgnmrdata.Ppmscale)
                if (pfgnmrdata.Ppmscale(k)>=speclim(2))
                    endrange=k;
                    break;
                end
             end

             % %Checking if Normalization was applied
             % if isfield(NmrData,'Normalised')
             %     pfgnmrdata.SPECTRA = NmrData.Normalised.matrix';
             %     % excluding regions
             %     if isfield(NmrData,'exclude')
             %        if get(hExcludeShow,'Value')
             %            for k=1:NmrData.arraydim
             %                pfgnmrdata.SPECTRA(:,k)=...
             %                    pfgnmrdata.SPECTRA(:,k).*isnan(NmrData.exclude');
             %            end
             %        end
             %    end
             % end

             % Making a new stucture
             pfgnmrdata.sp=pfgnmrdata.Ppmscale(k1);
             pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(k1);
             pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(k1:endrange);
             pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(k1:endrange,:);
             pfgnmrdata.np=length(pfgnmrdata.Ppmscale);

             NmrData.pca.ncomp=str2double(get(hEditNcompPCA,'String'));    % Get number of components          
             NmrData.pca.confvalue=str2double(get(hEditConfPCA,'String')); % Get confidence value
             NmrData.pca.ppmscale=pfgnmrdata.Ppmscale;

             matrix = pfgnmrdata.SPECTRA';                                 % Get the raw matrix                         
             NmrData.pca.raw_matrix = matrix;

        else % Load model case
            NmrData.pca.ncomp=str2double(get(hEditNcompPCA,'String'));     % Get number of components          
            NmrData.pca.confvalue=str2double(get(hEditConfPCA,'String'));  % Get confidence value
            pfgnmrdata.SPECTRA=pca.raw_matrix';

            % if NmrData.pca.ncomp < size 
        end  
        
        % 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 
        elseif isfield(NmrData.pca,'BinPCA')
            NmrData.pca = rmfield(NmrData.pca, 'BinPCA');
        end

        % Checking if samples was removed using the ClassGUI
        if isfield(NmrData,'Classes')  
            if isfield(NmrData.Classes,'Labels') 
                if isfield(NmrData.Classes.Labels,'UserData') 
                    if size(unique(NmrData.Classes.Labels.UserData(:,3)),1) == 2
                        idx_rm = find(strcmp(NmrData.Classes.Labels.Modified(:,3), 'no'));
                        NmrData.pca.outlier = idx_rm;
                    end
                end
            end
        end
 
        if ~exist('idx_rm','var')     
            idx_rm = 0;
            NmrData.pca.outlier = idx_rm;
        end

        % Separating the data matrix for PCA calculation 
        opt.prepr{1} = 'mean';
        if isfield(NmrData.pca,'BinPCA') 
            % Model with bin method applied
            matrix = pfgnmrdata.SPECTRA'; 
            m=NmrData.pca.BinPCA.normalized_buckets;
            %Checking if Normalization was applied
            if isfield(NmrData,'Normalised')
                m = NmrData.Normalised.matrix;
               %  % excluding regions
               %  if isfield(NmrData,'exclude')
               %     if get(hExcludeShow,'Value')
               %         for k=1:NmrData.arraydim
               %             pfgnmrdata.SPECTRA(:,k)=...
               %                 pfgnmrdata.SPECTRA(:,k).*isnan(NmrData.exclude');
               %         end
               %     end
               % end
            end

            if any(idx_rm)
                m(idx_rm,:) = [];
            end            
            NmrData.pca.parameters = pca_svd(m, NmrData.pca.ncomp,NmrData.pca.confvalue,opt);
            NmrData.pca.raw_matrix = matrix; % raw data without preprocessing
        else
            if isfield(NmrData.pca,'TypeModel')
                if any(idx_rm)
                    NmrData.pca.raw_matrix(idx_rm,:) = [];
                end                    
                NmrData.pca.parameters = pca_svd(NmrData.pca.raw_matrix, NmrData.pca.ncomp,NmrData.pca.confvalue,opt);     
            else
                matrix = pfgnmrdata.SPECTRA';   
                if isfield(NmrData,'Normalised')
                    matrix = NmrData.Normalised.matrix;
                end
                if any(idx_rm)
                    matrix(idx_rm,:) = [];
                end    
                NmrData.pca.parameters = pca_svd(matrix, NmrData.pca.ncomp,NmrData.pca.confvalue,opt);
                NmrData.pca.raw_matrix = matrix; % raw data 
            end           
        end
                
        % Table Variance Captured by PCA
        TableData(:,1)=NmrData.pca.parameters.Eigenvalue;
        TableData(:,2)=NmrData.pca.parameters.var_exp{1,1};
        TableData(:,3)=NmrData.pca.parameters.var_cum{1,1};
        set(hTableEigenvalues,'Data',TableData);     
        
        % Plot Options
        if get(hPCAScoresPlotUse,'Value') %Turn on/off Scores plots 
            NmrData.pca.PlotOpt(1) = 1;
        else
            NmrData.pca.PlotOpt(1) = 0;
        end
        if get(hPCALoadingsPlotUse,'Value') %Turn on/off Loadings plots
            NmrData.pca.PlotOpt(2) = 1;
        else
            NmrData.pca.PlotOpt(2) = 0;
        end
        if get(hPCAResidualPlotUse,'Value') %Turn on/off Residual plots
            NmrData.pca.PlotOpt(3) = 1;
        else
            NmrData.pca.PlotOpt(3) = 0;
        end            
        X=sum(NmrData.pca.PlotOpt);
        
        % PCAplots GUI imput to export data
        if X > 0
            ExportInf.filename = NmrData.filename;
            ExportInf.type = NmrData.type;
            ExportInf.sfrq = NmrData.sfrq;
            ExportInf.np = NmrData.np;
            ExportInf.sw =NmrData.sw;           
            if ~isfield(NmrData.pca,'TypeModel') % Load Model case              
                ExportInf.analyzedata = analyzedata;
            else
                ExportInf.analyzedata = NmrData.pca.ExportInf.analyzedata;
            end      
            if isfield(NmrData.pca,'BinPCA')
                ExportInf.bin.Field = 'Yes';
                ExportInf.bin.Bucket = NmrData.pca.BinPCA.Bucket;
                ExportInf.bin.Slackness = NmrData.pca.BinPCA.Slackness;
                ExportInf.bin.Variables = size(NmrData.pca.BinPCA.non_normalized_buckets,2);
            else
                ExportInf.bin.Field = 'No';
                ExportInf.bin.Bucket = 0;
                ExportInf.bin.Slackness = 0;
                ExportInf.bin.Variables = 0;                
            end            
        else
            warndlg('No plot selected (Check the ''Plots'' panel)')
            uiwait(gcf)
            return
        end   
        
        % Checking with samples were removed by the user
        NmrData.pca.prune = NmrData.prune;

        % Basic Class Construction
        Classes = zeros(NmrData.arraydim,1);
        SequenceTable = get(hClassTable,'data');

        % Saving original size of the array of samples
        NmrData.pca.arraydim = NmrData.arraydim;

        % Construction of Class table for user imput
        if ~isempty(SequenceTable)
            for n = 1:size(SequenceTable,1)            
                B = SequenceTable(n,2);
                E = SequenceTable(n,3); 
                samples = size(SequenceTable(n,2):1:SequenceTable(n,3),1);
                for i = B:E
                    Classes(B:E,1) = repmat(SequenceTable(n,1), samples, 1);
                end
            end    
        end

        % Cleaning Classes that the user removed
        NmrData.pca.Classes = Classes;
        if any(idx_rm)
            Classes(idx_rm,:) = [];
            NmrData.Classes.Labels.UserData(idx_rm,:) = [];
        end    

        % Run PCAplots GUI to present the results
        if ~isfield(NmrData,'Classes')
            PCAplots('PCA',NmrData.pca,ExportInf,Classes);
        elseif ~isfield(NmrData.Classes,'Labels')   
            PCAplots('PCA',NmrData.pca,ExportInf,Classes);      
        elseif size(NmrData.Classes.Labels.UserData,2) == 3
            PCAplots('PCA',NmrData.pca,ExportInf,Classes); 
        elseif size(NmrData.Classes.Labels.UserData,2) > 3 
            PCAplots('PCA',NmrData.pca,ExportInf,Classes,NmrData.Classes.Labels.UserData(:,4)); 
        end    

        guidata(hMainFigure,NmrData);
    end
%     function LoadModelPCA(~,~,Path)
%         NmrData=guidata(hMainFigure);
%         NmrData.pca.info = 'PCA analysis v 1.0';
%         msgA = 'Loading a model will overwrite previous model';
%         msgB = 'Loading a model will overwrite previous data';       
%         title = 'Confirm Load model';
%         if isfield(NmrData.pca, 'TypeModelLoaded')
%             answer = questdlg(msgA, title, ...
%             'Overwrite','Cancel','Cancel');  
%             switch answer
%                 case 'Overwrite'
%                     if nargin==3
%                         filepath=Path;
%                     else            
%                         [filename, pathname] = uigetfile('*.mat','Open PCA model.mat');
%                         if isnumeric(filename) || isnumeric(pathname)
%                             if filename==0 || pathname==0
%                                 return
%                             end
%                         end
%                         filepath=[pathname filename];
%                     end
%                     S=load(filepath,'-mat');    
%                     % Copy over all relevant parameters
%                     names=fieldnames(S);
%                     for nstruct=1:length(names)
%                         NmrData.(names{nstruct})=S.(names{nstruct});
%                     end
%                     NmrData.pca.TypeModelLoaded = 1;
%                     NmrData.arraydim = size(NmrData.pca.parameters.mean_matrix,1);
%                     set(hEditNcompPCA,'String',num2str(NmrData.pca.ncomp))
%                     set(hEditConfPCA,'String',num2str(NmrData.pca.confvalue))
%                 case 'Cancel'
%                     return
%             end
%         elseif ~isempty(NmrData.arraydim)  
%             answer = questdlg(msgB, title, ...
%             'Overwrite','Cancel','Cancel');  
%             switch answer
%                 case 'Overwrite'
%                     if nargin==3
%                         filepath=Path;
%                     else            
%                         [filename, pathname] = uigetfile('*.mat','Open PCA model.mat');
%                         if isnumeric(filename) || isnumeric(pathname)
%                             if filename==0 || pathname==0
%                                 return
%                             end
%                         end
%                         filepath=[pathname filename];
%                     end
%                     S=load(filepath,'-mat');    
%                     % Copy over all relevant parameters
%                     names=fieldnames(S);
%                     for nstruct=1:length(names)
%                         NmrData.(names{nstruct})=S.(names{nstruct});
%                     end
%                     NmrData.pca.TypeModelLoaded = 1;
%                     NmrData.arraydim = size(NmrData.pca.parameters.mean_matrix,1);
%                     set(hEditNcompPCA,'String',num2str(NmrData.pca.ncomp))
%                     set(hEditConfPCA,'String',num2str(NmrData.pca.confvalue))                       
%                 case 'Cancel'
%                     return
%             end
%         else
%             if nargin==3
%                 filepath=Path;
%             else            
%                 [filename, pathname] = uigetfile('*.mat','Open PCA model.mat');
%                 if isnumeric(filename) || isnumeric(pathname)
%                     if filename==0 || pathname==0
%                         return
%                     end
%                 end
%                 filepath=[pathname filename];
%             end
%             S=load(filepath,'-mat');    
%             % Copy over all relevant parameters
%             names=fieldnames(S);
%             for nstruct=1:length(names)
%                 NmrData.(names{nstruct})=S.(names{nstruct});
%             end
%             NmrData.pca.TypeModelLoaded = 1;
%             NmrData.arraydim = size(NmrData.pca.parameters.mean_matrix,1);
%             set(hEditNcompPCA,'String',num2str(NmrData.pca.ncomp))
%             set(hEditConfPCA,'String',num2str(NmrData.pca.confvalue))                       
%         end   
%         msgbox('Operation Completed');
%         guidata(hMainFigure,NmrData);
%     end
    function EditComponent_Callback(source,~)
        comp=round(str2double(get(hEditNcompPCA,'String'))); 
        Compbutton = source.Tag;
        if strcmpi(Compbutton,'PlusComp')
            comp = comp+1;
            set(hEditNcompPCA,'String',num2str(comp));
        elseif strcmpi(Compbutton,'MinusComp')
            comp = comp-1;
            set(hEditNcompPCA,'String',num2str(comp));
        end    

        if isempty(comp)
            warndlg('Component number must be numeric')
            uiwait(gcf)
            set(hEditNcompPCA,'String',num2str(2));
        elseif isnan(comp)
            warndlg('Component number must be numeric')
            uiwait(gcf)
            set(hEditNcompPCA,'String',num2str(2));     
        elseif comp < 2
            warndlg('Component number must be bigger than 1')
            uiwait(gcf)
            set(hEditNcompPCA,'String',num2str(2)); 
        else
            comp=round(comp);
            if isfield(NmrData,'pca')
                if isfield(NmrData.pca,'TypeModel')
                    if comp<1
                        comp=1;
                    end
                    if comp>size(NmrData.pca.raw_matrix,1)
                        comp=size(NmrData.pca.raw_matrix,1);
                    end                 
                else
                    if comp<1
                        comp=1;
                    end
                    if comp>numel(NmrData.SPECTRA(1,:))
                        comp=numel(NmrData.SPECTRA(1,:));
                    end  
                end
            else
                if comp<1
                    comp=1;
                end
                if comp>numel(NmrData.SPECTRA(1,:))
                    comp=numel(NmrData.SPECTRA(1,:));
                end   
            end
            set(hEditNcompPCA,'String',num2str(comp));
        end
    end
    function EditConfidence_Callback(source,~,~)
        confidence=str2double(get(hEditConfPCA,'String'));       
        Confbutton = source.Tag;
        if strcmpi(Confbutton,'PlusConf')
            confidence = confidence + 0.01;
            set(hEditConfPCA,'String',num2str(confidence));
        elseif strcmpi(Confbutton,'MinusConf')
            confidence = confidence - 0.01;
            set(hEditConfPCA,'String',num2str(confidence));
        end

        if isempty(confidence)
            warndlg('confidence number must be numeric and > than 0')
            uiwait(gcf)
            set(hEditConfPCA,'String',num2str(0.99));
        else
            if confidence<0.00
                confidence=0.00;
            end
            if confidence>0.99
                confidence=0.99;
            end
        end
        set(hEditConfPCA,'String',num2str(confidence));
    end  
%----PLSDA-----------------------
    function doPLSDA(~,~)
        % Getting data from GNAT
        NmrData=guidata(hMainFigure);
        input.thresflag=0;
        analyzedata=PrepareAnalyzeData(input);   

        % Data checking
        if isfield(NmrData.plsda,'BinPCA')
            if isempty(NmrData.plsda.BinPCA.non_normalized_buckets)
                NmrData.plsda = rmfield(NmrData.plsda, 'BinPCA');
            end
        end
        
        % Colecting information for Chemometrics GUI
        ExportInf.filename = NmrData.filename;
        ExportInf.type = NmrData.type;
        ExportInf.sfrq = NmrData.sfrq;
        ExportInf.np = NmrData.np;
        ExportInf.sw =NmrData.sw;           
        ExportInf.analyzedata = analyzedata;   
        ExportInf.Specscale = NmrData.plsda.ppmscale;
        % if isfield(NmrData.plsda,'BinPCA')
        %     ExportInf.bin.Field = 'Yes';
        %     ExportInf.bin.Bucket = NmrData.plsda.BinPCA.Bucket;
        %     ExportInf.bin.Slackness = NmrData.plsda.BinPCA.Slackness;
        %     ExportInf.bin.Variables = size(NmrData.plsda.BinPCA.non_normalized_buckets,2);
        % else
        %     ExportInf.bin.Field = 'No';
        %     ExportInf.bin.Bucket = 0;
        %     ExportInf.bin.Slackness = 0;
        %     ExportInf.bin.Variables = 0;                
        % end  
        
        % Verify if the user split the dataset into calibration and validation 
        if isempty (hTableCalVal)
            warndlg((sprintf('It is necessary first run the split cal/val panel')),'Warning');            
            return  
        end    

        % Combined conditional check using logical short-circuiting
        if isfield(NmrData, 'Classes') && ...
                isfield(NmrData.Classes, 'Labels') && ...
                isfield(NmrData.Classes.Labels, 'UserData') && ...
                size(unique(NmrData.Classes.Labels.UserData(:,3)), 1) == 2

            idx_rm = find(strcmp(NmrData.Classes.Labels.UserData(:,3), 'no'));
            NmrData.plsda.outlier = idx_rm;
        else
            idx_rm = [];
            NmrData.plsda.outlier = idx_rm;
        end  

        % Initiating the GUI
        % Checking if the user create labels for each class    
        [NmrData.Classes.Labels.Classes,~]=sortrows(NmrData.Classes.Labels.Classes);
        % Run PCAplots GUI to present the results    
        if size(NmrData.Classes.Labels.UserData,2) == 3
            PCAplots('PLSDA',NmrData.plsda,ExportInf,NmrData.Classes.Labels.Classes); 
        elseif size(NmrData.Classes.Labels.UserData,2) > 3 
            PCAplots('PLSDA',NmrData.plsda,ExportInf,NmrData.Classes.Labels.Classes,NmrData.Classes.Labels.Original(:,4)); 
        end         
        guidata(hMainFigure,NmrData);
    end
    function doCalVal(~,~)
        % Getting data from GNAT
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        pfgnmrdata=NmrData.pfgnmrdata;      

        % Checking the active area of the spectrum
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
             speclim(2)=(NmrData.sw+NmrData.sp);
        end
        
        % Clipping the matrix based on the active spectrum showed in GNAT
        for k=1:length(pfgnmrdata.Ppmscale)
           if (pfgnmrdata.Ppmscale(k)>speclim(1))
              begin=k-1;
              k1=begin;
              break;
           end
        end       
        for k=begin:length(pfgnmrdata.Ppmscale)
           if (pfgnmrdata.Ppmscale(k)>=speclim(2))
               endrange=k;
               break;
           end
        end
    
        % %Checking if Normalization was applied
        % if isfield(NmrData,'Normalised')
        %     pfgnmrdata.SPECTRA = NmrData.Normalised.matrix';
        %     % excluding regions
        %     if isfield(NmrData,'exclude')
        %         if get(hExcludeShow,'Value')
        %             for k=1:NmrData.arraydim
        %                 pfgnmrdata.SPECTRA(:,k)=...
        %                     pfgnmrdata.SPECTRA(:,k).*isnan(NmrData.exclude');
        %             end
        %         end
        %     end
        % end
        
        % Checking if samples was removed using the ClassGUI
        if isfield(NmrData,'Classes')  
            if isfield(NmrData.Classes,'Labels') 
                if isfield(NmrData.Classes.Labels,'UserData') 
                    if size(unique(NmrData.Classes.Labels.UserData(:,3)),1) == 2
                        idx_rm = find(strcmp(NmrData.Classes.Labels.Modified(:,3), 'no'));
                        NmrData.plsda.outlier = idx_rm;
                    end
                end
            end
        end

        if ~exist('idx_rm','var')
            idx_rm = 0;
            NmrData.plsda.outlier = idx_rm;
        end

        % Making a new stucture
        pfgnmrdata.sp=pfgnmrdata.Ppmscale(k1);
        pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(k1);
        pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(k1:endrange);
        pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(k1:endrange,:);
        pfgnmrdata.np=length(pfgnmrdata.Ppmscale);
        input.thresflag=0; %#ok<STRNU> 
        matrix = pfgnmrdata.SPECTRA'; 
        set(hProcessPLSDAButton,'Enable','on')

        % Check the distribution of Calibration and Validation
        Cal=round(str2double(get(hEditCalPLSDA,'String')));         
        Val = 100 - Cal;
        set(hEditValPLSDA,'String',num2str(Val));
        
        % Constructing vector array from classes table
        Classes = zeros(NmrData.arraydim,1);
        SequenceTable = get(hClassTable,'data');
        if isempty (SequenceTable)
            warndlg((sprintf('Before sppliting your dataset into Calibration and Validation, It is necessary first define one class to each sample')),'Warning');            
            return  
        else
            for n = 1:size(SequenceTable,1)            
                B = SequenceTable(n,2);
                E = SequenceTable(n,3); 
                samples = size(SequenceTable(n,2):1:SequenceTable(n,3),1);
                for i = B:E
                    Classes(B:E,1) = repmat(SequenceTable(n,1), samples, 1);
                end
            end    
        end        

        % Getting the method used to split data
        switch get(hPanelPLSDAPlots,'SelectedObject') 
            case hPLSk % Kenston pick
                NmrData.plsda.split='k';
            case hPLSd % Duplex freq
                NmrData.plsda.split='d';
            case hPLSs % Segments
                NmrData.plsda.split='s';        
        end     

        % Cleaning Classes/samples that the user removed
        NmrData.plsda.Classes = Classes;
        if any(idx_rm)
            Classes(idx_rm,:) = [];
            Labels = NmrData.Classes.Labels.UserData;
            Labels(idx_rm,:) = [];
            matrix(idx_rm,:) = [];
        end

        % Checking if the binning limits was calculated
        hBinFigure = findobj('Type','figure','Tag','Bin');
        if ~isempty(hBinFigure)
            BinPCA = guidata(hBinFigure);
            NmrData.plsda.BinPCA=BinPCA;
            if any(idx_rm)
                NmrData.plsda.BinPCA.normalized_buckets(idx_rm,:) = [];
            end 
            % The user oppened the gui but did not press "Apply Bin"
            if ~isfield(NmrData.plsda.BinPCA,'normalized_buckets')
                NmrData.plsda = rmfield(NmrData.plsda, 'BinPCA');
            end 
        elseif isfield(NmrData.plsda,'BinPCA')
            NmrData.plsda = rmfield(NmrData.plsda, 'BinPCA');
        end

        NmrData.plsda.Classes = Classes;

        % Verify if each sample has its own class
        if nnz(~Classes) > 0
            warndlg((sprintf('It is necessary at least one class to each sample to continue \n Check Labels GUI for more information')),'Warning');            
            return  
        elseif isfield(NmrData.plsda,'BinPCA')
                       
            if isfield(NmrData,'Normalised')
                [objetos,xcal,xval,ycal,yval]=caltestda_pls(NmrData.Normalised.matrix,Classes,Cal,NmrData.plsda.split,[],[]);            

                xcal=NmrData.Normalised.matrix(objetos.treinamento,:);
                xval=NmrData.Normalised.matrix(objetos.teste,:);
            else
                [objetos,xcal,xval,ycal,yval]=caltestda_pls(NmrData.plsda.BinPCA.normalized_buckets,Classes,Cal,NmrData.plsda.split,[],[]);    
                
                xcal=NmrData.plsda.BinPCA.normalized_buckets(objetos.treinamento,:);
                xval=NmrData.plsda.BinPCA.normalized_buckets(objetos.teste,:);
            end

            ycal=NmrData.plsda.Classes(objetos.treinamento,:);
            yval=NmrData.plsda.Classes(objetos.teste,:); 
        else           
            if isfield(NmrData,'Normalised')
                % [objetos,xcal,xval,ycal,yval]=caltestda_pls(NmrData.Normalised.matrix,Classes,Cal,NmrData.plsda.split,[],[]);

                objetos.treinamento=[1	2	3	4	5	7	8	9	11	12	14	16	18	20	21	24	25	26	27	28	29	31	33	35	37	40	41	42	44	46	47	48	50	51	53	54	55	56	57	58	59	61	62	63	64	66	67	69	70	71	72	75	77	79	80	81];
                objetos.teste=[6	10	13	15	17	19	22	23	30	32	34	36	38	39	43	45	49	52	60	65	68	73	74	76	78];

                xcal=NmrData.Normalised.matrix(objetos.treinamento,:);
                xval=NmrData.Normalised.matrix(objetos.teste,:);
            else
                [objetos,xcal,xval,ycal,yval]=caltestda_pls(matrix,Classes,Cal,NmrData.plsda.split,[],[]);

                xcal=matrix(objetos.treinamento,:);
                xval=matrix(objetos.teste,:);
            end
    
            ycal=NmrData.plsda.Classes(objetos.treinamento,:);
            yval=NmrData.plsda.Classes(objetos.teste,:); 

        end

        if ~isempty(objetos)
            uiwait(msgbox('The Cal/Val calculation was carried out successfully','Cal/Val spliting','help','modal'));
        end

        % Constructing the dummy matrix:
        %   y1[1        y2[1 0 0
        %      1           1 0 0
        %      2           0 1 0
        %      2           0 1 0
        %      3           0 0 1
        %      3]          0 0 1]
        ycalM = vet_matrix(ycal,unique(Classes));
        yvalM = vet_matrix(yval,unique(Classes));        

        % Creating Tab for visualize cal/val split
        hTabTableCalVal.Parent = hTabGroupPLSDA;

        % Saving 'split' for PLS1-DA and PLS2-DA (See manual)
        NmrData.plsda.objetos = objetos;
        NmrData.plsda.xcal  = xcal;
        NmrData.plsda.xval  = xval;
        NmrData.plsda.ycalV = ycal; % Classes saved in vector format
        NmrData.plsda.yvalV = yval;          
        NmrData.plsda.ycalM = ycalM; % Classes saved in matrix format
        NmrData.plsda.yvalM = yvalM;      
        NmrData.plsda.ppmscale = pfgnmrdata.Ppmscale;

        % Table Cal/Val separation
        Cal = string(Classes); Val = string(Classes);
        Cal(NmrData.plsda.objetos.treinamento) = '.'; Cal(NmrData.plsda.objetos.teste) = 'X';  
        Val(NmrData.plsda.objetos.treinamento) = 'X'; Val(NmrData.plsda.objetos.teste) = '.'; 
        
        Samples = "Sample_" + string(1:size(Classes', 2));
        
        TableData(:,1)=cellstr(Samples');
        TableData(:,2)=cellstr(Cal);
        TableData(:,3)=cellstr(Val);
        
        set(hTableCalVal,'Data',TableData);
        NmrData.plsda.TableContent = get(hTableCalVal,'data');
        
%       Try to implement some colos in the Calibration/Test table in the future
%         colors = ['#FF0000';'#00FF00'];
%         colergen = @(cor,text) ['<html><table border=0 width=20 bgcolor=',cor,'><TR><TD>',text,'</TD></TR> </table><html>'];        
%         for n = 1:2
%             ChemoData.objetos.treinamento
%             ChemoData.objetos.teste
%             if isempty(aa)
%                 continue
%             elseif ~isempty(aa)
%                 for m = 1:num_aa                  
%                     k = aa(m) ;
%                     S{k,1} = colergen(colors(n,1:end),num2str(C(k,1)));                              
%                 end                
%             end
%         end    
                
        guidata(hMainFigure,NmrData);
    end
%----OPLS------------------------
    function doOPLS(~,~)
        NmrData=guidata(hMainFigure);
        input.thresflag=0;
        analyzedata=PrepareAnalyzeData(input);              
        NmrData.pfgnmrdata=PreparePfgnmrdata(); 
        
        % Colecting information for Chemometrics GUI
        ExportInf.filename = NmrData.filename;
        ExportInf.type = NmrData.type;
        ExportInf.sfrq = NmrData.sfrq;
        ExportInf.np = NmrData.np;
        ExportInf.sw =NmrData.sw;           
        ExportInf.analyzedata = analyzedata;                           
        
        % Verify if the user split the dataset into calibration and validation 
        if isempty (hTableCalValOPLS)
            warndlg((sprintf('It is necessary first run the split cal/val panel')),'Warning');            
            return  
        end
        
        % Initiating the GUI
        if ~isfield(NmrData.Classes,'Labels')   
            PCAplots('OPLS',NmrData.opls,ExportInf,NmrData.Classes.Labels.Classes);      
        else
            PCAplots('OPLS',NmrData.opls,ExportInf,NmrData.Classes.Labels.Classes,NmrData.Classes.Labels.UserData(:,end)); 
        end        
        guidata(hMainFigure,NmrData);
    end
    function doCalValOPLS(~,~)
        NmrData=guidata(hMainFigure);
        input.thresflag=0; %#ok<STRNU>
        %analyzedata=PrepareAnalyzeData(input);              
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        pfgnmrdata=NmrData.pfgnmrdata;      
        matrix = pfgnmrdata.SPECTRA'; 
        set(hProcessOPLSDAButton,'Enable','on')
        
        % Constructing vector array
        Classes = zeros(NmrData.arraydim,1);
        SequenceTable = get(hClassTableOPLS,'data');
        if ~isempty(SequenceTable)
            for n = 1:size(SequenceTable,1)            
                B = SequenceTable(n,2);
                E = SequenceTable(n,3); 
                samples = size(SequenceTable(n,2):1:SequenceTable(n,3),1);
                for i = B:E
                    Classes(B:E,1) = repmat(SequenceTable(n,1), samples, 1);
                end
            end    
        end        

        % Getting the method used to split data (See manual)
        switch get(hPanelOPLSDAPlots,'SelectedObject') 
            case hOPLSk %Kenston pick
                NmrData.opls.split='k';
            case hOPLSd %Duplex freq
                NmrData.opls.split='d';
            case hOPLSs %Segments
                NmrData.opls.split='s';        
        end
        
        % Verify if each sample has its own class
        if nnz(~Classes) > 0
            warndlg((sprintf('It is necessary at least one class to each sample to continue \n Check Labels GUI for more information')),'Warning');            
            return  
        else
            [objetos,xcal,xval,ycal,yval]=caltestda_pls(matrix,Classes,70,NmrData.opls.split,[],[]);
        end
        
        % Constructing the dummy matrix:

        %   y1[1        y2[1 0 0
        %      1           1 0 0
        %      2           0 1 0
        %      2           0 1 0
        %      3           0 0 1
        %      3]          0 0 1]
        % ycalM = vet_matrix(ycal,size(unique(Classes),1));
        % yvalM = vet_matrix(yval,size(unique(Classes),1));   
        ycalM = vet_matrix(ycal,unique(Classes));
        yvalM = vet_matrix(yval,unique(Classes));

        % Creating Tab for visualize cal/val split
        hTabTableCalValOPLS.Parent = hTabGroupOPLSDA;

        % Saving 'split' for PLS1-DA and PLS2-DA (See manual)
        NmrData.opls.objetos = objetos;
        NmrData.opls.xcal = xcal;
        NmrData.opls.xval = xval;
        NmrData.opls.ycalV = ycal; % Classes saved in vector format
        NmrData.opls.yvalV = yval;          
        NmrData.opls.ycalM = ycalM; % Classes saved in matrix format
        NmrData.opls.yvalM = yvalM;       
        NmrData.opls.LV = 5; % ----- Change for the user input later ------
        
        % Table Cal/Val separation
        Cal = string(Classes); Val = string(Classes);
        Cal(NmrData.opls.objetos.treinamento) = '.'; Cal(NmrData.opls.objetos.teste) = 'X';  
        Val(NmrData.opls.objetos.treinamento) = 'X'; Val(NmrData.opls.objetos.teste) = '.'; 
        
        Samples = "Sample_" + string(1:size(Classes', 2));
        
        TableData(:,1)=cellstr(Samples');
        TableData(:,2)=cellstr(Cal);
        TableData(:,3)=cellstr(Val);
        
        set(hTableCalVal,'Data',TableData);
        NmrData.opls.TableContent = get(hTableCalValOPLS,'data');

%       Try to implement some colos in the Calibration/Test table in the
%       future
%         colors = ['#FF0000';'#00FF00'];
%         colergen = @(cor,text) ['<html><table border=0 width=20 bgcolor=',cor,'><TR><TD>',text,'</TD></TR> </table><html>'];        
%         for n = 1:2
%             ChemoData.objetos.treinamento
%             ChemoData.objetos.teste
%             if isempty(aa)
%                 continue
%             elseif ~isempty(aa)
%                 for m = 1:num_aa                  
%                     k = aa(m) ;
%                     S{k,1} = colergen(colors(n,1:end),num2str(C(k,1)));                              
%                 end                
%             end
%         end    
                
        guidata(hMainFigure,NmrData);
    end
%----OPLSDA----------------------
    function doOPLSDA(~,~)
        % Getting data from GNAT
        NmrData=guidata(hMainFigure);
        input.thresflag=0;
        analyzedata=PrepareAnalyzeData(input);              
        
        % Colecting information for Chemometrics GUI
        ExportInf.filename = NmrData.filename;
        ExportInf.type = NmrData.type;
        ExportInf.sfrq = NmrData.sfrq;
        ExportInf.np = NmrData.np;
        ExportInf.sw = NmrData.sw;           
        ExportInf.analyzedata = analyzedata;
        ExportInf.Specscale =NmrData.Specscale; 

        % Verify if the user split the dataset into calibration and validation 
        if isempty (hTableCalValOPLSDA)
            warndlg((sprintf('It is necessary first run the split cal/val panel')),'Warning');            
            return  
        end

        % Checking if samples was removed using the ClassGUI
        if isfield(NmrData,'Classes')  
            if isfield(NmrData.Classes,'Labels') 
                if isfield(NmrData.Classes.Labels,'UserData') 
                    if size(unique(NmrData.Classes.Labels.UserData(:,3)),1) == 2
                        idx_rm = find(strcmp(NmrData.Classes.Labels.UserData(:,3), 'no'));
                        NmrData.oplsda.outlier = idx_rm;
                    end
                end
            end
        end    

        if ~exist('idx_rm','var')
            idx_rm = 0;
            NmrData.oplsda.outlier = idx_rm;
        end           
        
        % Initiating the GUI
        % Checking if the user create labels for each class    
        [NmrData.Classes.Labels.Classes,~]=sortrows(NmrData.Classes.Labels.Classes);
        % Run PCAplots GUI to present the results    
        if size(NmrData.Classes.Labels.UserData,2) == 3
            PCAplots('OPLSDA',NmrData.oplsda,ExportInf,NmrData.Classes.Labels.Classes); 
        elseif size(NmrData.Classes.Labels.UserData,2) > 3 
            PCAplots('OPLSDA',NmrData.oplsda,ExportInf,NmrData.Classes.Labels.Classes,NmrData.Classes.Labels.Original(:,4)); 
        end         
        guidata(hMainFigure,NmrData);
    end
    function doCalValOPLSDA(~,~)
        % Getting data from GNAT
        NmrData=guidata(hMainFigure);
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        pfgnmrdata=NmrData.pfgnmrdata;      

        % Checking the active area of the spectrum
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
             speclim(2)=(NmrData.sw+NmrData.sp);
        end
        
        % Clipping the matrix based on the active spectrum showed in GNAT
        for k=1:length(pfgnmrdata.Ppmscale)
           if (pfgnmrdata.Ppmscale(k)>speclim(1))
              begin=k-1;
              k1=begin;
              break;
           end
        end       
        for k=begin:length(pfgnmrdata.Ppmscale)
           if (pfgnmrdata.Ppmscale(k)>=speclim(2))
               endrange=k;
               break;
           end
        end
    
        % %Checking if Normalization was applied
        % if isfield(NmrData,'Normalised')
        %     pfgnmrdata.SPECTRA = NmrData.Normalised.matrix';
        %     % excluding regions
        %     if isfield(NmrData,'exclude')
        %         if get(hExcludeShow,'Value')
        %             for k=1:NmrData.ngrad
        %                 pfgnmrdata.SPECTRA(:,k)=...
        %                     pfgnmrdata.SPECTRA(:,k).*isnan(NmrData.exclude');
        %             end
        %         end
        %     end
        % end

        % Checking if samples was removed using the ClassGUI
        if isfield(NmrData,'Classes')  
            if isfield(NmrData.Classes,'Labels') 
                if isfield(NmrData.Classes.Labels,'UserData') 
                    if size(unique(NmrData.Classes.Labels.UserData(:,3)),1) == 2
                        idx_rm = find(strcmp(NmrData.Classes.Labels.Modified(:,3), 'no'));
                        NmrData.plsda.outlier = idx_rm;
                    end
                end
            end
        end

        if ~exist('idx_rm','var')
            idx_rm = 0;
            NmrData.pca.outlier = idx_rm;
        end

        % Making a new stucture
        pfgnmrdata.sp=pfgnmrdata.Ppmscale(k1);
        pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(k1);
        pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(k1:endrange);
        pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(k1:endrange,:);
        pfgnmrdata.np=length(pfgnmrdata.Ppmscale);
        input.thresflag=0; %#ok<STRNU> 
        matrix = pfgnmrdata.SPECTRA'; 
        set(hProcessOPLSDAButton,'Enable','on')

        % Check the distribution of Calibration and Validation
        Cal = round(str2double(get(hEditCalOPLSDA,'String')));        
        Val = 100 - Cal;
        set(hEditValOPLSDA,'String',num2str(Val));
 
        % Constructing vector array from classes table
        Classes = zeros(NmrData.arraydim,1);
        SequenceTable = get(hClassTable,'data');
        if isempty(SequenceTable)
            warndlg((sprintf('Before sppliting your dataset into Calibration and Validation, It is necessary first define one class to each sample')),'Warning');            
            return  
        else
            for n = 1:size(SequenceTable,1)            
                B = SequenceTable(n,2);
                E = SequenceTable(n,3); 
                samples = size(SequenceTable(n,2):1:SequenceTable(n,3),1);
                for i = B:E
                    Classes(B:E,1) = repmat(SequenceTable(n,1), samples, 1);
                end
            end    
        end        

        % Getting the method used to split data (See manual)
        switch get(hPanelOPLSDAPlots,'SelectedObject') 
            case hOPLSDAk %Kenston pick
                NmrData.oplsda.split='k';
            case hOPLSDAd %Duplex freq
                NmrData.oplsda.split='d';
            case hOPLSDAs %Segments
                NmrData.oplsda.split='s';        
        end

        % Cleaning Classes/samples that the user removed
        NmrData.plsda.Classes = Classes;
        if any(idx_rm)
            Classes(idx_rm,:) = [];
            Labels = NmrData.Classes.Labels.UserData;
            Labels(idx_rm,:) = [];
            matrix(idx_rm,:) = [];
        end

        % Checking if the binning limits was calculated
        hBinFigure = findobj('Type','figure','Tag','Bin');
        if ~isempty(hBinFigure)
            % [Classes,idx]=sortrows(Classes);
            BinPCA = guidata(hBinFigure);
            NmrData.oplsda.BinPCA=BinPCA;
            % The user oppened the gui but did not press "Apply Bin"
            if ~isfield(NmrData.oplsda.BinPCA,'normalized_buckets')
                NmrData.oplsda = rmfield(NmrData.oplsda, 'BinPCA');
                % matrix=matrix(idx,:);                
            else
                NmrData.oplsda.BinPCA.normalized_buckets=NmrData.oplsda.BinPCA.normalized_buckets(idx,:);
                if any(idx_rm)
                    NmrData.oplsda.BinPCA.normalized_buckets(idx_rm,:) = [];
                end                 
            end 
        elseif isfield(NmrData.oplsda,'BinPCA')
            NmrData.oplsda = rmfield(NmrData.oplsda, 'BinPCA');
            % [Classes,idx]=sortrows(Classes);
            % matrix=matrix(idx,:);   
        else
            % [Classes,idx]=sortrows(Classes);
            % matrix=matrix(idx,:);
        end        
        NmrData.oplsda.Classes = Classes;

        % Verify if each sample has its own class
        if nnz(~Classes) > 0
            warndlg((sprintf('It is necessary at least one class to each sample to continue \n Check Labels GUI for more information')),'Warning');            
            return  
        elseif isfield(NmrData.oplsda,'BinPCA')
                       
            if isfield(NmrData,'Normalised')
                [objetos,xcal,xval,ycal,yval]=caltestda_pls(NmrData.Normalised.matrix,Classes,Cal,NmrData.oplsda.split,[],[]);            

                xcal=NmrData.Normalised.matrix(objetos.treinamento,:);
                xval=NmrData.Normalised.matrix(objetos.teste,:);
            else
                [objetos,xcal,xval,ycal,yval]=caltestda_pls(NmrData.oplsda.BinPCA.normalized_buckets,Classes,Cal,NmrData.oplsda.split,[],[]);    
                
                xcal=NmrData.oplsda.BinPCA.normalized_buckets(objetos.treinamento,:);
                xval=NmrData.oplsda.BinPCA.normalized_buckets(objetos.teste,:);
            end

            ycal=NmrData.oplsda.Classes(objetos.treinamento,:);
            yval=NmrData.oplsda.Classes(objetos.teste,:); 
        else           
            if isfield(NmrData,'Normalised')
                [objetos,xcal,xval,ycal,yval]=caltestda_pls(NmrData.Normalised.matrix,Classes,Cal,NmrData.oplsda.split,[],[]);

                xcal=NmrData.Normalised.matrix(objetos.treinamento,:);
                xval=NmrData.Normalised.matrix(objetos.teste,:);
            else
                [objetos,xcal,xval,ycal,yval]=caltestda_pls(matrix,Classes,Cal,NmrData.oplsda.split,[],[]);

                xcal=matrix(objetos.treinamento,:);
                xval=matrix(objetos.teste,:);
            end
    
            ycal=NmrData.oplsda.Classes(objetos.treinamento,:);
            yval=NmrData.oplsda.Classes(objetos.teste,:); 

        end

        if ~isempty(objetos)
            uiwait(msgbox('The Cal/Val calculation was carried out successfully','Cal/Val spliting','help','modal'));
        end
        
        % Constructing the dummy matrix:
        %   y1[1        y2[1 0 0
        %      1           1 0 0
        %      2           0 1 0
        %      2           0 1 0
        %      3           0 0 1
        %      3]          0 0 1]
        ycalM = vet_matrix(ycal,unique(Classes));
        yvalM = vet_matrix(yval,unique(Classes));        

        % Creating Tab for visualize cal/val split
        hTabTableCalValOPLSDA.Parent = hTabGroupOPLSDA;

        % Saving 'split' for OPLS1-DA and OPLS2-DA (See manual)
        NmrData.oplsda.objetos = objetos;
        NmrData.oplsda.xcal = xcal;
        NmrData.oplsda.xval = xval;
        NmrData.oplsda.ycalV = ycal; % Classes saved in vector format
        NmrData.oplsda.yvalV = yval;          
        NmrData.oplsda.ycalM = ycalM; % Classes saved in matrix format
        NmrData.oplsda.yvalM = yvalM;       
        NmrData.oplsda.LV = 5; % ----- Change for the user input later ------
        NmrData.oplsda.ppmscale = pfgnmrdata.Ppmscale;
        
        % Table Cal/Val separation
        Cal = string(Classes); Val = string(Classes);
        Cal(NmrData.oplsda.objetos.treinamento) = '.'; Cal(NmrData.oplsda.objetos.teste) = 'X';  
        Val(NmrData.oplsda.objetos.treinamento) = 'X'; Val(NmrData.oplsda.objetos.teste) = '.'; 
        
        Samples = "Sample_" + string(1:size(Classes', 2));
        
        TableData(:,1)=cellstr(Samples');
        TableData(:,2)=cellstr(Cal);
        TableData(:,3)=cellstr(Val);
        
        set(hTableCalValOPLSDA,'Data',TableData);
        NmrData.oplsda.TableContent = get(hTableCalValOPLSDA,'data');

%       Try to implement some colos in the Calibration/Test table in the
%       future
%         colors = ['#FF0000';'#00FF00'];
%         colergen = @(cor,text) ['<html><table border=0 width=20 bgcolor=',cor,'><TR><TD>',text,'</TD></TR> </table><html>'];        
%         for n = 1:2
%             ChemoData.objetos.treinamento
%             ChemoData.objetos.teste
%             if isempty(aa)
%                 continue
%             elseif ~isempty(aa)
%                 for m = 1:num_aa                  
%                     k = aa(m) ;
%                     S{k,1} = colergen(colors(n,1:end),num2str(C(k,1)));                              
%                 end                
%             end
%         end    
                
        guidata(hMainFigure,NmrData);
    end
%----STOCSY----------------------
    function doSTOCSY(~,~)
        % Getting data from GNAT
        NmrData=guidata(hMainFigure);  

        % Checking the active area of the spectrum
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
             speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
             speclim(2)=(NmrData.sw+NmrData.sp);
        end

        input.thresflag=0;
        NmrData.pfgnmrdata=PreparePfgnmrdata();
        pfgnmrdata=NmrData.pfgnmrdata; 
        for k=1:length(pfgnmrdata.Ppmscale)
             if (pfgnmrdata.Ppmscale(k)>speclim(1))
                begin=k-1;
                k1=begin;
                break;
             end
        end
        
        for k=begin:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>=speclim(2))
                endrange=k;
                break;
            end
        end

        % Making a new stucture
%         pfgnmrdata.sp=pfgnmrdata.Ppmscale(k1);
%         pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(k1);
%         pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(k1:endrange);
%         pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(k1:endrange,:);
%         pfgnmrdata.np=length(pfgnmrdata.Ppmscale);
%         matrix = pfgnmrdata.SPECTRA'; 

        % Making a new structure
        matrix = real(NmrData.SPECTRA(k1:endrange,:))'; 
        pfgnmrdata.Ppmscale=NmrData.Specscale(k1:endrange);

        NmrData.stocsy.pthr=str2double(get(hEditThresSTOCSY,'String'));  % Get confidence value
        NmrData.stocsy.ppmscale=pfgnmrdata.Ppmscale;                     % Get the ppmscale              
        NmrData.stocsy.raw_matrix = matrix;                              % Get the raw matrix         

        % Getting the method used to split data
        switch get(hPanelSTOCSYopts,'SelectedObject') 
            case hSTOCSYp % Kenston pick
                NmrData.stocsy.CCmetric='pearson';
            case hSTOCSYs % Duplex freq
                NmrData.stocsy.CCmetric='spearman';      
        end          

        % Checking if a sample was removed from the analysis
        matrix=reshape(matrix,[],NmrData.ngrad,NmrData.narray2);
        % Prune gradient levels for if opted
        if get(hNgradUse,'Value')
            %check the validity of the prune array
            if length(NmrData.prune)>=length(NmrData.Gzlvl)
                errstring=...
                    {'Too many gradient levels in prune',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.prune <1
                errstring=...
                    {'Prune numbers cannot be zero or negative',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.prune>NmrData.ngrad
                errstring=...
                    {'Prune numbers cannot exceed number of gradient levels',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif length(unique(NmrData.prune))~=length(NmrData.prune)
                errstring=...
                    {'Duplicates in prune vector',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            else
                %do the pruning
                matrix(:,NmrData.prune,:)=[];
            end
        end
        
        % Prune array 2 levels if opted
        if get(hArray2Use,'Value')
            %check the validity of the prune array
            if length(NmrData.pruneArray2)>=NmrData.narray2
                errstring=...
                    {'Too many array levels in prune',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.pruneArray2 <1
                errstring=...
                    {'Prune numbers cannot be zero or negative',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif length(unique(NmrData.pruneArray2))~=length(NmrData.pruneArray2)
                errstring=...
                    {'Duplicates in prune vector',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            else
                %do the pruning
                matrix(:,:,NmrData.pruneArray2)=[];
            end
        end

        % Reshaping to be a 2D matrix again
        matrix = reshape(matrix,[],size(matrix,1));
%         matrix = matrix(:,:,1);
%         matrix = reshape(matrix,[],size(matrix,1));
%         matrix = matrix';

        % Checking if the binning limits was calculated
        hBinFigure = findobj('Type','figure','Tag','Bin');
        if ~isempty(hBinFigure)
            BinPCA = guidata(hBinFigure);
            NmrData.stocsy.BinPCA=BinPCA;
            if isempty(BinPCA.non_normalized_buckets)
                NmrData.stocsy = rmfield(NmrData.stocsy, 'BinPCA');
            end 
        elseif isfield(NmrData.stocsy,'BinPCA')
            NmrData.stocsy = rmfield(NmrData.stocsy, 'BinPCA');
        end
        
        % Checking if one signal was selected for 1D STOCSY calculation
        if get(hMeasureCheck,'Value') && ~isempty(NmrData.reference) && isempty(hBinFigure)
            peakPPM=(NmrData.reference-min(pfgnmrdata.Ppmscale))/(pfgnmrdata.Ppmscale(end)-pfgnmrdata.Ppmscale(1));
            peakID=round(peakPPM*size(pfgnmrdata.Ppmscale,2));
        elseif ~isempty(hBinFigure) && get(hMeasureCheck,'Value') && ~isempty(NmrData.reference)      
            peakID=find(NmrData.stocsy.BinPCA.intervals(:,1)<NmrData.reference & NmrData.stocsy.BinPCA.intervals(:,2)>NmrData.reference);
        else
            warndlg('You should define the ppm to be analysed in the panel Set region','Warning'); 
            return
        end

        if isfield(NmrData.stocsy,'BinPCA')
            matrix=NmrData.stocsy.BinPCA.normalized_buckets;
            twoD = 1;
            CCXY=STOCSY(matrix,NmrData.stocsy.BinPCA.intervals(:,1),peakID,NmrData.stocsy.pthr,NmrData.stocsy.CCmetric,NmrData.reference,twoD);
        else
            twoD = 1;
            CCXY=STOCSY(matrix,NmrData.stocsy.Ppmscale,peakID,NmrData.stocsy.pthr,NmrData.stocsy.CCmetric,NmrData.reference,twoD);
%             CCXY=STOCSY(matrix(3:6,:),NmrData.stocsy.Ppmscale,peakID,NmrData.stocsy.pthr,NmrData.stocsy.CCmetric,NmrData.reference,twoD);
        end       
        guidata(hMainFigure,NmrData);
    end

%% ---------Multiway Tab Callbacks
%----PARAFAC-------
    function doPARAFAC(~,~)
        NmrData=guidata(hMainFigure);
        if NmrData.narray3==1 && NmrData.ngrad2==NmrData.ngrad %3D
            NmrData.pfgnmrdata=PreparePfgnmr3Ddata();
            set(hGroupMode4,'SelectedObject',hRadioConst4none)
            Options=[1e-7 1 1 0 0 0];
            
            if get(hAutoPlotUse,'Value')
                figure
            else
                Options=[1e-7 1 0 0 0 0];
            end
            
            const=[0 0 0];
            OldLoad=[];
            FixMode=[];
            Weights=[] ;
            NmrData.ncomp=str2double(get(hEditNcompPARAFAC,'String'));
            guidata(hMainFigure,NmrData);
            pfgnmrdata=NmrData.pfgnmrdata;
            
            % Set spectral limits
            speclim=xlim(hAxes);
            if speclim(1)<NmrData.sp
                speclim(1)=NmrData.sp;
            end
            if speclim(2)>(NmrData.sw+NmrData.sp)
                speclim(2)=(NmrData.sw+NmrData.sp);
            end
            Specrange=speclim;
            if length(Specrange)~=2
                error('PARAFAC: Specrange should have excatly 2 elements')
            end
            if Specrange(1)<pfgnmrdata.sp
                guidata(hMainFigure,NmrData); WriteLogDispInfo('PARAFAC: Specrange(1) is too low. The minumum will be used')
                Specrange(1)=pfgnmrdata.sp;
            end
            if Specrange(2)>(pfgnmrdata.wp+pfgnmrdata.sp)
                guidata(hMainFigure,NmrData); WriteLogDispInfo('PARAFAC: Specrange(2) is too high. The maximum will be used')
                Specrange(2)=pfgnmrdata.wp+pfgnmrdata.sp;
            end
            for k=1:length(pfgnmrdata.Ppmscale)
                if (pfgnmrdata.Ppmscale(k)>Specrange(1))
                    begin=k-1;
                    break;
                end
            end
            for k=begin:length(pfgnmrdata.Ppmscale)
                if (pfgnmrdata.Ppmscale(k)>=Specrange(2))
                    endrange=k;
                    break;
                end
            end
            
            % Set initialisation
            switch get(hGroupInit,'SelectedObject')
                case hRadioInit1
                    Options(2)=0;
                case hRadioInit2
                    Options(2)=1;
                case hRadioInit3
                    Options(2)=2;
                case hRadioInit4
                    Options(2)=10;
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Unknown constraint in mode 1 - defaulting to no constraint')
            end
            
            % Set constraints
            switch get(hGroupMode1,'SelectedObject')
                case hRadioConst1none
                    const(1)=0;
                case hRadioConst1ortho
                    const(1)=1;
                case hRadioConst1nneg
                    const(1)=2;
                case hRadioConst1unimod
                    const(1)=3;
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Unknown constraint in mode 1 - defaulting to no constraint')
            end
            switch get(hGroupMode2,'SelectedObject')
                
                case hRadioConst2none
                    const(2)=0;
                    
                case hRadioConst2ortho
                    const(2)=1;
                    
                case hRadioConst2nneg
                    const(2)=2;
                    
                case hRadioConst2unimod
                    const(2)=3;
                    
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Unknown constraint in mode 2 - defaulting to no constraint')
            end
            switch get(hGroupMode3,'SelectedObject')
                
                case hRadioConst3none
                    const(3)=0;
                    
                case hRadioConst3ortho
                    const(3)=1;
                    
                case hRadioConst3nneg
                    const(3)=2;
                    
                case hRadioConst3unimod
                    const(3)=3;
                    
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown constraint in mode 3 - defaulting to no constraint')
            end
            
            % Make a new stucture
            pfgnmrdata.sp=pfgnmrdata.Ppmscale(begin);
            pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(begin);
            pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(begin:endrange);
            pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(begin:endrange,:,:);
            pfgnmrdata.np=length(pfgnmrdata.Ppmscale) ;
            
            tmp=permute(pfgnmrdata.SPECTRA,[1 2 3]);
            
           % tmp=pfgnmrdata.SPECTRA;
            Options(1)=1e-12;
            %Options(6)=1e5;
            % size(tmp)
            [NmrData.parafacFac]= parafac(tmp,NmrData.ncomp,Options,const,OldLoad,FixMode,Weights);
           % [Factors]= parafac(tmp,NmrData.ncomp);
           % figure()
           %  plotfac(Factors);
            
            % Make separate plots
            if get(hResidualPlotUse,'Value')
                parafacresidual_gdp(NmrData.parafacFac,tmp,NmrData.ncomp,pfgnmrdata.Ppmscale)
            end
            if get(hSepPlotUse,'Value')
                
                % Mode 1 - All components together
                pMainFigure = figure(...
                    'Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 1 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode1=NmrData.parafacFac{1};
                h=plot(pfgnmrdata.Ppmscale,mode1);
                set(gca,'xdir','reverse');
                axis('tight');
                set(h,'LineWidth',1);
                set(gca,'LineWidth',1);
                ylim([(min(min(mode1))-0.1*max(max(mode1))) max(max(mode1))*1.1]);
                title({'','Spectrum mode',''},'FontSize',12, 'FontWeight','bold');
                xlabel('Chemical shift / ppm','FontSize',10, 'FontWeight','bold');
                ylabel('Intensity','FontSize',10, 'FontWeight','bold');
                
                
                % Mode 1 - All components separate
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 1 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                ax=zeros(1,NmrData.ncomp);
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(pfgnmrdata.Ppmscale,mode1(:,k));
                    set(gca,'xdir','reverse');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold');
                    if k==1
                        title({'','Spectrum mode',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Chemical shift / ppm','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
                
                
                % Mode2 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 2 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode2=NmrData.parafacFac{2};
                h=plot(mode2, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode2))-0.1*max(max(mode2))) max(max(mode2))*1.1])
                title({'','Mode 2',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                % Mode 2 - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 2 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode2(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 2',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                
                linkaxes(ax,'x');
                
                
                % Mode 3 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 3 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode3=NmrData.parafacFac{3};
                h=plot(mode3, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode3))-0.1*max(max(mode3))) max(max(mode3))*1.1])
                title({'','Mode 3',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                
                % Mode3  - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 3 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode3(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 3',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
            end
            NmrData.tmp=tmp;
            NmrData.tmpPpmscale=pfgnmrdata.Ppmscale;
            guidata(hMainFigure,NmrData);
        elseif NmrData.narray3>1 && NmrData.ngrad2~=NmrData.ngrad %4D data
            NmrData.pfgnmrdata=PreparePfgnmr4Ddata();
            
            Options=[1e-7 1 1 0 0 0];
            
            if get(hAutoPlotUse,'Value')
                figure
            else
                Options=[1e-7 1 0 0 0 0];
            end
            
            const=[0 0 0 0];
            OldLoad=[];
            FixMode=[];
            Weights=[] ;
            NmrData.ncomp=str2double(get(hEditNcompPARAFAC,'String'));
            guidata(hMainFigure,NmrData);
            pfgnmrdata=NmrData.pfgnmrdata;
            
            % Set spectral limits
            speclim=xlim(hAxes);
            if speclim(1)<NmrData.sp
                speclim(1)=NmrData.sp;
            end
            if speclim(2)>(NmrData.sw+NmrData.sp)
                speclim(2)=(NmrData.sw+NmrData.sp);
            end
            Specrange=speclim;
            if length(Specrange)~=2
                error('PARAFAC: Specrange should have excatly 2 elements')
            end
            if Specrange(1)<pfgnmrdata.sp
                guidata(hMainFigure,NmrData); WriteLogDispInfo('PARAFAC: Specrange(1) is too low. The minumum will be used')
                Specrange(1)=pfgnmrdata.sp;
            end
            if Specrange(2)>(pfgnmrdata.wp+pfgnmrdata.sp)
                guidata(hMainFigure,NmrData); WriteLogDispInfo('PARAFAC: Specrange(2) is too high. The maximum will be used')
                Specrange(2)=pfgnmrdata.wp+pfgnmrdata.sp;
            end
            for k=1:length(pfgnmrdata.Ppmscale)
                if (pfgnmrdata.Ppmscale(k)>Specrange(1))
                    begin=k-1;
                    break;
                end
            end
            for k=begin:length(pfgnmrdata.Ppmscale)
                if (pfgnmrdata.Ppmscale(k)>=Specrange(2))
                    endrange=k;
                    break;
                end
            end
            
            % Set initialisation
            switch get(hGroupInit,'SelectedObject')
                case hRadioInit1
                    Options(2)=0;
                case hRadioInit2
                    Options(2)=1;
                case hRadioInit3
                    Options(2)=2;
                case hRadioInit4
                    Options(2)=10;
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Unknown constraint in mode 1 - defaulting to no constraint')
            end
            
            % Set constraints
            switch get(hGroupMode1,'SelectedObject')
                case hRadioConst1none
                    const(1)=0;
                case hRadioConst1ortho
                    const(1)=1;
                case hRadioConst1nneg
                    const(1)=2;
                case hRadioConst1unimod
                    const(1)=3;
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Unknown constraint in mode 1 - defaulting to no constraint')
            end
            switch get(hGroupMode2,'SelectedObject')
                
                case hRadioConst2none
                    const(2)=0;
                    
                case hRadioConst2ortho
                    const(2)=1;
                    
                case hRadioConst2nneg
                    const(2)=2;
                    
                case hRadioConst2unimod
                    const(2)=3;
                    
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Unknown constraint in mode 2 - defaulting to no constraint')
            end
            switch get(hGroupMode3,'SelectedObject')
                
                case hRadioConst3none
                    const(3)=0;
                    
                case hRadioConst3ortho
                    const(3)=1;
                    
                case hRadioConst3nneg
                    const(3)=2;
                    
                case hRadioConst3unimod
                    const(3)=3;
                    
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown constraint in mode 3 - defaulting to no constraint')
            end
            switch get(hGroupMode4,'SelectedObject')
                
                case hRadioConst4none
                    const(4)=0;
                    
                case hRadioConst4ortho
                    const(4)=1;
                    
                case hRadioConst4nneg
                    const(4)=2;
                    
                case hRadioConst4unimod
                    const(4)=3;
                    
                otherwise
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown constraint in mode 4 - defaulting to no constraint')
            end
            
            % Make a new stucture
            pfgnmrdata.sp=pfgnmrdata.Ppmscale(begin);
            pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(begin);
            pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(begin:endrange);
            pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(begin:endrange,:,:,:);
            pfgnmrdata.np=length(pfgnmrdata.Ppmscale) ;
            
            %tmp=permute(pfgnmrdata.SPECTRA,[4 1 2 3]);
            tmp=pfgnmrdata.SPECTRA;
            %size(tmp)
            [NmrData.parafacFac]= parafac(tmp,NmrData.ncomp,Options,const,OldLoad,FixMode,Weights);
           
            % Make separate plots
            if get(hResidualPlotUse,'Value')
                %parafac4dresidual_gdp(NmrData.parafacFac,tmp,NmrData.ncomp,pfgnmrdata.Ppmscale)
                disp('4D residuals are not available')
            end
            if get(hSepPlotUse,'Value')
                
                % Mode 1 - All components together
                pMainFigure = figure(...
                    'Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 1 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode1=NmrData.parafacFac{1};
                h=plot(pfgnmrdata.Ppmscale,mode1);
                set(gca,'xdir','reverse');
                axis('tight');
                set(h,'LineWidth',1);
                set(gca,'LineWidth',1);
                ylim([(min(min(mode1))-0.1*max(max(mode1))) max(max(mode1))*1.1]);
                title({'','Spectrum mode',''},'FontSize',12, 'FontWeight','bold');
                xlabel('Chemical shift / ppm','FontSize',10, 'FontWeight','bold');
                ylabel('Intensity','FontSize',10, 'FontWeight','bold');
                
                
                % Mode 1 - All components separate
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 1 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                ax=zeros(1,NmrData.ncomp);
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(pfgnmrdata.Ppmscale,mode1(:,k));
                    set(gca,'xdir','reverse');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold');
                    if k==1
                        title({'','Spectrum mode',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Chemical shift / ppm','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
                
                
                % Mode2 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 2 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode2=NmrData.parafacFac{2};
                h=plot(mode2, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode2))-0.1*max(max(mode2))) max(max(mode2))*1.1])
                title({'','Mode 2',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                % Mode 2 - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 2 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode2(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 2',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                
                linkaxes(ax,'x');
                
                
                % Mode 3 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 3 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode3=NmrData.parafacFac{3};
                h=plot(mode3, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode3))-0.1*max(max(mode3))) max(max(mode3))*1.1])
                title({'','Mode 3',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                
                % Mode3  - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 3 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode3(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 3',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
                
                % Mode 4 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 4 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode4=NmrData.parafacFac{4};
                h=plot(mode4, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode3))-0.1*max(max(mode4))) max(max(mode4))*1.1])
                title({'','Mode 4',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                
                % Mode4  - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 4 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode4(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 4',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
            end
            NmrData.tmp=tmp;
            NmrData.tmpPpmscale=pfgnmrdata.Ppmscale;
            guidata(hMainFigure,NmrData);
        else %Not PARAFAC data
        end
    end
    function residualsPARAFAC(~,~)
            NmrData=guidata(hMainFigure);
            if isempty(NmrData.parafacFac)
                msgbox('No fitted data available');
            else
                if NmrData.narray3==1 && NmrData.ngrad2==NmrData.ngrad %3D
                    NmrData.ncomp=size((NmrData.parafacFac{1}),2);
                    parafacresidual_gdp(NmrData.parafacFac,NmrData.tmp,NmrData.ncomp,NmrData.tmpPpmscale)
                    guidata(hMainFigure,NmrData);
                elseif NmrData.narray3>1 && NmrData.ngrad2~=NmrData.ngrad %4D data
                    %NmrData.ncomp=size((NmrData.parafacFac{1}),2);
                    %parafac4dresidual_gdp(NmrData.parafacFac,NmrData.tmp,NmrData.ncomp,NmrData.tmpPpmscale)
                    %guidata(hMainFigure,NmrData);
                    disp('4D residuals are not available')
                else
                end
            end
        end
    function replotPARAFAC(~,~)
            NmrData=guidata(hMainFigure);
            if isempty(NmrData.parafacFac)
                msgbox('No fitted data available');
            else
                NmrData.ncomp=size((NmrData.parafacFac{1}),2);
                
                % Mode 1 - All components together
                pMainFigure = figure(...
                    'Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 1 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                
                mode1=NmrData.parafacFac{1};
                h=plot(NmrData.tmpPpmscale,mode1);
                set(gca,'xdir','reverse');
                axis('tight');
                set(h,'LineWidth',1);
                set(gca,'LineWidth',1);
                ylim([(min(min(mode1))-0.1*max(max(mode1))) max(max(mode1))*1.1]);
                title({'','Spectrum mode',''},'FontSize',12, 'FontWeight','bold');
                xlabel('Chemical shift / ppm','FontSize',10, 'FontWeight','bold');
                ylabel('Intensity','FontSize',10, 'FontWeight','bold');
                
                
                % Mode 1 - All components separate
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 1 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                ax=zeros(1,NmrData.ncomp);
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(NmrData.tmpPpmscale,mode1(:,k));
                    set(gca,'xdir','reverse');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold');
                    if k==1
                        title({'','Spectrum mode',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Chemical shift / ppm','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
                
                
                % Mode2 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 2 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode2=NmrData.parafacFac{2};
                h=plot(mode2, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode2))-0.1*max(max(mode2))) max(max(mode2))*1.1])
                title({'','Mode 2',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                % Mode 2 - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 2 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode2(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 2',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                
                linkaxes(ax,'x');
                
                
                % Mode 3 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 3 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode3=NmrData.parafacFac{3};
                h=plot(mode3, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode3))-0.1*max(max(mode3))) max(max(mode3))*1.1])
                title({'','Mode 3',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                
                % Mode3  - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 3 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode3(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 3',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
                
                if size(NmrData.parafacFac,2)==4
                     % Mode 4 - All components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 4 - All components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                mode4=NmrData.parafacFac{4};
                h=plot(mode4, '-*');
                axis('tight')
                set(h,'LineWidth',1)
                set(gca,'LineWidth',1)
                ylim([(min(min(mode4))-0.1*max(max(mode4))) max(max(mode4))*1.1])
                title({'','Mode 4',''},'FontSize',12, 'FontWeight','bold')
                xlabel('Experiment','FontSize',10, 'FontWeight','bold')
                ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                
                
                % Mode4  - Separate components
                pMainFigure=figure('Color',[0.9 0.9 0.9],...
                    'MenuBar','none',...
                    'Toolbar','Figure',...
                    'NumberTitle','Off',...
                    'Name','Mode 4 - Separate components');
                
                %Clean up the Toolbar, removing things we don't need
                rmv = findall(pMainFigure,'ToolTipString','New Figure');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Open File');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Link Plot');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
                set(rmv,'Visible','Off')
%                 rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%                 set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
                set(rmv,'Visible','Off')
                rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
                set(rmv,'Visible','Off')
                
                for k=1:NmrData.ncomp
                    ax(k)=subplot(NmrData.ncomp,1,k);
                    %h=
                    plot(mode4(:,k), '-*');
                    ylabel('Intensity','FontSize',10, 'FontWeight','bold')
                    if k==1
                        title({'','Mode 4',''},'FontSize',12, 'FontWeight','bold')
                    end
                    if k==NmrData.ncomp
                        xlabel('Experiment','FontSize',10, 'FontWeight','bold');
                    end
                end
                linkaxes(ax,'x');
                end
                guidata(hMainFigure,NmrData);
            end
    end
%----SLICING-------
    function doSLICING(~,~)
        NmrData=guidata(hMainFigure);

        NmrData.pfgnmrdata=PreparePfgnmrdata();
        
        %Options=[1e-6 1 1 0 0 0];
        
        if get(hAutoPlotUseSLICING,'Value')
            Options=[1e-6 1 1 0 0 0];
        else
            Options=[1e-6 1 0 0 0 0];
        end
        
        const=[0 0 0];
        OldLoad=[];
        FixMode=[];
        Weights=[] ;
        NmrData.ncomp=str2double(get(hEditNcompSLICING,'String'));
        guidata(hMainFigure,NmrData);
        pfgnmrdata=NmrData.pfgnmrdata;
                
        %set spectral limits
        speclim=xlim(hAxes);
        if speclim(1)<NmrData.sp
            speclim(1)=NmrData.sp;
        end
        if speclim(2)>(NmrData.sw+NmrData.sp)
            speclim(2)=(NmrData.sw+NmrData.sp);
        end
        Specrange=speclim;
        if length(Specrange)~=2
            error('SLICING: Specrange should have excatly 2 elements')
        end
        if Specrange(1)<pfgnmrdata.sp
            guidata(hMainFigure,NmrData); WriteLogDispInfo('SLICING: Specrange(1) is too low. The minumum will be used')
            Specrange(1)=pfgnmrdata.sp;
        end
        if Specrange(2)>(pfgnmrdata.wp+pfgnmrdata.sp)
            guidata(hMainFigure,NmrData); WriteLogDispInfo('SLICING: Specrange(2) is too high. The maximum will be used')
            Specrange(2)=pfgnmrdata.wp+pfgnmrdata.sp;
        end
        for k=1:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>Specrange(1))
                begin=k-1;
                break;
            end
        end
        for k=begin:length(pfgnmrdata.Ppmscale)
            if (pfgnmrdata.Ppmscale(k)>=Specrange(2))
                endrange=k;
                break;
            end
        end
        
        % Set initialisation
        switch get(hGroupInitSLICING,'SelectedObject')
            case hRadioInit1SLICING
                Options(2)=0;
            case hRadioInit2SLICING
                Options(2)=1;
            case hRadioInit3SLICING
                Options(2)=2;
            case hRadioInit4SLICING
                Options(2)=10;
            otherwise
                guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown constraint in mode 1 - defaulting to no constraint')
        end
        
        % Set constraints
        switch get(hGroupMode1SLICING,'SelectedObject')
            case hRadioConst1noneSLICING
                const(1)=0;
            case hRadioConst1orthoSLICING
                const(1)=1;
            case hRadioConst1nnegSLICING
                const(1)=2;
            case hRadioConst1unimodSLICING
                const(1)=3;
            otherwise
                guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown constraint in mode 1 - defaulting to no constraint')
        end
        switch get(hGroupMode2SLICING,'SelectedObject')
            case hRadioConst2noneSLICING
                const(2)=0;
            case hRadioConst2orthoSLICING
                const(2)=1;
            case hRadioConst2nnegSLICING
                const(2)=2;
            case hRadioConst2unimodSLICING
                const(2)=3;
            otherwise
                guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown constraint in mode 2 - defaulting to no constraint')
        end
        switch get(hGroupMode3SLICING,'SelectedObject')
            case hRadioConst3noneSLICING
                const(3)=0;
            case hRadioConst3orthoSLICING
                const(3)=1;
            case hRadioConst3nnegSLICING
                const(3)=2;
            case hRadioConst3unimodSLICING
                const(3)=3;
            otherwise
                guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown constraint in mode 3 - defaulting to no constraint')
        end
        
        %make a new stucture
        pfgnmrdata.sp=pfgnmrdata.Ppmscale(begin);
        pfgnmrdata.wp=pfgnmrdata.Ppmscale(endrange)-pfgnmrdata.Ppmscale(begin);
        pfgnmrdata.Ppmscale=pfgnmrdata.Ppmscale(begin:endrange);
        pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA(begin:endrange,:,:);
        pfgnmrdata.np=length(pfgnmrdata.Ppmscale) ;
        
        %do the slicing
        [np , ~]=size(pfgnmrdata.SPECTRA);
        nslice=nextpow2(NmrData.pfgnmrdata.ngrad) - 1;
        
        
        slicedata=zeros(np,2^nslice,nslice);
        
        for k=1:nslice
            slicedata(:,:,k)=pfgnmrdata.SPECTRA(:,2^(k-1):(2^nslice + 2^(k-1)-1));
            
        end
        size(slicedata)
        
        
        figure;
        
        [NmrData.parafacFac]= parafac(slicedata,NmrData.ncomp,Options,const,OldLoad,FixMode,Weights);
        
        
        %Make separate plots
        if get(hSepPlotUse,'Value')
            %Mode 1
            pMainFigure=figure('Color',[0.9 0.9 0.9],...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Toolbar','Figure',...
                'Name','Mode 1');
            
            %Clean up the Toolbar, removing things we don't need
            rmv = findall(pMainFigure,'ToolTipString','New Figure');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Open File');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Link Plot');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
            set(rmv,'Visible','Off')
%             rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%             set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
            set(rmv,'Visible','Off')
            mode1=NmrData.parafacFac{1};
            
            size(pfgnmrdata.Ppmscale)
            size(mode1)
            
            h=plot(pfgnmrdata.Ppmscale,mode1);
            set(gca,'xdir','reverse');
            axis('tight')
            set(h,'LineWidth',1)
            set(gca,'LineWidth',1)
            ylim([(min(min(mode1))-0.1*max(max(mode1))) max(max(mode1))*1.1])
            title('Spectrum mode','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            xlabel('Chemical shift (ppm)','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            ylabel('Intensity','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            
            
            pMainFigure=figure('Color',[0.9 0.9 0.9],...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Toolbar','Figure',...
                'Name','Mode 1 - separate');
            %Clean up the Toolbar, removing things we don't need
            rmv = findall(pMainFigure,'ToolTipString','New Figure');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Open File');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Link Plot');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
            set(rmv,'Visible','Off')
%             rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%             set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
            set(rmv,'Visible','Off')
            
            ax=zeros(1,NmrData.ncomp);
            for k=1:NmrData.ncomp
                ax(k)=subplot(NmrData.ncomp,1,k);
                %h=
                plot(pfgnmrdata.Ppmscale,mode1(:,k));
                set(gca,'xdir','reverse'); %TMB 10-03-16
                title('Spectrum mode','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
                xlabel('Chemical shift (ppm)','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
                ylabel('Intensity','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            end
            linkaxes(ax,'x');
            
            %Mode2
            %pMainFigure=
            figure('Color',[0.9 0.9 0.9],...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Toolbar','Figure',...
                'Name','Mode 1');
            mode2=NmrData.parafacFac{2};
            h=plot(mode2, '-*');
            axis('tight')
            set(h,'LineWidth',1)
            set(gca,'LineWidth',1)
            ylim([(min(min(mode2))-0.1*max(max(mode2))) max(max(mode2))*1.1])
            title('Diffussion mode','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            xlabel('Gradient amplitude squared','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            ylabel('Intensity','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            
            
            pMainFigure=figure('Color',[0.9 0.9 0.9],...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Toolbar','Figure',...
                'Name','Mode 2 - separate');
            %Clean up the Toolbar, removing things we don't need
            rmv = findall(pMainFigure,'ToolTipString','New Figure');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Open File');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Link Plot');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
            set(rmv,'Visible','Off')
%             rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%             set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
            set(rmv,'Visible','Off')
            
            for k=1:NmrData.ncomp
                ax(k)=subplot(NmrData.ncomp,1,k);
                %h=
                plot(mode2(:,k), '-*'); %TMB 10-03-16
                title('Diffussion mode','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
                xlabel('Gradient amplitude squared','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
                ylabel('Intensity','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            end
            linkaxes(ax,'x');
            
            %Mode 3
            
            pMainFigure=figure('Color',[0.9 0.9 0.9],...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Toolbar','Figure',...
                'Name','Mode 3');
            mode3=NmrData.parafacFac{3};
            h=plot(mode3, '-*'); %TMB 10-03-16
            %set(gca,'xdir','reverse'); %TMB 10-03-16
            axis('tight')
            set(h,'LineWidth',1)
            set(gca,'LineWidth',1)
            ylim([(min(min(mode3))-0.1*max(max(mode3))) max(max(mode3))*1.1])
            title('Time mode','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            xlabel('Time','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            ylabel('Concentration','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            %Clean up the Toolbar, removing things we don't need
            rmv = findall(pMainFigure,'ToolTipString','New Figure');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Open File');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Link Plot');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
            set(rmv,'Visible','Off')
%             rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%             set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
            set(rmv,'Visible','Off')
            
            pMainFigure=figure('Color',[0.9 0.9 0.9],...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Toolbar','Figure',...
                'Name','Mode 3 - separate');
            %Clean up the Toolbar, removing things we don't need
            rmv = findall(pMainFigure,'ToolTipString','New Figure');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Open File');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Link Plot');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Legend');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Rotate 3D');
            set(rmv,'Visible','Off')
%             rmv = findall(pMainFigure,'ToolTipString','Edit Plot');
%             set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Data Cursor');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Insert Colorbar');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Brush/Select Data');
            set(rmv,'Visible','Off')
            rmv = findall(pMainFigure,'ToolTipString','Hide Plot Tools');
            set(rmv,'Visible','Off')
            
            for k=1:NmrData.ncomp
                ax(k)=subplot(NmrData.ncomp,1,k);
                %h=
                plot(mode3(:,k), '-*'); %TMB 10-03-16
                title('Time mode','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
                xlabel('Time','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
                ylabel('Concentration','FontSize',12, 'FontWeight','bold') %TMB 10-03-16
            end
            linkaxes(ax,'x');
        end
        guidata(hMainFigure,NmrData);
    end
%% ---------Misc Tab (right) Callbacks

%----Macros-------
    % set(hButtonFlipPlusSpec, 'KeyPressFcn', @keyPressCallback); 
    % set(hButtonFlipMinusSpec, 'KeyPressFcn', @keyPressCallback); 
    % set(hMainFigure, 'KeyPressFcn', @keyPressCallback); 
    % % keyPressCallback()
    set(hMainFigure,'WindowKeyPressFcn',@keyPressCallback);
    function keyPressCallback(~,eventdata) 
          % determine the key that was pressed
          keyPressed = eventdata.Key;
          modifier = eventdata.Modifier;
          if isempty(modifier)
              modifier = '';
          end
          if strcmpi(keyPressed,'m')
              % the key that was pressed was the return so set focus to 
              % the plot button
              uicontrol(hButtonFlipPlusSpec);
              % invoke the callback for the plot button
              ButtonFlipPlusSpec_Callback(hButtonFlipPlusSpec,[]);
          elseif strcmpi(keyPressed,'n')
              uicontrol(hButtonFlipMinusSpec);
              % invoke the callback for the plot button
              ButtonFlipMinusSpec_Callback(hButtonFlipMinusSpec,[]);
          elseif strcmpi(keyPressed,'a') && strcmpi(modifier,'Control')
              uicontrol(hButtonFull);
              % invoke the callback for the plot button
              ButtonFull_Callback(hButtonFull,[]);    
          elseif strcmpi(keyPressed,'f') && strcmpi(modifier,'Control')
              uicontrol(hFTButtonShort);
              % invoke the callback for the plot button
              FTButton_Callback(hFTButtonShort,[]);  
          elseif strcmpi(keyPressed,'l') && ~strcmpi(modifier,'Control')
              uicontrol(hSliderPh0);
              tmp = get(hSliderPh0,'value') + 1; 
              set(hSliderPh0,'value',tmp);
              % invoke the callback for the plot button
              SliderPh0_Callback(hSliderPh0,[]);  
          elseif strcmpi(keyPressed,'k') && ~strcmpi(modifier,'Control')
              uicontrol(hSliderPh0);
              tmp = get(hSliderPh0,'value') + 0.1; 
              set(hSliderPh0,'value',tmp);
              % invoke the callback for the plot button
              SliderPh0_Callback(hSliderPh0,[]);  
          elseif strcmpi(keyPressed,'j') && ~strcmpi(modifier,'Control')
              uicontrol(hSliderPh0);
              tmp = get(hSliderPh0,'value') - 0.1; 
              set(hSliderPh0,'value',tmp);
              % invoke the callback for the plot button
              SliderPh0_Callback(hSliderPh0,[]);  
          elseif strcmpi(keyPressed,'h') && ~strcmpi(modifier,'Control')
              uicontrol(hSliderPh0);
              tmp = get(hSliderPh0,'value') - 1; 
              set(hSliderPh0,'value',tmp);
              % invoke the callback for the plot button
              SliderPh0_Callback(hSliderPh0,[]);  
          elseif strcmpi(keyPressed,'l') && strcmpi(modifier,'Control')
              uicontrol(hSliderPh1);
              tmp = get(hSliderPh1,'value') + 1; 
              set(hSliderPh1,'value',tmp);
              % invoke the callback for the plot button
              SliderPh1_Callback(hSliderPh1,[]);  
          elseif strcmpi(keyPressed,'k') && strcmpi(modifier,'Control')
              uicontrol(hSliderPh1);
              tmp = get(hSliderPh1,'value') + 0.1; 
              set(hSliderPh1,'value',tmp);
              % invoke the callback for the plot button
              SliderPh1_Callback(hSliderPh1,[]);  
          elseif strcmpi(keyPressed,'j') && strcmpi(modifier,'Control')
              uicontrol(hSliderPh1);
              tmp = get(hSliderPh1,'value') - 0.1; 
              set(hSliderPh1,'value',tmp);
              % invoke the callback for the plot button
              SliderPh1_Callback(hSliderPh1,[]);  
          elseif strcmpi(keyPressed,'h') && strcmpi(modifier,'Control')
              uicontrol(hSliderPh1);
              tmp = get(hSliderPh1,'value') - 1; 
              set(hSliderPh1,'value',tmp);
              % invoke the callback for the plot button
              SliderPh1_Callback(hSliderPh1,[]); 
          end
     end    
    function MacroRun_Callback( ~, ~)
        %  NmrData=guidata(hMainFigure);
        [filename, pathname] = uigetfile('*.m','Open Macro m-file');
        if isnumeric(filename) || isnumeric(pathname)
            if filename==0 || pathname==0
                return
            end
        end
        FilePath=strcat(pathname,filename);
        Evaluate_Macro_Code(FilePath)
        
        % guidata(hMainFigure,NmrData);
    end
    function MacroUser1_Callback( ~, ~)
        %  NmrData=guidata(hMainFigure);
        
        MacroPath=mfilename('fullpath');
        MacroPath(end-17:end)=[];
        if isunix()==1
            OSslash='/';
        else
            OSslash='\';
        end
        MacroPath=strcat(MacroPath,OSslash);
        MacroPath=strcat(MacroPath,'Macros');
        MacroPath=strcat(MacroPath,OSslash);
        MacroPath=strcat(MacroPath,'Defaults');
        MacroPath=strcat(MacroPath,OSslash);
        MacroPath1=strcat(MacroPath,'GNAT_Macro1.m');
        
        if exist(MacroPath1,'file')
            Evaluate_Macro_Code(MacroPath1)
        else
            msgbox('Default macro 1 (GNAT_Macro1) file does exist','GNAT Warning');
        end
        
        % guidata(hMainFigure,NmrData);
    end
    function Evaluate_Macro_Code(FilePath)
        TmpVar=[]; %#ok<NASGU>
        FileID=fopen(FilePath);
        k=1;
        EvalCode=[];
        while k
            MacroLine=fgetl(FileID);
            if MacroLine==-1;  break;  end
            strtrim(MacroLine);
            ComChar=find(MacroLine =='%');
            if ComChar
                MacroLine(ComChar(1):end)=[];
            end
            strtrim(MacroLine);
            %             while strcmp(MacroLine,'...')
            %                 MacroLine=erase(MacroLine,'...')
            %             end
            
            if MacroLine==""
                %disp('empty')
                %do nothing
            elseif contains(MacroLine,'...') %allowing the use of line splitting
                MacroLine=erase(MacroLine,'...');
                EvalCode=strcat(EvalCode,MacroLine);
            else
                % MacroLine
                
                
                EvalCode=strcat(EvalCode,MacroLine);
                EvalCode=strcat(EvalCode,';');
                DispStr='disp(" ");';
                EvalCode=strcat(EvalCode,DispStr);
                DispStr='disp("Processing line:");';
                EvalCode=strcat(EvalCode,DispStr);
                DispStr=['disp("'  MacroLine  '");'];
                EvalCode=strcat(EvalCode,DispStr);
            end
        end
        %  EvalCode
        disp('Trying Macro')
        
        try
            eval(EvalCode);
            disp('Macro run normally')
        catch ME
            disp('Something went wrong in the next Macro statement (first statement if no macro line printed),')
            disp('with the following error statment:')
            disp(' ')
            disp(ME)
            
        end
    end
%% ---------Neural Network Tab Callback
    function NNPureshift_Callback(~,~)
    %---------------------------------------------------------------------%
    %This function processes a Pure Shift spectrum using a trained neural %
    %network model to enhance spectral quality. The input must be a Pure  %
    %Shift spectrum that has been converted using GNAT. For optimal       %
    %performance, the spectrum should contain 4096 data points. If        %
    %necessary, apply zero-filling to reach 4096 points prior to running  %
    %the neural network enhancement.                                      %
    %                                                                     %
    %The default normalization factor is set to 1, consistent with the    %
    % scaling                                                             %
    %scheme used during the original model training. However, users may   %
    %adjust the normalization factor if the dynamic range of their experimental %
    %data deviates from that of the training dataset.                     %
    %The data are normalized by the maximum absolute value and then scaled%
    %so                                                                   %
    %scaleVal = 1 gives standard normalization (max = 1).                 %
    %Values less than 1 attenuate the signal, while values greater than 1 % 
    % amplify it.                                                         %
    %---------------------------------------------------------------------%

    % Get current dataset
    NmrData = guidata(hMainFigure);

    % Check number of points (direct dimension)
    np = size(NmrData.SPECTRA, 1);
    
    if np ~= 4096
        msg = sprintf(['Data points must be exactly 4096 (found %d). ', ...
                       'Zero-fill the data before proceeding.'], np);
    
        errordlg(msg);     
        WriteLogDispInfo(msg);    
        return
    end

    isNN1 = get(hNN1Check,'Value');
    isNN2 = get(hNN2Check,'Value');

    % --- Validation
        if ~isNN1 && ~isNN2
            msg = 'Please select either NN1 or NN2 before proceeding.';
            warning('GNAT:NNSelection',msg);
            WriteLogDispInfo(msg);
            return
        end
        
        if isNN1 && isNN2
            msg = 'Please select only one neural network (NN1 or NN2).';
            warning('GNAT:NNSelection',msg);
            WriteLogDispInfo(msg);
            return
        end

        persistent netNN1 netNN2
        
                gnathPath = which('GNAT.m');
            
                if ~isempty(gnathPath)
                    basePath = fileparts(fileparts(gnathPath));
                else
                    basePath = pwd;
                end
            
       
           % --- Proceed Accordingly
            if isNN1
            
                WriteLogDispInfo('NN1 selected. Running NN1 processing...');
                disp('--- NN1 DEBUG START ---')
                        try
                        if isempty(netNN1)
                          if isMATLABReleaseOlderThan("R2025a")
                            modelPath = fullfile(basePath, ...
                                                'Associated Toolbox', ...
                                                'NeuralNetwork', ...
                                                '2025_Older', ...
                                                'netNN1.mat');
                          else
                             modelPath = fullfile(basePath, ...
                                                'Associated Toolbox', ...
                                                'NeuralNetwork', ...
                                                '2025_Newer', ...
                                                'netNN1.mat');
                          end
                         
                            
                            % --- Debug
                           
                            disp(['Base path: ' basePath])
                            disp(['Model path: ' modelPath])
                            disp(['Exists: ' num2str(exist(modelPath,'file'))])
                    
                            % --- Hard check
                            assert(exist(modelPath,'file')==2, 'netNN1.mat not found in ctfroot');
                    
                            % --- Load model
                            S = load(modelPath, 'netNN1');
                            netNN1 = S.netNN1;
                    
                            % --- Verify
                            disp(['Loaded NN1 class: ' class(netNN1)])
                            WriteLogDispInfo('NN1 loaded from MAT file.');
                    
                            disp('--- NN1 DEBUG END ---')
                    
                        end
                    
                        catch ME
                            disp('NN1 ERROR:')
                            disp(ME.message)
                            for k = 1:length(ME.stack)
                                disp(ME.stack(k))
                            end
                            error('NN1 loading failed'); % stop execution cleanly
                        end           
            
            elseif isNN2
            
                WriteLogDispInfo('NN2 selected. Running NN2 processing...');
                disp('--- NN2 DEBUG START ---')
            
                try
                    if isempty(netNN2)
                
                           if isMATLABReleaseOlderThan("R2025a")
                            modelPath = fullfile(basePath, ...
                                                'Associated Toolbox', ...
                                                'NeuralNetwork', ...
                                                '2025_Older', ...
                                                'netNN2.mat');
                          else
                             modelPath = fullfile(basePath, ...
                                                'Associated Toolbox', ...
                                                'NeuralNetwork', ...
                                                '2025_Newer', ...
                                                'netNN2.mat');
                          end
                            
                
                        % --- Debug
                      
                        disp(['Base path: ' basePath])
                        disp(['Model path: ' modelPath])
                        disp(['Exists: ' num2str(exist(modelPath,'file'))])
                
                        % --- Hard check
                        assert(exist(modelPath,'file')==2, 'netNN2.mat not found in ctfroot');
                
                        % --- Load model
                        S = load(modelPath, 'netNN2');
                        netNN2 = S.netNN2;
                
                        % --- Verify
                        disp(['Loaded NN2 class: ' class(netNN2)])
                        WriteLogDispInfo('NN2 loaded from MAT file.');
                
                        disp('--- NN2 DEBUG END ---')
                
                end
                            
                catch ME
                    disp('NN2 ERROR:')
                    disp(ME.message)
                    for k = 1:length(ME.stack)
                        disp(ME.stack(k))
                    end
                    error('NN2 loading failed'); % stop execution cleanly
                end
            
                disp('--- NN2 DEBUG END ---')
            
            end

        % --- Select network
    if isNN1
        net = netNN1;   % assume loaded earlier
        WriteLogDispInfo('Using NN1 for prediction.');
    elseif isNN2
        net = netNN2;
        WriteLogDispInfo('Using NN2 for prediction.');
    end


    % Save original for undo (only once)
    if ~isfield(NmrData,'nndata.orig')
        NmrData.nndata.orig = NmrData;
    end

    guidata(hMainFigure,NmrData);

      scaleVal = str2double(get(hScaleNN,'String'));
        % --- Validate numeric input
        if isnan(scaleVal) || ~isfinite(scaleVal)
            msg = 'Normalization factor must be a valid numeric value.';
            warning('GNAT:InvalidScaling',msg);
            WriteLogDispInfo(msg);
            return
        end
        
        if scaleVal <= 0
            msg = 'Normalization factor must be positive.';
            warning('GNAT:InvalidScaling',msg);
            WriteLogDispInfo(msg);
            return
        end

        WriteLogDispInfo(sprintf('Normalization factor set to %.4g', scaleVal));


    if isempty(NmrData) || isempty(NmrData.SPECTRA)
        WriteLogDispInfo('No spectrum loaded.');
        return
    end
       

        origSpec = real(NmrData.SPECTRA);     
        [~, narray] = size(origSpec);
        if isfield(NmrData,'exclude')
            if get(hExcludeShow,'Value')
                for k=1:NmrData.arraydim
                    origSpec(:,k)=...
                        origSpec(:,k).*isnan(NmrData.exclude');
                end
            end
        end
        
        recSpec = zeros(4096, narray);
        
        for k = 1:narray
        
            X = (origSpec(:,k));
        
            if length(X) ~= 4096
                n = length(X);
                X = interp1(1:n, X, linspace(1,n,4096));
            end
        
            % Match training orientation
            X = flipud(X);
        
            X = single(X(:));
            X = X./((max(abs(X)))/scaleVal);
            if isMATLABReleaseOlderThan("R2025a")
                X = reshape(X, [1 1 4096 1]);
               % X=reshape(X,1,1,4096,1);
            else
            X = reshape(X,[4096 1 1 1]);
            end
        
                disp('--- NET INFO ---')
                disp(class(net))
                disp(size(X))

            if isMATLABReleaseOlderThan("R2025a")
                     % --- Predict
                if isa(net,'dlnetwork')
                    dlX = dlarray(X,'SSC');
                    Y = predict(net, dlX);
                    Y = extractdata(Y);
                else
                    Y = predict(net, X);
                end
            else
                           % --- Predict
                if isa(net,'dlnetwork')
                    dlX = dlarray(X,'BSSC');
                    Y = predict(net, dlX);
                    Y = extractdata(Y);
                   % Y = predict(net, X, "InputDataFormats","BSSC");
                else
                    Y = predict(net, X);
                end
            end
            %Y = Y.*(max(abs(X)));
            %X = X.*((max(abs(X))));
        
            % Restore GNAT orientation
            recSpec(:,k) = flipud(squeeze(Y));
        
        end
        
        recSpec=recSpec./max(recSpec);
        NmrData.SPECTRA = recSpec;
        NmrData.fn      = size(recSpec,1);
        NmrData.np      = NmrData.fn;
        NmrData.arraydim = narray;
        NmrData.rp = 0;
        NmrData.lp = 0;

        guidata(hMainFigure,NmrData);
        
        Setup_NmrData_NN();
        ButtonAutoscale_Callback();

        isSepPlot = get(hSepPlotCheck,'Value');

        if isSepPlot
            X = real(X(:));
        % Separate Plot if user needs it.
        figure;
        plot(flipud(real(X(:,1))), 'b'); hold on;
        plot(recSpec(:,1), 'r--','LineWidth',1.5);
        xlabel('Data Points');
        ylabel('Intensity');
        legend('Input Spectrum','NN Output');
        title('Enhanced NMR Spectrum');
        grid on;
         WriteLogDispInfo('Separate plot is plotted.');
        else
         WriteLogDispInfo('No separate plot is asked.');
        end


    WriteLogDispInfo('Neural network pure-shift reconstruction complete.');

end

    function UndoNNPureshift_Callback(~,~)
    %---------------------------------------------------------------------%
    %This function converts the neural network–enhanced spectrum back to  %
    %a Pure Shift representation. The input should be the processed       %
    %spectrum generated by the neural network enhancement routine within  %
    %GNAT. The function restores the spectral format to match the         %
    %original Pure Shift data structure.                                  %
    %---------------------------------------------------------------------%

    NmrData = guidata(hMainFigure);

    if ~isfield(NmrData,'nndata') || isempty(NmrData.nndata.orig)
        WriteLogDispInfo('No previous state to restore.');
        return
    end

    % Restore previous dataset
    NmrData = NmrData.nndata.orig;

    guidata(hMainFigure, NmrData);
    Setup_NmrData();

    WriteLogDispInfo('Neural network reconstruction undone.');

end
%% Utility functions
    function ButtonphaseTable_Callback(~,~)
        NmrData=guidata(hMainFigure);
        
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
            guidata(hMainFigure,NmrData);
            
        if NmrData.narray2*NmrData.ngrad<NmrData.arraydim
            disp('Not suitable for 4D data')
            return
        else
            
            switch  get(hScopeGroup,'SelectedObject')
                case hRadioScopeGlobal
                    disp('Not suitable for Global phasing')
                    return
                case hRadioScopeIndividual
                    Table_pch0=reshape(NmrData.rpInd,NmrData.ngrad,NmrData.narray2);
                    Table_pch0=Table_pch0';
                    Table_pch1=reshape(NmrData.lpInd,NmrData.ngrad,NmrData.narray2);
                    Table_pch1=Table_pch1';
                    if isfield(NmrData,'hTablePhases')
                        if isvalid(NmrData.hTablePhases)
                            close(NmrData.hTablePhases)
                        end
                    end

            end
        end
            hTablePhases=figure(...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Units','Normalized',...
                'Visible','Off',...
                'Toolbar','none',...
                'Name','Settings');
            NmrData.hTablePhases=hTablePhases;
            hPhasesUiTabGroup=uitabgroup(...
                'Parent',hTablePhases,...
                'Position',[0.0 0.0 1.0 1.0],...
                'Units','Normalized');
            hSPhasesUiTab1=uitab(...
                'Parent',hPhasesUiTabGroup,...
                'Title','Phase Correction Order 0',...
                'Units','Normalized');
            hPhasesUiTab2=uitab(...
                'Parent',hPhasesUiTabGroup,...
                'Title','Phase Correction Order 1',...
                'Units','Normalized');
            
            hTablePch0=uitable(...
                'Data',Table_pch0,...
                'Parent',hSPhasesUiTab1,...
                'Units','Normalized',...
                'ColumnEditable',true(1,numel(Table_pch0)),...
                'Position',[0.1 0.05 0.9 0.9 ],...
                'CellEditCallBack', {@TablePhases_Callback});
            hTablePch1=uitable(...
                'Data',Table_pch1,...
                'Parent',hPhasesUiTab2,...
                'Units','Normalized',...
                'ColumnEditable',true(1,numel(Table_pch1)),...
                'Position',[0.1 0.05 0.9 0.9 ],...
                'CellEditCallBack', {@TablePhases_Callback});
            
            guidata(hMainFigure,NmrData);
            
            function TablePhases_Callback( ~, ~)
            NmrData=guidata(hMainFigure);
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
            guidata(hMainFigure,NmrData);
            
            originalPhase0=NmrData.rpInd;
            tmpphase=get(hTablePch0,'Data');
            if sum(isnan(tmpphase))
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only numeric values can be entered as gradient amplitudes')
                return
            else
                NmrData.rpInd=reshape(tmpphase',1,NmrData.ngrad*NmrData.narray2);
            end
            rpChange=NmrData.rpInd-originalPhase0;
            guidata(hMainFigure,NmrData);
            
            NmrData=guidata(hMainFigure);
            originalPhase1=NmrData.lpInd;
            tmpphase=get(hTablePch1,'Data');
            if sum(isnan(tmpphase))
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Only numeric values can be entered as gradient amplitudes')
                return
            else
                NmrData.lpInd=reshape(tmpphase',1,NmrData.ngrad*NmrData.narray2);
            end
            lpChange=NmrData.lpInd-originalPhase1;
            guidata(hMainFigure,NmrData);
            
            Rc=1i*(pi/180);
            for ii=1:NmrData.arraydim
                lpCorr= linspace(0,1,NmrData.fn)*lpChange(ii);
                lpCorrDSP= linspace(0,1,NmrData.fn)*0;
                phaseCorr=...
                    (exp(Rc*(rpChange(ii) + lpCorr+ lpCorrDSP)))';
                NmrData.SPECTRA(:,ii)=...
                    NmrData.SPECTRA(:,ii).*phaseCorr;
            end
            
            set(hEditPh1,'string',num2str(NmrData.lpInd(NmrData.flipnr),4))
            set(hEditPh0,'string',num2str(NmrData.rpInd(NmrData.flipnr),4))
            set(hSliderPh0,'value',NmrData.rpInd(NmrData.flipnr));
            set(hSliderPh1,'value',NmrData.lpInd(NmrData.flipnr));
           
            guidata(hMainFigure,NmrData);
            PlotSpectrum();
            end
            
            
            set(hTablePhases,'Visible','On');
    end
    function PeakWidth=EstimatePeakshape(Spec,MaxPoint)
        
        if MaxPoint==0
            [~, MaxPoint]=max(Spec);
        end
        IntFac=16;
        SearchPoints=16;
        if MaxPoint<SearchPoints
            SearchPoints=MaxPoint-1;
        elseif length(Spec)-MaxPoint<SearchPoints
            SearchPoints=length(Spec)-MaxPoint-1;
        else
            SearchPoints=16;
        end
        IntSpec=interpft(Spec,IntFac*length(Spec)+2);
        [MaxPointIntAmp, MaxPointInt]=max(IntSpec(IntFac*(MaxPoint-SearchPoints):IntFac*(MaxPoint+SearchPoints)));
        MaxPointInt=IntFac*(MaxPoint-SearchPoints) + MaxPointInt -1;
        
        for k=1:length(IntSpec(MaxPointInt:end))
            IntSpec(MaxPointInt+k);
            if IntSpec(MaxPointInt+k)<MaxPointIntAmp/2
                break
            end
            
        end
        RightPoint=k;
        
        for k=1:length(IntSpec(1:MaxPointInt))
            IntSpec(MaxPointInt-k);
            if IntSpec(MaxPointInt-k)<MaxPointIntAmp/2
                break
            end
        end
        LeftPoint=k;
        PeakWidth=(((RightPoint+LeftPoint)/NmrData.fn)*(NmrData.sw*NmrData.sfrq))/IntFac;
    end
    function Baseline_function(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.BasePoints(1)=NmrData.Specscale(1);
        if isempty(get(hMainFigure,'WindowButtonDownFcn'))
            %we only update the parameters
            %disp('Hi')
        else
            switch get(gcbf, 'SelectionType')
                case 'normal'
                    %leftclick
                    %add a new point
                    pt=get(gca,'currentpoint');
                    xpos=pt(1,1);
                    ypos=pt(2,2);
                    xl=xlim(hAxes);
                    yl=ylim(hAxes);
                    if xpos>xl(2) || xpos<xl(1) || ypos>yl(2) || ypos<yl(1)
                        %outside axis
                    else
                        NmrData.BasePoints=[NmrData.BasePoints xpos];
                    end
                    
                case 'alt'
                    %remove last point
                    if ~isempty(NmrData.BasePoints>0)
                        NmrData.BasePoints(end)=[];
                    end
                case 'extend'
                    %middleclick
                    %Stop taking new points
                    set(hMainFigure,'WindowButtonDownFcn','')
                case 'open'
                    %doubleclick
                    %do nothing
                    
                otherwise
                    error('illegal choice')
            end
        end
        
        NmrData.baselinepoints=NmrData.BasePoints;
      
        
        NmrData.baselinepoints=unique(NmrData.baselinepoints);
        NmrData.baselinepoints=sort(NmrData.baselinepoints);
        NmrData.region=ones(1,NmrData.fn);
        bpoints=[1 NmrData.fn];
        for k=1:length(NmrData.baselinepoints)
            bpoints=[bpoints round(NmrData.fn*...
                (NmrData.baselinepoints(k)-NmrData.sp)/NmrData.sw)]; %#ok<AGROW>
        end
        bpoints=unique(bpoints);
        bpoints=sort(bpoints);
        if bpoints(1)==0
            bpoints(1)=1;
        end
        if bpoints(end)==NmrData.fn
            bpoints(end)=NmrData.fn;
        end
%         bpoints=unique(bpoints)
%         bpoints=sort(bpoints);
%         
        bpoints1=bpoints(1:2:end);
        bpoints2=bpoints(2:2:end);
        for k=1:(length(bpoints1))
            if k<=length(bpoints2)
                NmrData.region(bpoints1(k):bpoints2(k))=NaN;
            end
        end
        if NmrData.plottype==0
            NmrData.xlim_fid=xlim(hAxes);
            NmrData.ylim_fid=ylim(hAxes);
        elseif NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        else
            error('Illegal plot type')
        end
        %a=NmrData.BasePoints;
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function Auto_Baseline_function(indata)
        % Journal of Magnetic Resonance, 27, 265-272 (1977)
        NmrData=guidata(hMainFigure);
        
        u_mn=6; %4 reccomended from paper but prob from grotty data
        v_mn=6; %2-3 reccomended from paper
        negl_fac_mn=0.125; % 0.125 from paper
        
        sigma1=1/0; %starting value: infinity
        
        cut_perc=5;%ignore this % of spectrum each side
        
        spec_org=NmrData.SPECTRA;
        spec=real(NmrData.SPECTRA(:,NmrData.flipnr));
        spec_cut=round(numel(spec)*cut_perc*0.01);
        spec(1:spec_cut)=0;
        spec(end-spec_cut:end)=0;
        
        spec_sq=spec.^2;
        spec_abs=abs(spec);
        
        it_max=1000;
        
        for k=1:it_max
            %create the heaviside functionality
            spec_u_heavi=u_mn*sigma1-spec_abs;
            spec_u_heavi(spec_u_heavi>0)=1;
            spec_u_heavi(spec_u_heavi<0)=0;
            
            %Tentative sigma
            sigma0=sum((spec_sq.*spec_u_heavi))/(1+sum(spec_u_heavi));
            sigma0=sqrt(sigma0);
            
            if sigma0==sigma1
                %do the fitting
                NmrData.baselinecorr=zeros(NmrData.fn,NmrData.arraydim);
                
                spec_v=v_mn*sigma1-spec_abs;
                if indata.caller==1 %Baseline corrections
                    for m=1:NmrData.arraydim
                        
                        basefit=polyfit(NmrData.Specscale(spec_v>0)'...
                            ,NmrData.SPECTRA(spec_v>0,m),NmrData.order);
                        NmrData.baselinecorr(:,m)=polyval(basefit,NmrData.Specscale);
                        NmrData.SPECTRA(:,m)=NmrData.SPECTRA(:,m)...
                            -NmrData.baselinecorr(:,m);
                    end
                end
                spec=real(NmrData.SPECTRA(:,NmrData.flipnr));
                spec(1:spec_cut)=0;
                spec(end-spec_cut:end)=0;
                spec_sq=spec.^2;
                spec_abs=abs(spec);
                
                if sum(abs(NmrData.baselinecorr))<(negl_fac_mn* sigma1)
                    break
                end
                
            else
                %copy new sigma and go again
                sigma1=sigma0;
            end
        end
        if k==it_max
            warning('Maximum iterations for baseline/integral regions')
        end
        
        baseswitch=1;
        basetest=spec_v>0;
        NmrData.BasePoints=[];
        for p=1:NmrData.fn
            
            if basetest(p)==1 && baseswitch==0
                %set a basepoint and change switch
                NmrData.BasePoints=[NmrData.BasePoints NmrData.Specscale(p)];
                baseswitch=1;
            elseif basetest(p)==1 && baseswitch==1
                % do nothing
            elseif basetest(p)==0 && baseswitch==1
                %set a basepoint and change switch
                NmrData.BasePoints=[NmrData.BasePoints NmrData.Specscale(p)];
                baseswitch=0;
            elseif basetest(p)==0 && baseswitch==0
                %set a basepoint and change switch
                % do nothing
            else
                error('unexpected')
            end
        end
        set(hMainFigure,'WindowButtonDownFcn','')
        
        if indata.caller==1 %Baseline corrections
            
            guidata(hMainFigure,NmrData);
            Baseline_function();
            PlotSpectrum();
        elseif indata.caller==2 %Integral regions
            NmrData.SPECTRA=spec_org;
            guidata(hMainFigure,NmrData);
            NmrData.IntPoint=NmrData.BasePoints;
            IntLine_function();
        end
        
        guidata(hMainFigure,NmrData);
    end
    function Excludeline_function(~,~)
        NmrData=guidata(hMainFigure);

        switch get(gcbf, 'SelectionType')
            case 'normal'
                %leftclick
                %add a new point
                pt=get(gca,'currentpoint');
                xpos=pt(1,1);
                ypos=pt(2,2);
                xl=xlim(hAxes);
                yl=ylim(hAxes);
                if xpos>xl(2) || xpos<xl(1) || ypos>yl(2) || ypos<yl(1)
                    %outside axis
                else
                    NmrData.ExcludePoints=[NmrData.ExcludePoints xpos];
                end
                
            case 'alt'
                %remove last point
                if ~isempty(NmrData.ExcludePoints>0)
                    NmrData.ExcludePoints(end)=[];
                end
            case 'extend'
                %middleclick
                %Stop taking new points
                set(hMainFigure,'WindowButtonDownFcn','')
            case 'open'
                %doubleclick
                %do nothing
                
            otherwise
                error('illegal choice')
        end
        NmrData.excludelinepoints=unique(NmrData.ExcludePoints);
        NmrData.excludelinepoints=sort(NmrData.excludelinepoints);
        NmrData.exclude=ones(1,NmrData.fn);
        expoints=[1 NmrData.fn];
        for k=1:length(NmrData.excludelinepoints)
            expoints=[expoints round(NmrData.fn*...
                (NmrData.excludelinepoints(k)-NmrData.sp)/NmrData.sw)]; %#ok<AGROW>
        end
        expoints=unique(expoints);
        expoints=sort(expoints);
        expoints1=expoints(1:2:end);
        expoints2=expoints(2:2:end);
        for k=1:(length(expoints1))
            if k<=length(expoints2)
                NmrData.exclude(expoints1(k):expoints2(k))=NaN;
            end
        end
        hExcludeline=findobj(hAxes,'tag','excludeline');
        delete(hExcludeline)
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        %DrawExcludeline();
        %set(hAxes,'ButtonDownFcn',@Excludeline_function);
        %set(hMainFigure,'WindowButtonDownFcn',@Excludeline_function);
    end
    function IntLine_function(~,~)
        
        if isempty(get(hMainFigure,'WindowButtonDownFcn'))
            %do nothing
        else
            switch get(gcbf, 'SelectionType')
                case 'normal'
                    %leftclick
                    %add a new point
                    pt=get(gca,'currentpoint');
                    xpos=pt(1,1);
                    ypos=pt(2,2);
                    xl=xlim(hAxes);
                    yl=ylim(hAxes);
                    if xpos>xl(2) || xpos<xl(1) || ypos>yl(2) || ypos<yl(1)
                        %outside axis
                    else
                        NmrData.IntPoint=[NmrData.IntPoint xpos];
                       
                    end
                case 'alt'
                    %Righ click
                    pt=get(gca,'currentpoint');
                    xpos=pt(1,1);
                    ypos=pt(2,2); %#ok<NASGU>
                    %xl=xlim(hAxes);
                    %yl=ylim(hAxes);
                    selectedpeak=[];
                    npeaks=size(NmrData.integral_peaks,2);
                    for peaknr=1:npeaks
                        peaksregion=NmrData.integral_peaks;
                         start=peaksregion(peaknr).start;
                         stop=peaksregion(peaknr).stop;
                        if xpos>=start && xpos<=stop
                            selectedpeak=peaknr;
                            break
                        end
                    end
                    if ~isempty(selectedpeak)
                        NmrData.IntPoint(NmrData.IntPoint==start)=[];
                        NmrData.IntPoint(NmrData.IntPoint==stop)=[];
                    end

                case 'extend'
                    %middleclick
                    %Stop taking new points
                    set(hMainFigure,'WindowButtonDownFcn','')
                case 'open'
                    %doubleclick
                    %do nothing
                otherwise
                    error('illegal choice')
            end
        end
        
        NmrData.IntPointSort=unique(NmrData.IntPoint);
        NmrData.IntPointSort=sort(NmrData.IntPointSort);
        IntPointIndex=[];
        for k=1:length(NmrData.IntPointSort)
            IntPointIndex=[IntPointIndex round(NmrData.fn*...
                (NmrData.IntPointSort(k)-NmrData.sp)/NmrData.sw)]; %#ok<AGROW>
        end
        IntPointIndex=unique(IntPointIndex);
        IntPointIndex=sort(IntPointIndex);
        if bitand(1,length(IntPointIndex)) %odd
            IntPointIndex=[1 IntPointIndex];
            NmrData.Integral=ones(1,NmrData.fn);
            for k=1:length(IntPointIndex)/2
                NmrData.Integral(IntPointIndex(2*k-1):IntPointIndex(2*k)+1)=NaN;
            end
        else %even
            NmrData.Integral=ones(1,NmrData.fn).*NaN;
            for k=1:length(IntPointIndex)/2
                
                NmrData.Integral((IntPointIndex(2*k-1)):(IntPointIndex(2*k)))=1;
                %NmrData.Integral(IntPointIndex(kk):IntPointIndex(kk+1))=NaN;
            end
        end
        NmrData.IntPointIndex=IntPointIndex;
        %make integral regions for fitting
        spectmp=real(NmrData.SPECTRA(:,NmrData.flipnr));
        integral_peaks=[];
        for m=1:length(NmrData.IntPointSort)/2
            integral_peaks(m).start=NmrData.IntPointSort(2*m-1); %#ok<AGROW>
            integral_peaks(m).startIndex=NmrData.IntPointIndex(2*m-1); %#ok<AGROW>
            integral_peaks(m).stop=NmrData.IntPointSort(2*m); %#ok<AGROW>
            integral_peaks(m).stopIndex=NmrData.IntPointIndex(2*m); %#ok<AGROW>
            [~, Index]=max(spectmp(NmrData.IntPointIndex(2*m-1): NmrData.IntPointIndex(2*m)));
            SpecIndex=NmrData.IntPointIndex(2*m-1)+ Index;
            integral_peaks(m).max=NmrData.Specscale(SpecIndex); %#ok<AGROW>
            integral_peaks(m).maxIndex=SpecIndex; %#ok<AGROW>
            integral_peaks(m).ValueRaw=sum(spectmp(integral_peaks(m).startIndex:...
                integral_peaks(m).stopIndex)); %#ok<AGROW>
            integral_peaks(m).Offset=0; %#ok<AGROW>
            integral_peaks(m).Tilt=0; %#ok<AGROW>
            for k=1:NmrData.arraydim
                integral_peaks(m).Individual(k).Offset=0;
                integral_peaks(m).Individual(k).Tilt=0;
            end
            %integral_peaks(m).ValueCorrected=integral_peaks(m).ValueRaw; %#ok<AGROW>
            %Will need value and Value corrected for export. DOSY etc.
        end
        NmrData.integral_peaks=integral_peaks;
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function DrawIntLine(~,~)
        NmrData=guidata(hMainFigure);
        
        hIntLine=findobj(hAxes,'tag','IntLine');
        delete(hIntLine);
        TmpIntegral=NmrData.Integral;
        %Calculating the cumulative sum of integrals for plotting
        if isempty(NmrData.SPECTRA)
            RealSpec=0;
        else
            RealSpec=real(NmrData.SPECTRA(:,NmrData.flipnr));
        end
        IntSpec=zeros(size(NmrData.Integral));
        CumSum=0;
        for k=1:numel(NmrData.integral_peaks)
            Start=NmrData.integral_peaks(k).startIndex;
            Stop=NmrData.integral_peaks(k).stopIndex;
            if get(hRadioScopeGlobalInt,'Value')
                Offset=NmrData.integral_peaks(k).Offset;
                Tilt=NmrData.integral_peaks(k).Tilt;
            else
                Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
            end
            %TiltLine=zeros(1,Stop-Start);
            tmp=0:(Stop-Start);
            tmp=(Tilt*tmp)/tmp(end);
            TiltLine=tmp(:);
            IntSpec(Start:Stop)=cumsum(RealSpec(Start:Stop)-Offset -TiltLine) + CumSum ;
            CumSum=sum(RealSpec(Start:Stop)-Offset-TiltLine) + CumSum;
        end
        
        IntSpec(IntSpec==0)=NaN;
        ypos=get(hAxes,'ylim');
        ydata=0.9*ypos(2)-(IntSpec/max(IntSpec))*ypos(2)*0.9;
        xlimits=get(hAxes,'xlim');
        %hIntLine=
        line(NmrData.Specscale,ydata,...
            'color',[0 0.8 0],'linewidth', 1,...
            'tag','IntLine');
        set(hAxes,'xlim',xlimits);
        %plot peak numbers
        ypos=get(hAxes,'ylim');
        yp=(ypos(2)-ypos(1))/2;
        %yp1=0.2*yp + ypos(1);
        yp2=0.1*yp + ypos(1);
        if ~isempty(NmrData.IntPointIndex) && NmrData.IntPointIndex(1)==1
            NmrData.IntPointIndex(  1)=[];
        end
        
        for k=1:numel(NmrData.integral_peaks)
            yPos=RealSpec(NmrData.integral_peaks(k).maxIndex) +0.2*yp;
            text(NmrData.integral_peaks(k).max,yPos,num2str(k));
        end
        intnorm=str2double(get(hEditNorm,'String'));
        intpeak=round(str2double(get(hEditNormPeak,'String')));
        intcum=0;%#ok<NASGU>
        %Calculate normalisation
        switch get(hBGroupNormalise,'SelectedObject')
            case hRadio1Normalise %Peak
                for k=1:numel(NmrData.integral_peaks)
                    if numel(NmrData.integral_peaks)<intpeak
                        set(hEditNormPeak,'String', num2str(1));
                        intpeak=1;
                    end
                    StartRef=NmrData.integral_peaks(intpeak).startIndex;
                    StopRef=NmrData.integral_peaks(intpeak).stopIndex;
                    if get(hRadioScopeGlobalInt,'Value')
                        OffsetRef=NmrData.integral_peaks(k).Offset;
                        TiltRef=NmrData.integral_peaks(k).Tilt;
                    else
                        OffsetRef=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                        TiltRef=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                    end
                    tmp=0:(StopRef-StartRef);
                    tmp=(TiltRef*tmp)/tmp(end);
                    TiltLineRef=tmp(:);
                    RefInt=sum(RealSpec(StartRef:StopRef)-OffsetRef - TiltLineRef);
                    
                    Start=NmrData.integral_peaks(k).startIndex;
                    Stop=NmrData.integral_peaks(k).stopIndex;
                    if get(hRadioScopeGlobalInt,'Value')
                        Offset=NmrData.integral_peaks(k).Offset;
                        Tilt=NmrData.integral_peaks(k).Tilt;
                    else
                        Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                        Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                    end
                    tmp=0:(Stop-Start);
                    tmp=(Tilt*tmp)/tmp(end);
                    TiltLine=tmp(:);
                    IntPeak=intnorm*sum(RealSpec(Start:Stop)-Offset - TiltLine)/RefInt;
                    text(NmrData.integral_peaks(k).max,yp2,num2str(IntPeak));
                end
                
            case hRadio2Normalise %Total
                for k=1:numel(NmrData.integral_peaks)
                    Start=NmrData.integral_peaks(k).startIndex;
                    Stop=NmrData.integral_peaks(k).stopIndex;
                    if get(hRadioScopeGlobalInt,'Value')
                        Offset=NmrData.integral_peaks(k).Offset;
                        Tilt=NmrData.integral_peaks(k).Tilt;
                    else
                        Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                        Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                    end
                    tmp=0:(Stop-Start);
                    tmp=(Tilt*tmp)/tmp(end);
                    TiltLine=tmp(:);
                    IntPeak=intnorm*sum(RealSpec(Start:Stop)-Offset -TiltLine)/CumSum;
                    text(NmrData.integral_peaks(k).max,yp2,num2str(IntPeak));
                end
                
            case hRadio3Normalise %Absolute
                for k=1:numel(NmrData.integral_peaks)
                    Start=NmrData.integral_peaks(k).startIndex;
                    Stop=NmrData.integral_peaks(k).stopIndex;
                    if get(hRadioScopeGlobalInt,'Value')
                        Offset=NmrData.integral_peaks(k).Offset;
                        Tilt=NmrData.integral_peaks(k).Tilt;
                    else
                        Offset=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Offset;
                        Tilt=NmrData.integral_peaks(k).Individual(NmrData.flipnr).Tilt;
                    end
                    tmp=0:(Stop-Start);
                    tmp=(Tilt*tmp)/tmp(end);
                    TiltLine=tmp(:);
                    IntPeak=sum(RealSpec(Start:Stop)-Offset - TiltLine);
                    text(NmrData.integral_peaks(k).max,yp2,num2str(IntPeak));
                end
                
            otherwise
                error('illegal choice')
        end
        
        NmrData.Integral=TmpIntegral;
        guidata(hMainFigure,NmrData);
    end
    function DrawBaseline(~,~)
        NmrData=guidata(hMainFigure);
        hBaseline=findobj(hAxes,'tag','baseline');
        delete(hBaseline)
        ypos=get(hAxes,'ylim');
        ypos=(ypos(2)-ypos(1))/2;
        ydata=ypos.*NmrData.region;
        xlimits=get(hAxes,'xlim');
        line(NmrData.Specscale,ydata,...
            'color','g','linewidth', 1.0,...
            'tag','baseline');
        set(hAxes,'xlim',xlimits);
        guidata(hMainFigure,NmrData);
    end
    function NoiseLine_function(~,~)
        NmrData=guidata(hMainFigure);

        switch get(gcbf, 'SelectionType')
            case 'normal'
                %leftclick
                %add a new point
                pt=get(gca,'currentpoint');
                xpos=pt(1,1);
                ypos=pt(2,2);
                xl=xlim(hAxes);
                yl=ylim(hAxes);
                if xpos>xl(2) || xpos<xl(1) || ypos>yl(2) || ypos<yl(1)
                    %outside axis
                else
                    NmrData.ExcludePoints=[NmrData.ExcludePoints xpos];
                end
                
            case 'alt'
                %remove last point
            case 'extend'
                %middleclick
            case 'open'
                %doubleclick
                
            otherwise
                error('illegal choice')
        end
        NmrData.excludelinepoints=unique(NmrData.ExcludePoints);
        NmrData.excludelinepoints=sort(NmrData.excludelinepoints);
        NmrData.exclude=ones(1,NmrData.fn);
        expoints=[1 NmrData.fn];
        for k=1:length(NmrData.excludelinepoints)
            expoints=[expoints round(NmrData.fn*...
                (NmrData.excludelinepoints(k)-NmrData.sp)/NmrData.sw)]; %#ok<AGROW>
        end
        expoints=unique(expoints);
        expoints=sort(expoints);
        expoints1=expoints(1:2:end);
        expoints2=expoints(2:2:end);
        for k=1:(length(expoints1))
            if k<=length(expoints2)
                NmrData.exclude(expoints1(k):expoints2(k))=NaN;
            end
        end
        hNoiseLine=findobj(hAxes,'tag','NoiseLine');
        delete(hNoiseLine)
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
    end
    function DrawNoiseLine(~,~)
        NmrData=guidata(hMainFigure);
        hNoiseLine=findobj(hAxes,'tag','NoiseLine');
        delete(hNoiseLine)
        ypos=get(hAxes,'ylim');
        ypos=(ypos(2)-ypos(1))/3;
        ydata=ypos.*NmrData.exclude;
        xlimits=get(hAxes,'xlim');
        %hExcludeline=
        line(NmrData.Specscale,ydata,...
            'color','r','linewidth', 1.0,...
            'tag','excludeline');
        set(hAxes,'xlim',xlimits);
        
        guidata(hMainFigure,NmrData);
    end
    function Threshold_function(~,~)
        %set a threshold
        NmrData=guidata(hMainFigure);
        set(hMainFigure,'WindowButtonDownFcn','')
        guidata(hMainFigure,NmrData);
        hThresh=findobj(hAxes,'tag','threshold');
        delete(hThresh);  %(works even if hthresh==[])
        pt=get(gca,'currentpoint');
        ypos=pt(1,2);
        switch NmrData.shiftunits
            case 'ppm'
                startunit='ppm';
            case 'Hz'
                NmrData.shiftunits='ppm';
                NmrData.xlim_spec=NmrData.xlim_spec./NmrData.sfrq;
                startunit='Hz';
            otherwise
                error('illegal choice')
        end
        
        speclim=NmrData.xlim_spec;
        speclim=NmrData.fn*(speclim-NmrData.sp)/NmrData.sw;
        if speclim(1)<1
            speclim(1)=1;
        end
        if speclim(2)>NmrData.fn
            speclim(2)=NmrData.fn;
        end
        speclim=round(speclim);
        NmrData.th=100*ypos/max(real(NmrData.SPECTRA(speclim(1):speclim(2),NmrData.flipnr)));
        
        %NmrData.th=100*ypos/max(real(NmrData.SPECTRA(NmrData.xlim_spec(1):NmrData.xlim_spec(2),NmrData.flipnr)));
        
        switch startunit
            case 'ppm'
                %all fine
            case 'Hz'
                NmrData.shiftunits='Hz';
                NmrData.xlim_spec=NmrData.xlim_spec.*NmrData.sfrq;
                NmrData.reference=NmrData.reference.*NmrData.sfrq;
            otherwise
                error('illegal choice')
        end
        NmrData.thresydata=[ypos ypos];
        %b=NmrData.thresydata
        NmrData.thresxdata=get(hAxes,'xlim');
        line(NmrData.thresxdata,NmrData.thresydata,...
            'color','Black','linewidth', 1.0,...
            'tag','threshold');
        drawnow
        guidata(hMainFigure,NmrData);
        %set(hAxes,'ButtonDownFcn',@Axes_ButtonDownFcn)
    end
    function DrawExcludeline(~,~)
        NmrData=guidata(hMainFigure);
        hExcludeline=findobj(hAxes,'tag','excludeline');
        delete(hExcludeline)
        ypos=get(hAxes,'ylim');
        ypos=(ypos(2)-ypos(1))/3;
        ydata=ypos.*NmrData.exclude;
        xlimits=get(hAxes,'xlim');
        %hExcludeline=
        line(NmrData.Specscale,ydata,...
            'color','r','linewidth', 1.0,...
            'tag','excludeline');
        set(hAxes,'xlim',xlimits);
        
        guidata(hMainFigure,NmrData);
    end
    function Pivot_function(~,~)
        NmrData=guidata(hMainFigure);
        hPivot=findobj(hAxes,'tag','Pivot');
        delete(hPivot);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.pivotxdata=[xpos xpos];
        NmrData.pivotydata=get(hAxes,'ylim');
        NmrData.pivot=xpos;
        line(NmrData.pivotxdata,NmrData.pivotydata,...
            'color',[0 1 1],'linewidth', 1.0,...
            'tag','Pivot');
        drawnow
        guidata(hMainFigure,NmrData);
    end
    function pfgnmrdata=PreparePfgnmrdata()
        %Prepare the data for advanced processing
        zoom off
        pan off
        set(hMainFigure,'WindowButtonDownFcn','')
        %get the delta the spectrum
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        guidata(hMainFigure,NmrData);
        % Excludeline_function()
        NmrData=guidata(hMainFigure);
        pfgnmrdata.filename=NmrData.filename;
        pfgnmrdata.type=NmrData.type;
        pfgnmrdata.np=NmrData.np;
        pfgnmrdata.wp=NmrData.sw;
        pfgnmrdata.sp=NmrData.sp;
        pfgnmrdata.dosyconstant=NmrData.dosyconstant;
        pfgnmrdata.Gzlvl=NmrData.Gzlvl;
        pfgnmrdata.ngrad=NmrData.ngrad;
        pfgnmrdata.arraydim=NmrData.arraydim;
        pfgnmrdata.Ppmscale=NmrData.Specscale;
        if (isfield(NmrData,'NUC1'))
        pfgnmrdata.NUC1=NmrData.NUC1;
        end 
        if (isfield(NmrData,'d2'))
            pfgnmrdata.d2=NmrData.d2;
        end
        if (isfield(NmrData,'bt'))
            pfgnmrdata.bt=NmrData.bt;
        end
        if (isfield(NmrData,'bigtau'))
            pfgnmrdata.bigtau=NmrData.bigtau;
            pfgnmrdata.Gzlvl=NmrData.bigtau;
        end
        
        switch NmrData.disptype
            case 0
                pfgnmrdata.SPECTRA=abs(NmrData.SPECTRA);
            case 1
                pfgnmrdata.SPECTRA=real(NmrData.SPECTRA);
            otherwise
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Unknown display type. Using phase sensitive mode')
                pfgnmrdata.SPECTRA=real(NmrData.SPECTRA);
        end
        pfgnmrdata.normfac=max(max(pfgnmrdata.SPECTRA));
        pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA/max(max(pfgnmrdata.SPECTRA));
        if isfield(NmrData,'exclude')
            if get(hExcludeShow,'Value')
                for k=1:NmrData.arraydim
                    pfgnmrdata.SPECTRA(:,k)=...
                        pfgnmrdata.SPECTRA(:,k).*isnan(NmrData.exclude');
                end
            end
        end
        %MN 10Nov09 Add flipnr for score and locodosy
        pfgnmrdata.flipnr=NmrData.flipnr; % For running SCORE in 3D datasets
        
        if isfield(NmrData,'Gzlvl') && (pfgnmrdata.ngrad>1) && ~ischar(NmrData.Gzlvl)
            
            % Prune gradient levels if opted
            if get(hNgradUse,'Value')
                %check the validity of the prune array
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Pruning of gradient array will be done')
               % if length(NmrData.prune)>=length(NmrData.Gzlvl)
               if length(NmrData.prune)>=NmrData.ngrad
                    errstring=...
                        {'Too many gradient levels in prune',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                elseif NmrData.prune <1
                    errstring=...
                        {'Prune numbers cannot be zero or negative',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                elseif NmrData.prune>NmrData.ngrad
                    errstring=...
                        {'Prune numbers cannot exceed number of gradient levels',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                elseif length(unique(NmrData.prune))~=length(NmrData.prune)
                    errstring=...
                        {'Duplicates in prune vector',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                else
                    %do the pruning
                    % a=NmrData.prune
                    pfgnmrdata.SPECTRA(:,NmrData.prune)=[];
                    pfgnmrdata.Gzlvl(NmrData.prune)=[];
                    if isfield(pfgnmrdata,"bigtau")                  
                    pfgnmrdata.bigtau(NmrData.prune)=[];
                    end
                    pfgnmrdata.ngrad=pfgnmrdata.ngrad-length(NmrData.prune);
                end
            end
            
            
        elseif (isfield(NmrData,'d2'))
            pfgnmrdata.d2=NmrData.d2;
            if get(hNgradUse,'Value')
                %check the validity of the prune array
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Pruning of d2 array will be done')
                if length(NmrData.prune)>=length(NmrData.d2)
                    errstring=...
                        {'Too many values in prune',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                elseif NmrData.prune <1
                    errstring=...
                        {'Prune numbers cannot be zero or negative',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                elseif NmrData.prune>length(NmrData.d2)
                    errstring=...
                        {'Prune numbers cannot exceed number of array elements',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                elseif length(unique(NmrData.prune))~=length(NmrData.prune)
                    errstring=...
                        {'Duplicates in prune vector',...
                        'No pruning will be done'};
                    hErr=errordlg...
                        (errstring,'Prune error');
                    uiwait(hErr)
                else
                    %do the pruning
                    pfgnmrdata.SPECTRA(:,NmrData.prune)=[];
                    pfgnmrdata.d2(NmrData.prune)=[];
                    pfgnmrdata.arraydim=pfgnmrdata.arraydim-length(NmrData.prune);
                    pfgnmrdata.ngrad=pfgnmrdata.ngrad-length(NmrData.prune);
                    pfgnmrdata.flipnr=pfgnmrdata.flipnr-length(NmrData.prune);
                    if pfgnmrdata.flipnr<1
                        pfgnmrdata.flipnr=1;
                    end
                end
            end
            
        else
            guidata(hMainFigure,NmrData); WriteLogDispInfo('No pruning will be done')
        end
        guidata(hMainFigure,NmrData);
    end
    function pfgnmrdata=PreparePfgnmr3Ddata()
        %Prepare the data for advanced processing
        NmrData=guidata(hMainFigure);
        pfgnmrdata.filename=NmrData.filename;
        pfgnmrdata.np=NmrData.np;
        pfgnmrdata.wp=NmrData.sw;
        pfgnmrdata.sp=NmrData.sp;
        pfgnmrdata.dosyconstant=NmrData.dosyconstant;
        pfgnmrdata.Gzlvl=NmrData.Gzlvl;
        pfgnmrdata.ngrad=NmrData.ngrad;
        pfgnmrdata.narray2=NmrData.narray2;
        pfgnmrdata.Ppmscale=NmrData.Specscale;
        pfgnmrdata.SPECTRA=real(NmrData.SPECTRA);
        pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA/max(max(pfgnmrdata.SPECTRA));
       
        if isfield(NmrData,'exclude')
            if get(hExcludeShow,'Value')
                for k=1:NmrData.arraydim
                    pfgnmrdata.SPECTRA(:,k)=...
                        pfgnmrdata.SPECTRA(:,k).*isnan(NmrData.exclude');
                end
            end
        end
        unshaped=pfgnmrdata.SPECTRA;
        pfgnmrdata.SPECTRA=reshape(pfgnmrdata.SPECTRA,NmrData.fn,NmrData.ngrad,NmrData.narray2);
        
        %NUS (have to be tested)
        if ~isempty(NmrData.nus)
            disp('There is a nuslist. I will sort the data accordingly to it')
            NUSLIST=NmrData.nus;
            NUSLIST=NUSLIST+1;
            if size(NUSLIST,1)~=(NmrData.ngrad*NmrData.narray2)
                disp('This is not 100% NUS. I will keep using like this')
            else
                temp_data=zeros(size(pfgnmrdata.SPECTRA));
                for i=1:size(NUSLIST,1)
                    temp_data(:,NUSLIST(i,1),NUSLIST(i,2))=unshaped(:,i);
                end
                pfgnmrdata.SPECTRA=temp_data;
            end
        end
        
        % Prune gradient levels if opted
        if get(hNgradUse,'Value')
            %check the validity of the prune array
            if length(NmrData.prune)>=length(NmrData.Gzlvl)
                errstring=...
                    {'Too many gradient levels in prune',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.prune <1
                errstring=...
                    {'Prune numbers cannot be zero or negative',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.prune>NmrData.ngrad
                errstring=...
                    {'Prune numbers cannot exceed number of gradient levels',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif length(unique(NmrData.prune))~=length(NmrData.prune)
                errstring=...
                    {'Duplicates in prune vector',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            else
                %do the pruning
                pfgnmrdata.SPECTRA(:,NmrData.prune,:)=[];
                pfgnmrdata.Gzlvl(NmrData.prune)=[];
                pfgnmrdata.ngrad=pfgnmrdata.ngrad-length(NmrData.prune);
            end
        end
        
        % Prune array 2 levels if opted
        if get(hArray2Use,'Value')
            %check the validity of the prune array
            if length(NmrData.pruneArray2)>=NmrData.narray2
                errstring=...
                    {'Too many array levels in prune',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.pruneArray2 <1
                errstring=...
                    {'Prune numbers cannot be zero or negative',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif length(unique(NmrData.pruneArray2))~=length(NmrData.pruneArray2)
                errstring=...
                    {'Duplicates in prune vector',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            else
                %do the pruning
                pfgnmrdata.SPECTRA(:,:,NmrData.pruneArray2)=[];
                pfgnmrdata.narray2=pfgnmrdata.narray2-length(NmrData.pruneArray2);
            end
        end
        
        
        guidata(hMainFigure,NmrData);
    end
    function pfgnmrdata=PreparePfgnmr4Ddata()
        %Prepare the data for advanced processing
        NmrData=guidata(hMainFigure);
        pfgnmrdata.filename=NmrData.filename;
        pfgnmrdata.np=NmrData.np;
        pfgnmrdata.wp=NmrData.sw;
        pfgnmrdata.sp=NmrData.sp;
        pfgnmrdata.dosyconstant=NmrData.dosyconstant;
        pfgnmrdata.Gzlvl=NmrData.Gzlvl;
        pfgnmrdata.ngrad=NmrData.ngrad;
        pfgnmrdata.ngrad2=NmrData.ngrad2;
        pfgnmrdata.narray2=NmrData.narray2;
        pfgnmrdata.narray3=NmrData.narray3;
        pfgnmrdata.Ppmscale=NmrData.Specscale;
        pfgnmrdata.SPECTRA=real(NmrData.SPECTRA);
        pfgnmrdata.SPECTRA=pfgnmrdata.SPECTRA/max(max(pfgnmrdata.SPECTRA));
        if isfield(NmrData,'exclude')
            if get(hExcludeShow,'Value')
                for k=1:NmrData.arraydim
                    pfgnmrdata.SPECTRA(:,k)=...
                        pfgnmrdata.SPECTRA(:,k).*isnan(NmrData.exclude');
                end
            end
        end
        unshaped=pfgnmrdata.SPECTRA;
        pfgnmrdata.SPECTRA=reshape(pfgnmrdata.SPECTRA,NmrData.fn,NmrData.ngrad,NmrData.narray2,NmrData.narray3);
        
        %NUS (have to be tested)
        if ~isempty(NmrData.nus)
            disp('There is a nuslist. I will sort the data accordingly to it')
            NUSLIST=NmrData.nus;
            NUSLIST=NUSLIST+1;
            if size(NUSLIST,1)~=(NmrData.ngrad*NmrData.narray2*NmrData.narray3)
                disp('This is not 100% NUS. I will keep using like this')
            else
                temp_data=zeros(size(pfgnmrdata.SPECTRA));
                for i=1:size(NUSLIST,1)
                    temp_data(:,NUSLIST(i,1),NUSLIST(i,2),NUSLIST(i,3))=unshaped(:,i);
                end
                pfgnmrdata.SPECTRA=temp_data;
            end
        end

        % Prune gradient levels if opted
        if get(hNgradUse,'Value')
            %check the validity of the prune array
            if length(NmrData.prune)>=length(NmrData.Gzlvl)
                errstring=...
                    {'Too many gradient levels in prune',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.prune <1
                errstring=...
                    {'Prune numbers cannot be zero or negative',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.prune>NmrData.ngrad
                errstring=...
                    {'Prune numbers cannot exceed number of gradient levels',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif length(unique(NmrData.prune))~=length(NmrData.prune)
                errstring=...
                    {'Duplicates in prune vector',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            else
                %do the pruning
                pfgnmrdata.SPECTRA(:,NmrData.prune,:,:,:)=[];
                pfgnmrdata.Gzlvl(NmrData.prune)=[];
                pfgnmrdata.ngrad=pfgnmrdata.ngrad-length(NmrData.prune);
                pfgnmrdata.ngrad2=pfgnmrdata.ngrad2-(length(NmrData.pruneArray2)*NmrData.narray2);
            end
        end
        
        % Prune array 2 levels if opted
        if get(hArray2Use,'Value')
            %check the validity of the prune array
            if length(NmrData.pruneArray2)>=NmrData.narray2
                errstring=...
                    {'Too many array levels in prune',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.pruneArray2 <1
                errstring=...
                    {'Prune numbers cannot be zero or negative',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif length(unique(NmrData.pruneArray2))~=length(NmrData.pruneArray2)
                errstring=...
                    {'Duplicates in prune vector',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            else
                %do the pruning
                pfgnmrdata.SPECTRA(:,:,NmrData.pruneArray2,:)=[];
                pfgnmrdata.narray2=pfgnmrdata.narray2-length(NmrData.pruneArray2);
                pfgnmrdata.ngrad2=pfgnmrdata.ngrad2-(length(NmrData.pruneArray2)*pfgnmrdata.ngrad);
            end
        end
        
        % Prune array 3 levels if opted
        if get(hArray3Use,'Value')
            %check the validity of the prune array
            if length(NmrData.pruneArray3)>=NmrData.narray3
                errstring=...
                    {'Too many array levels in prune',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif NmrData.pruneArray3 <1
                errstring=...
                    {'Prune numbers cannot be zero or negative',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            elseif length(unique(NmrData.pruneArray3))~=length(NmrData.pruneArray3)
                errstring=...
                    {'Duplicates in prune vector',...
                    'No pruning will be done'};
                hErr=errordlg...
                    (errstring,'Prune error');
                uiwait(hErr)
            else
                %do the pruning
                pfgnmrdata.SPECTRA(:,:,:,NmrData.pruneArray3)=[];
                pfgnmrdata.narray3=pfgnmrdata.narray3-length(NmrData.pruneArray3);
            end
        end
        
        guidata(hMainFigure,NmrData);
    end
    function PlotSpectrum()
        NmrData=guidata(hMainFigure);
        ThPlot=0;
        if  get(hThreshButton,'Value') == 1
            %Check if threshold shoudl be plotted
            hThresh=findobj(hAxes,'tag','threshold');
            if isempty(hThresh)
                %do nothing
            else
                ThPlot=1;
            end
        end
        
        %set(gcf,'CurrentAxes',hAxes)
        if NmrData.plotsep==1
            MainFigure=figure('Color',[0.9 0.9 0.9],...
                'NumberTitle','Off',...
                'MenuBar','none',...
                'Toolbar','Figure',...
                'Name','Spectrum plot');
            
            %Clean up the Toolbar, removing things we don't need
            tmp = findall(MainFigure,'ToolTipString','New Figure');
            set(tmp,'Visible','Off')
%             tmp = findall(MainFigure,'ToolTipString','Edit Plot');
%             set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Open File');
            set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Link Plot');
            set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Insert Legend');
            set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Rotate 3D');
            set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Brush/Select Data');
            set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Hide Plot Tools');
            set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Data Cursor');
            set(tmp,'Visible','Off')
            tmp = findall(MainFigure,'ToolTipString','Insert Colorbar');
            set(tmp,'Visible','Off')
        end
        if NmrData.plottype==0
            %FID
            set(hBaselineShow,'Value',0)
            set(hExcludeShow,'Value',0)
            % set(hThresholdButton,'Value',get(hThresholdButton,'Min'))
            set(hPivotCheck,'Value',0)
            Timescale=GetTimescale();
            Winfunc=GetWinfunc('PlotSpectrum');
            orgfid = NmrData.FID;
            
            %leftshift the fid
            if NmrData.lrfid>0
                %left shift the fid
                for k=1:NmrData.arraydim
                    NmrData.FID(:,k)= circshift(NmrData.FID(:,k),-NmrData.lrfid);
                end
            end
            
            %phase or abs
            if NmrData.disptype==0
                plotfid=abs(NmrData.FID(:,NmrData.flipnr));
            else
                plotfid=real(NmrData.FID(:,NmrData.flipnr));
            end
            if NmrData.plotsep==1
                if NmrData.plotpub==1
                   % PlotCol='Black';
                end
                %determine what to plot
                if  get(hPlotFID,'Value') && get(hPlotWinfunc,'Value') && get(hPlotFIDWinfunc,'Value')
                    %FID + new FID + winfunc
                    %hPlot= 
                    plot(Timescale,plotfid,...
                        Timescale,plotfid.*Winfunc/(max(Winfunc)),'red',...
                        Timescale,0.9*max(NmrData.ylim_fid)*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                    
                elseif get(hPlotFID,'Value') && get(hPlotWinfunc,'Value')
                    %FID + winfunc
                    %hPlot= 
                    plot(Timescale,plotfid,...
                        Timescale,0.9*max(NmrData.ylim_fid)*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                    
                elseif  get(hPlotFID,'Value') && get(hPlotFIDWinfunc,'Value')
                    %FID + new FID
                    %hPlot= 
                    plot(Timescale,plotfid, Timescale,...
                        plotfid.*Winfunc/(max(Winfunc)),'red');
                    
                elseif get(hPlotWinfunc,'Value') && get(hPlotFIDWinfunc,'Value')
                    %new FID + winfunc
                    %hPlot= 
                    plot(Timescale,...
                        plotfid.*Winfunc/(max(Winfunc)),'red',...
                        Timescale,0.9*max(NmrData.ylim_fid)*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                    
                elseif get(hPlotFID,'Value')
                    %FID
                    %hPlot= 
                    plot(Timescale,plotfid);
                    
                elseif get(hPlotFIDWinfunc,'Value')
                    % new FID
                    %hPlot= 
                    plot(Timescale,...
                        plotfid.*Winfunc/(max(Winfunc)),'red');
                    
                elseif get(hPlotWinfunc,'Value')
                    % winfunc
                    %hPlot= 
                    plot(Timescale,0.9*max(NmrData.ylim_fid)*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                else
                    % unknown
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown plot combination')
                end
                
                xlabel(gca,'{\fontsize{16}Time  /s}');
                ylim(NmrData.ylim_fid);
                xlim(NmrData.xlim_fid);
            else
                %determine what to plot
                if  get(hPlotFID,'Value') && get(hPlotWinfunc,'Value') && get(hPlotFIDWinfunc,'Value')
                    %FID + new FID + winfunc
                    %hPlot= 
                    plot(Timescale,plotfid, Timescale,...
                        plotfid.*Winfunc/(max(Winfunc)),'red',...
                        Timescale,0.9*max(ylim())*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                    
                elseif get(hPlotFID,'Value') && get(hPlotWinfunc,'Value')
                    %FID + winfunc
                    %hPlot= 
                    plot(Timescale,plotfid,...
                        Timescale,0.9*max(ylim())*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                    
                elseif  get(hPlotFID,'Value') && get(hPlotFIDWinfunc,'Value')
                    %FID + new FID
                    %hPlot= 
                    plot(Timescale,plotfid, Timescale,...
                        plotfid.*Winfunc/(max(Winfunc)),'red');
                    
                elseif get(hPlotWinfunc,'Value') && get(hPlotFIDWinfunc,'Value')
                    %new FID + winfunc
                    %hPlot= 
                    plot(Timescale,...
                        plotfid.*Winfunc/(max(Winfunc)),'red',...
                        Timescale,0.9*max(ylim())*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                    
                elseif get(hPlotFID,'Value')
                    plot(Timescale,plotfid);
                    
                elseif get(hPlotFIDWinfunc,'Value')
                    % new FID
                    %hPlot= 
                    plot(Timescale,...
                        plotfid.*Winfunc/(max(Winfunc)),'red');
                    
                elseif get(hPlotWinfunc,'Value')
                    % winfunc
                    %hPlot= 
                    plot(Timescale,0.9*max(ylim())*Winfunc/(max(Winfunc)),'green','Linewidth',0.1);
                else
                    % unknown
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('unknown plot combination')
                end
                xlabel(gca,'{\fontsize{16}Time  /s}')
                xlim(NmrData.xlim_fid);
                ylim(NmrData.ylim_fid);
            end
            NmrData.FID = orgfid;
            if NmrData.plotsep==1
                if NmrData.plotpub==1
                    %set(hPlot,'Color','Black');
                    %PlotCol='Blue';
                    set(gca,'Box','Off','TickDir','Out','YTick',[],'Ycolor','White');
                    xlabel(gca,'{\fontsize{16}Time  /s}');
                    set(gca,'FontName','Arial','FontWeight','Normal','LineWidth',1, 'FontSize',12);
                    
                end
                
            end
        elseif NmrData.plottype==1
            %Spectrum
            switch NmrData.shiftunits
                case 'ppm'
                    NmrData.Specscale=...
                        linspace(NmrData.sp,(NmrData.sw+NmrData.sp),NmrData.fn);
                case 'Hz'
                    NmrData.Specscale=...
                        linspace(NmrData.sp.*NmrData.sfrq,(NmrData.sw+NmrData.sp).*NmrData.sfrq,NmrData.fn);
                case 'spinach'
                    
                 NmrData.Specscale=linspace(-NmrData.sw/2,...
                 NmrData.sw/2,...
                 NmrData.fn)+NmrData.sfo1;
                 NmrData.Specscale=-1e6*NmrData.Specscale/NmrData.sfrq;
                    
                otherwise
                    error('illegal choice')
            end
            if NmrData.plotsep==1
                %Separate plot
                test_marker=0;
                test_spec=1;
                if NmrData.disptype==0
                    if test_spec==1
                        hPlot=plot(NmrData.Specscale,abs(NmrData.SPECTRA(:,NmrData.flipnr)));
                    end
                    if test_marker==1
                        hold on
                        hPlot=plot(NmrData.Specscale,abs(NmrData.SPECTRA(:,NmrData.flipnr)),'+','MarkerSize',12,'LineWidth',2,'Color','red');
                        hold off
                    end
                else
                    if test_spec==1
                        hPlot=plot(NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)));
                    end
                    if test_marker==1
                        hold on
                        hPlot=plot(NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)),'+','MarkerSize',12,'LineWidth',2,'Color','red');
                        hold off
                    end
                end
                xlabel('\bf Chemical shift ');
                xlim(NmrData.xlim_spec)
                ylim(NmrData.ylim_spec)
                set(gca,'Xdir','Reverse')
            else
                if NmrData.disptype==0
                    hPlot=plot(hAxes,NmrData.Specscale,abs(NmrData.SPECTRA(:,NmrData.flipnr)));
                    xlabel(hAxes,'\bf Chemical shift ');
                else

                    hPlot=plot(hAxes,NmrData.Specscale,real(NmrData.SPECTRA(:,NmrData.flipnr)));
                    xlabel(hAxes,'\bf Chemical shift ');
                end
            end
            set(hAxes,'Xdir','Reverse');
            xlim(NmrData.xlim_spec)
            ylim(NmrData.ylim_spec)
            
            if ThPlot==1
                %plot Thresholdline
                line(NmrData.thresxdata,NmrData.thresydata,...
                    'color','Black','linewidth', 1.0,...
                    'tag','threshold');
            end
            drawnow
            if get(hReferenceCheck,'Value')
                line(NmrData.referencexdata,NmrData.referenceydata,...
                    'color','magenta','linewidth', 1.0,...
                    'tag','Reference');
                drawnow
            else
                hReference=findobj(hAxes,'tag','Reference');
                delete(hReference)
            end
            if get(hRDshowCheck,'Value')
                NmrData.RDrcentreydata=get(hAxes,'ylim');
                NmrData.RDcentrexdata=[NmrData.RDcentre NmrData.RDcentre];
                line(NmrData.RDcentrexdata,NmrData.RDcentreydata,...
                    'color','black','linewidth', 1.0,...
                    'tag','RDcentre');
            else
                hRDcentre=findobj(hAxes,'tag','RDcentre');
                delete(hRDcentre)
            end
            if get(hRDshowLRCheck,'Value')
                NmrData.RDleftydata=get(hAxes,'ylim');
                NmrData.RDrightydata=get(hAxes,'ylim');
                NmrData.RDleftxdata=[NmrData.RDleft NmrData.RDleft];
                NmrData.RDrightxdata=[NmrData.RDright NmrData.RDright];
                line(NmrData.RDleftxdata,NmrData.RDleftydata,...
                    'color','red','linewidth', 1.0,...
                    'tag','RDleft');
                line(NmrData.RDrightxdata,NmrData.RDrightydata,...
                    'color','green','linewidth', 1.0,...
                    'tag','RDright');
            elseif get(hDeltashowLRCheck,'Value')
                NmrData.Deltaleftydata=get(hAxes,'ylim');
                NmrData.Deltarightydata=get(hAxes,'ylim');
                NmrData.Deltaleftxdata=[NmrData.Deltaleft NmrData.Deltaleft];
                NmrData.Deltarightxdata=[NmrData.Deltaright NmrData.Deltaright];
                line(NmrData.Deltaleftxdata,NmrData.Deltaleftydata,...
                    'color','red','linewidth', 1.0,...
                    'tag','Deltaleft');
                line(NmrData.Deltarightxdata,NmrData.Deltarightydata,...
                    'color','green','linewidth', 1.0,...
                    'tag','Deltaright');
            else
                hRDright=findobj(hAxes,'tag','RDright');
                hRDleft=findobj(hAxes,'tag','RDleft');
                delete(hRDleft)
                delete(hRDright)
            end
            if get(hIntegralsShow,'Value')
                DrawIntLine();
            end
            if get(hSNRShow,'Value')
                DrawNoiseLine();
            end
            if get(hExcludeShow,'Value')
                DrawExcludeline();
            end
            if get(hBaselineShow,'Value')
                DrawBaseline();
            end
            if get(hLRWindowsShow,'Value')
                DrawIncludeline();
            end
            if get(hPivotCheck,'Value')
                %Pivot_function();
            end
            if get(hPivotCheck,'Value')
                line(NmrData.pivotxdata,NmrData.pivotydata,...
                    'color',[0 1 1],'linewidth', 1.0,...
                    'tag','Pivot');
                drawnow
            else
                hPivot=findobj(hAxes,'tag','Pivot');
                delete(hPivot)
            end
            xlim(NmrData.xlim_spec)
            ylim(NmrData.ylim_spec)
            if isvalid(hPlot)
                set(hPlot,'HitTest','off')
            end
            if NmrData.plotsep==1
                if NmrData.plotpub==1
                    set(hPlot,'Color','Black');
                    set(gca,'Box','Off','TickDir','Out','YTick',[],'Ycolor','White');
                    xlabel(gca,'{\fontsize{16}\delta  /ppm}');
                    set(gca,'FontName','Arial','FontWeight','Normal','LineWidth',1, 'FontSize',12);
                    
                end
                
            end
            guidata(hMainFigure,NmrData);
        else
            error('Undefined plot type')
        end
        
        NmrData.plotsep=0;
        guidata(hMainFigure,NmrData);
        
    end
    function PhaseSpectrum(lpChange,rpChange,AbsPhase)
        %phase the spectrum depending on the change in lp and rp; a change
        %in lp also makes a change in rp depending on the pivot position
       % disp('Phase')
       % NmrData=guidata(hMainFigure)
        if NmrData.plottype==1
            NmrData.xlim_spec=xlim(hAxes);
            NmrData.ylim_spec=ylim(hAxes);
        end
        if isnan(lpChange)
            lpChange=0;
        end
        if isnan(rpChange)
            rpChange=0;
        end
        Rc=1i*(pi/180);
        switch get(hScopeGroup,'SelectedObject')
            case hRadioScopeGlobal
                lpCorr= linspace(0,1,NmrData.fn)*lpChange;
                lpCorrDSP= linspace(0,1,NmrData.fn)*0;
                if AbsPhase==1
  
                    %Apply absolute values - no change (after FT or loading in a
                    %new experiment)
                     %adding the DSP phase correction
                    lpCorrDSP= linspace(0,1,NmrData.fn)*NmrData.dspPhase;
                     
                elseif AbsPhase==20
                    %This means phasing individual spectra from GroupScope_Callback
                    %function. Workaround to speed it up (hard to keep
                    %elegant code when bolting on)
%                     disp('Hi')
                    PhaseCorrTot=zeros(NmrData.fn,NmrData.arraydim);
                    lpCorrDSP= linspace(0,1,NmrData.fn)*NmrData.dspPhase;
                    for k=1:NmrData.arraydim
                        lpCorr= linspace(0,1,NmrData.fn)*(NmrData.lp-NmrData.lpInd(k));
                        PhaseCorrTot(:,k)=(exp(Rc*((NmrData.rp-NmrData.rpInd(k)) + lpCorr)))';
                    end
                   NmrData.SPECTRA=NmrData.SPECTRA.*PhaseCorrTot;
                   %lpCorrDSP = -linspace(0,1,NmrData.fn)*NmrData.dspPhase;

                else
                    if AbsPhase==2 %autophase or manual edit
                        %never mind the pivot
                    else
                        rpCorrlp=- lpCorr(round(NmrData.fn*...
                            (NmrData.pivot-NmrData.sp)/NmrData.sw));
                        rpChange=rpChange+rpCorrlp;
                    end
                    NmrData.lp=NmrData.lp+lpChange;
                    NmrData.rp=NmrData.rp+rpChange;
                end
                phaseCorr=...
                    (exp(Rc*(rpChange + lpCorr + lpCorrDSP)))';
                %phasing all spectra
                     if AbsPhase==20
                    %don't phase current spectrum twice
                     else
                        
                NmrData.SPECTRA=NmrData.SPECTRA.*repmat...
                    (phaseCorr,1,(NmrData.arraydim));
                     end
                set(hEditPh1,'string',num2str(NmrData.lp,4))
                set(hEditPh0,'string',num2str(NmrData.rp,4))
                set(hSliderPh0,'value',NmrData.rp);
                set(hSliderPh1,'value',NmrData.lp);
            case hRadioScopeIndividual
                lpCorr= linspace(0,1,NmrData.fn)*lpChange;
                lpCorrDSP= linspace(0,1,NmrData.fn)*0;
                if AbsPhase==1
                    %Apply absolute values - no change (after FT or loading in a
                    %new experiment)
                    
                    lpCorrDSP= linspace(0,1,NmrData.fn)*NmrData.dspPhase;
                elseif AbsPhase==20
                        %This means phasing individual spectra from GroupScope_Callback
                        %function. Workaround to speed it up (hard to keep
                        %elegant code when bolting on)
                        PhaseCorrTot=zeros(NmrData.fn,NmrData.arraydim);
                        for k=1:NmrData.arraydim
                            lpCorr= linspace(0,1,NmrData.fn)*(NmrData.lpInd(k)-NmrData.lp);
                            PhaseCorrTot(:,k)=(exp(Rc*((NmrData.rpInd(k)-NmrData.rp)+ lpCorr)))';
                        end
                        NmrData.SPECTRA=NmrData.SPECTRA.*PhaseCorrTot;
                elseif AbsPhase==10
                        %This means phasing individual spectra from FT
                        %function. Workaround to speed it up (hard to keep
                        %elegant code when bolting on)
                        PhaseCorrTot=zeros(NmrData.fn,NmrData.arraydim);
                        lpCorrDSP= linspace(0,1,NmrData.fn)*NmrData.dspPhase;
                        for k=1:NmrData.arraydim
                            lpCorr= linspace(0,1,NmrData.fn)*NmrData.lpInd(k);
                            PhaseCorrTot(:,k)=(exp(Rc*(NmrData.rpInd(k) + lpCorr + lpCorrDSP)))';
                        end
                        NmrData.SPECTRA=NmrData.SPECTRA.*PhaseCorrTot;       
                else
                    if AbsPhase==2 %autophase or manual edit
                        %never mind the pivot
                    else
                        rpCorrlp= - lpCorr(round(NmrData.fn*...
                            (NmrData.pivot-NmrData.sp)/NmrData.sw));
                        rpChange=rpChange+rpCorrlp;
                    end
                    NmrData.lpInd(NmrData.flipnr)=...
                        NmrData.lpInd(NmrData.flipnr)+lpChange;
                    NmrData.rpInd(NmrData.flipnr)=...
                        NmrData.rpInd(NmrData.flipnr)+rpChange;
                end
                phaseCorr=...
                    (exp(Rc*(rpChange + lpCorr+ lpCorrDSP)))';
                %phasing just the displayed spectrum
                if AbsPhase==10 || AbsPhase==20
                    %don't phase current spectrum twice
                else
                    NmrData.SPECTRA(:,NmrData.flipnr)=...
                        NmrData.SPECTRA(:,NmrData.flipnr).*phaseCorr;
                end
                set(hEditPh1,'string',num2str(NmrData.lpInd(NmrData.flipnr),4))
                set(hEditPh0,'string',num2str(NmrData.rpInd(NmrData.flipnr),4))
                set(hSliderPh0,'value',NmrData.rpInd(NmrData.flipnr));
                set(hSliderPh1,'value',NmrData.lpInd(NmrData.flipnr));
            otherwise
                error('illegal choice')
        end
        guidata(hMainFigure,NmrData);
    end
    function Timescale=GetTimescale()
        NmrData=guidata(hMainFigure);
        %Timescale=linspace(0,NmrData.at*(NmrData.fn/NmrData.np),NmrData.fn);
        Timescale=linspace(0,NmrData.at,NmrData.np);
        guidata(hMainFigure,NmrData);
    end
    function Winfunc=GetWinfunc(Caller)
        NmrData=guidata(hMainFigure);
        if  strcmp(Caller,'FTButton_Callback')
            Timescale=linspace(0,NmrData.at*(NmrData.fn/NmrData.np),NmrData.fn);
        else
            Timescale=GetTimescale();
        end
        if get(hCheckLb,'Value')
            Lbfunc=exp(-Timescale'*pi*NmrData.lb);
        else
            Lbfunc=Timescale'*0+1;
        end
        if get(hCheckGw,'Value')
            gf=2*sqrt(log(2))/(pi*NmrData.gw);
            Gwfunc=exp(-(Timescale'/gf).^2);
        else
            Gwfunc=Timescale'*0+1;
        end
        if  strcmp(Caller,'FTButton_Callback')
            Winfunc=Gwfunc.*Lbfunc;
        elseif    strcmp(Caller,'PlotSpectrum')
            Winfunc=0.9*Gwfunc.*Lbfunc.*max(real(NmrData.FID(:,NmrData.flipnr)))/max(Gwfunc.*Lbfunc);
        else
            error('unknown caller for Winfunc');
        end
        guidata(hMainFigure,NmrData);
    end
    function Initiate_NmrData()
        NmrData=guidata(hMainFigure);
        tmp=NmrData.version;
        tmp2=NmrData.local;
        clear NmrData
        NmrData.alpha=0.2;
        NmrData.at=[];
        NmrData.arraydim=[];
        NmrData.array2nr=[];
        NmrData.array3nr=[];
        NmrData.BACKUPT1=[];
        NmrData.baselinecorr=[];
        NmrData.baselinepoints=[];
        NmrData.BasePoints=[];
        NmrData.d2=[];
        NmrData.dc=0;
        NmrData.dcspec=1;
        NmrData.decradata=[];
        NmrData.DELTA=[];
        NmrData.DELTAOriginal=[];
        NmrData.DELTAprime=[];
        NmrData.delta=[];
        NmrData.deltaOriginal=[];
        NmrData.disptype=1; %Determines if phase sensitive or absolute value plotting is used
        NmrData.DOSYdiffrange=[];
        NmrData.dosyconstant=[];
        NmrData.dosyconstantOriginal=[];
        NmrData.dosydata=[];
        NmrData.DOSYopts=[];
        NmrData.dspPhase=0;
        NmrData.exclude=[];
        NmrData.excludelinepoints=[];
        NmrData.ExcludePoints=[];
        NmrData.FID=[];
        NmrData.FitType=0;
        NmrData.filename='';
        NmrData.flipnr=[];
        NmrData.fn=0;
        NmrData.fpmult=0.5;
        NmrData.fshift=[];
        NmrData.gamma=[];
        NmrData.gammaOriginal=[];
        NmrData.gcal=[];
        NmrData.gcal_orig=[];
        NmrData.gf=0;
        NmrData.gradnr=[];
        NmrData.gw=0;
        NmrData.Gzlvl=[];
        NmrData.Integral=[];
        NmrData.integral_peaks=[];
        NmrData.IntPoint=[];
        NmrData.IntPointIndex=[];
        NmrData.IntPointSort=[];
        NmrData.Intscale=1;
        NmrData.lb=[];
        NmrData.local=tmp2;
        NmrData.lp=[];
        NmrData.lpInd=[];
        NmrData.locodosydata=[];
        NmrData.locodosyopts=[];
        NmrData.lrfid=0;
        NmrData.lrfidOrg=[];
        NmrData.lsspec=0;
        NmrData.linshift=1;
        NmrData.narray2=[];
        NmrData.ncomp=[];
        %NmrData.nfid=[];
        NmrData.ngrad=[];
        NmrData.ngrad2=[];
        NmrData.np=[];
        NmrData.nug=[1 0 0 0]; %default as pure exponential
        NmrData.nus=[];
        NmrData.gpnam=[];
        NmrData.nwin=[];
        NmrData.order=[];
        NmrData.panelpos=[0 0];
        NmrData.parafacFac=[];
        NmrData.pfgnmrdata=[];
        NmrData.pivot=[];
        NmrData.pivotxdata=[];
        NmrData.pivotydata=[];
        NmrData.plottype=1;
        NmrData.plotsep=0;
        NmrData.probename='undefined';
        NmrData.prune=[];
        NmrData.pruneArray2=[];
        NmrData.pruneArray3=[];
        NmrData.RDcentrexdata=[0 0];
        NmrData.RDcentreydata=[0 0];
        NmrData.RDcentre=0;
        NmrData.RDleftxdata=0;
        NmrData.RDleftydata=0;
        NmrData.RDleft=0;
        NmrData.RDrightxdata=[0 0];
        NmrData.RDrightydata=[0 0];
        NmrData.RDright=0;
        NmrData.reference=[];
        NmrData.reference_list=[];
        NmrData.referencexdata=[];
        NmrData.referenceydata=[];
        NmrData.RRTopts=[];
        %NmrData.procpar=[];
        NmrData.region=[];
        NmrData.rp=[];
        NmrData.rpInd=[];
        NmrData.SaveState=[];
        NmrData.scoredata=[];
        NmrData.SCOREopts=[];
        NmrData.sfrq=[];
        NmrData.shiftunits='ppm';
        NmrData.sp=[];
        NmrData.Specscale=[];
        NmrData.SPECTRA=[];
        NmrData.sw=[];
        NmrData.sw1=[];
        NmrData.tau=0;
        NmrData.tauOriginal=[];
        NmrData.th=0.0;
        NmrData.thShow=0;
        NmrData.thresxdata=0;
        NmrData.thresydata=0;
        NmrData.Timescale=[];
        NmrData.type='';
        NmrData.version=tmp;
        NmrData.xlim=[];
        NmrData.xlim_fid=[];
        NmrData.ylim=[];
        NmrData.ylim_fid=[];
        NmrData.flipnr=str2double(get(hEditFlip,'String'));
        NmrData.fn=NmrData.np;
        NmrData.gw=str2double(get(hEditGw,'String'));
        NmrData.lb=str2double(get(hEditLb,'String'));
        NmrData.density=1.050;
        NmrData.packing=0.64;
        NmrData.temperature=298.15; %GDP 31/01/2018 for SEGWE
        NmrData.answer=30.80; %GDP 31/01/2018 for SEGWE
        NmrData.argument = 100; %GDP 31/01/2018 for SEGWE
        NmrData.viscositydisplay=0.0003258*1000; %GDP 31/01/2018 for SEGWE
        NmrData.MWs=64.12;
        NmrData.peff=627;
        %AC
        NmrData.include=[];
        NmrData.includelinepoints=[];
        NmrData.IncludePoints=[];
        NmrData.startORend=0;
        NmrData.winstart=[];
        NmrData.winend=[];
        NmrData.numcomp=[];
        NmrData.concat1dspectra=[];
        NmrData.sderrmultiplier=[];
        NmrData.LRRegionData=[];
        NmrData.issynthetic=0;
        %AC
        %nD specific
        NmrData.xlim_1D=[];
        NmrData.ylim_1D=[];
        NmrData.xlim_2D=[];
        NmrData.ylim_2D=[];
        set(hPushCopyGtoI,'Enable','On')
        set(hPushAutoAll,'Enable','Off')
        set(hPushAuto0All,'Enable','Off')
        guidata(hMainFigure,NmrData);
    end
    function Setup_NmrData()
        NmrData=guidata(hMainFigure);
        set(hMainFigure,'CurrentAxes',hAxes)

        if NmrData.issynthetic==1       %AC
            slashindex=1;
        elseif isunix()==1
            slashindex=find(NmrData.filename=='/');
        else
            slashindex=find(NmrData.filename=='\');
        end

        % slashindex
        set(hMainFigure,'Name',...
            [NmrData.version ' ...' NmrData.filename(slashindex(end):end)])
        set(hScopeGroup,'SelectedObject',hRadioScopeGlobal)
        set(hEditOrder,'string',2);
        NmrData.lpOrg=NmrData.lp;
        NmrData.rpOrg=NmrData.rp;
        NmrData.order=round(str2double(get(hEditOrder,'string')));
        NmrData.plottype=1;
        NmrData.flipnr=1;
        NmrData.dc=0;
        NmrData.fpmult=0.5;
        NmrData.fn=NmrData.np;
        NmrData.thresydata=0;
        NmrData.thresxdata=0;
        NmrData.Timescale=linspace...
            (0,NmrData.at*(NmrData.fn/NmrData.np),NmrData.fn);
        NmrData.exclude=ones(1,NmrData.fn);
        NmrData.ExcludePoints=[];
        NmrData.excludelinepoints=[];
        NmrData.IntPoint=[];
        NmrData.Integral=ones(1,NmrData.fn);
        NmrData.region=ones(1,NmrData.fn);
        NmrData.baselinepoints=[];
        NmrData.BasePoints=[];
        NmrData.baselinecorr=zeros(NmrData.fn,NmrData.arraydim);
        NmrData.xlim_fid=[0 NmrData.at];
        NmrData.ylim_fid=...
            [min(real(NmrData.FID(:,1))) max(real(NmrData.FID(:,1)))];
        set(hEditFn,'string',num2str(NmrData.fn));
        set(hEditNp,'string',num2str(NmrData.np));
        set(hExcludeShow,'Value',0)
        NmrData.Specscale=...
            linspace(NmrData.sp,(NmrData.sw+NmrData.sp),NmrData.fn);
        NmrData.pivot=NmrData.Specscale(round(NmrData.np/2));
        set(hSliderPh0,'value',NmrData.rp);
        set(hEditPh0,'string',num2str(NmrData.rp,4));
        set(hSliderPh1,'value',NmrData.lp);
        set(hEditPh0,'string',num2str(NmrData.lp,4));
        NmrData.SPECTRA=flipud((fftshift(fft(NmrData.FID,NmrData.fn),1)));
%         NmrData.SPECTRA=flipud(((fft(NmrData.FID,NmrData.fn))));

        % plot(real(NmrData.SPECTRA(:,1)))
        guidata(hMainFigure,NmrData);
        PhaseSpectrum(NmrData.lp,NmrData.rp,1);
        % plot(real(NmrData.SPECTRA(:,1)))

        % CHECK with FFT
        IntFact=round(max(abs(NmrData.SPECTRA(:,1)))/1e5);
        set(hEditOffsetMult,'String',num2str(IntFact*10));
        set(hEditTiltMult,'String',num2str(IntFact));
        if isfield(NmrData,'lpInd')
            if length(NmrData.lpInd)==NmrData.arraydim
                %accept values
            else
                NmrData.lpInd=ones(1,NmrData.arraydim).*NmrData.lp;
            end
        else
            NmrData.lpInd=ones(1,NmrData.arraydim).*NmrData.lp;
            
        end
        if isfield(NmrData,'rpInd')
            if length(NmrData.rpInd)==NmrData.arraydim
                %accept values
            else
                NmrData.rpInd=ones(1,NmrData.arraydim).*NmrData.rp;
            end
        else
            NmrData.rpInd=ones(1,NmrData.arraydim).*NmrData.rp;
        end
        NmrData.th=0.0;
        hPlot=plot(hAxes,NmrData.Specscale,...
            real(NmrData.SPECTRA(:,NmrData.flipnr)));
        set(hPlot,'HitTest','off')
        xlabel(hAxes,'\bf Chemical shift');
        set(hAxes,'Xdir','Reverse');
        axis('tight');

        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        NmrData.pivotxdata=[NmrData.pivot NmrData.pivot];
        NmrData.pivotydata=get(hAxes,'ylim');
        NmrData.dosyconstantOriginal=NmrData.dosyconstant;
        NmrData.DELTAOriginal=NmrData.DELTA;
        NmrData.deltaOriginal=NmrData.delta;
        NmrData.tauOriginal=NmrData.tau;
        NmrData.gammaOriginal=NmrData.gamma;
        NmrData.array2nr=1;
        NmrData.array3nr=1;
        NmrData.narray3=1;
        NmrData.narray2=NmrData.arraydim/NmrData.ngrad;
        if NmrData.ngrad2~=NmrData.ngrad
            NmrData.narray2=NmrData.arraydim/NmrData.ngrad; %3 and 4
            NmrData.narray3=NmrData.arraydim/NmrData.ngrad2; %4
            NmrData.narray2=NmrData.narray2./NmrData.narray3; %3
        elseif NmrData.ngrad==1 && NmrData.arraydim>1 %This is a normal 2D experiment I think
            NmrData.narray2=1;
            NmrData.narray3=1;
            NmrData.ngrad2=NmrData.arraydim;
            NmrData.ngrad=NmrData.arraydim;
        end
        NmrData.gradnr=1;
        NmrData.fshift=zeros(1,NmrData.arraydim);
        set(hEditShift,'string',num2str(0));
        set(hEditLinear,'string',num2str(0));
        %NmrData.fshift=zeros(1,NmrData.arraydim);
        %AC
        NmrData.include=ones(1,NmrData.fn);
        NmrData.includelinepoints=[];
        NmrData.incpoints=[1 NmrData.fn];
        NmrData.LRRegionData=ones(100,1);
        NmrData.SVDcutoff=0.999;
        NmrData.locodosyopts=[0 0 0 0 0];
        NmrData.pfIterations=2500;
        set(hEditsderrmultiplier,'string',num2str(4));
        set(hEditDlimit,'string',num2str(25));
        set(hEditVlimit,'string',num2str(5));
        set(hEditSVDcutoff,'string',num2str(0.99));
        set(hLRWindowsShow,'Value',0)
        %AC
        set(hEditFlip,'string',num2str(NmrData.gradnr));
        set(hEditFlip2,'string',num2str(NmrData.array2nr));
        set(hEditFlip3,'string',num2str(NmrData.array3nr));
        set(hEditFlipSpec,'string',num2str(NmrData.flipnr));
        set(hEditFlipSpecShort,'String',num2str(NmrData.flipnr))
        set(hTextFlip,'string',['/' num2str(NmrData.ngrad)]);
        set(hTextFlip2,'string',['/' num2str(NmrData.narray2)]);
        set(hTextFlip3,'string',['/' num2str(NmrData.narray3)]);
        set(hTextFlipSpec,'string',['/' num2str(NmrData.arraydim)]);
        set(hButtonFid,'value',0);
        set(hButtonSpec,'value',1);
        set(hEditStop,'string',num2str(NmrData.arraydim));
         
         %Using phase correction for difital filter         
         if isempty(NmrData.lrfidOrg)
             %new data set
             NmrData.dspPhase=NmrData.lrfid*360;
             NmrData.lrfidOrg=NmrData.lrfid;
             NmrData.lrfid=0;
         end
         
        %Sanity check of dosy parameters - if they shoudl exist
        
        if ~strcmp(NmrData.delta,'non existing')
            if (NmrData.delta<=0) || (NmrData.delta==Inf) || (isnan(NmrData.delta))
                guidata(hMainFigure,NmrData); WriteLogDispInfo('WARNING. Diffusion encoding pulse width is not sensible.')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('Setting it to a default value of 0.001.')
                guidata(hMainFigure,NmrData); WriteLogDispInfo('You should probably change it under "Edit -> parameters"')
                NmrData.delta=0.001;
            end
        end
        if ~strcmp(NmrData.DELTA,'non existing')
            if length(NmrData.DELTA)==1 %If an array is read, it is assumed the values are correct
                if (NmrData.DELTA<=0) || (NmrData.DELTA==Inf) || (isnan(NmrData.DELTA))
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('WARNING. Diffusion time is not sensible.')
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('Setting it to a default value of 0.1.')
                    guidata(hMainFigure,NmrData); WriteLogDispInfo('You should probably change it under "Edit -> parameters"')
                    NmrData.DELTA=0.1;
                end
            end
        end
        
        NmrData.DELTAprime=...
            NmrData.dosyconstant./(NmrData.gamma.^2.*NmrData.delta.^2);
        guidata(hMainFigure,NmrData);

        FTButton_Callback();
        set(hExcludeShow,'Value',0)
        set(hNgradUse,'Value',0)
        set(hArray2Use,'Value',0)
        set(hArray3Use,'Value',0)
        set(hBaselineShow,'Value',0)
        set(hSNRShow,'Value',0)
        
        set(hEditNgrad,'string',[])
        set(hEditArray2,'string',[])
        set(hEditArray3,'string',[])
        
        %FTButton messes it up
        ButtonAutoscale_Callback();
        guidata(hMainFigure,NmrData);
        ClearIntegralsButton_Callback()
    end
    function Setup_NmrData_NN()
    
        NmrData = guidata(hMainFigure);
        set(hMainFigure,'CurrentAxes',hAxes)
    
        % -------------------------------
        % Basic structural parameters
        % -------------------------------
        NmrData.fn = size(NmrData.SPECTRA,1);
        NmrData.np = NmrData.fn;
    
        % Frequency axis (same logic as Setup_NmrData)
        NmrData.Specscale = linspace( ...
            NmrData.sp, ...
            (NmrData.sw + NmrData.sp), ...
            NmrData.fn);
    
        % Basic plotting state
        NmrData.plottype = 1;
        NmrData.flipnr = 1;
        NmrData.lpOrg = 0;
        NmrData.rpOrg = 0;
    
        % Store updated data
        guidata(hMainFigure,NmrData);
    
        % -------------------------------
        % Direct plot of SPECTRA
        % -------------------------------
        cla(hAxes);
    
        hPlot = plot(hAxes, ...
            NmrData.Specscale, ...
            real(NmrData.SPECTRA(:,NmrData.flipnr)));
    
        set(hPlot,'HitTest','off')
        set(hAxes,'Xdir','Reverse');
        xlabel(hAxes,'\bf Chemical shift');
        axis(hAxes,'tight');
    
        % Store axis limits
        NmrData.xlim_spec = xlim(hAxes);
        NmrData.ylim_spec = ylim(hAxes);
    
        guidata(hMainFigure,NmrData);
    
    end
    function Reference_function(~,~)
        NmrData=guidata(hMainFigure);
        hReference=findobj(hAxes,'tag','Reference');
        delete(hReference);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.referencexdata=[xpos xpos];
        NmrData.referenceydata=get(hAxes,'ylim');
        NmrData.reference=xpos;
        line(NmrData.referencexdata,NmrData.referenceydata,...
            'color','magenta','linewidth', 1.0,...
            'tag','Reference');
        drawnow
        
        set(hChangeEdit,'string',num2str(NmrData.reference,'%1.3f'));
        guidata(hMainFigure,NmrData);
    end
    function Measure_function(~,~)
        NmrData=guidata(hMainFigure);
        hReference=findobj(hAxes,'tag','Reference');
        delete(hReference);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.referencexdata=[xpos xpos];
        NmrData.referenceydata=get(hAxes,'ylim');
        NmrData.reference=xpos;
        line(NmrData.referencexdata,NmrData.referenceydata,...
            'color','magenta','linewidth', 1.0,...
            'tag','Reference');
        drawnow
        guidata(hMainFigure,NmrData);
    end
    function RDLeft_function(~,~)
        NmrData=guidata(hMainFigure);
        hRDleft=findobj(hAxes,'tag','RDleft');
        delete(hRDleft);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.RDleftxdata=[xpos xpos];
        NmrData.RDleftydata=get(hAxes,'ylim');
        NmrData.RDleft=xpos;
        line(NmrData.RDleftxdata,NmrData.RDleftydata,...
            'color','red','linewidth', 1.0,...
            'tag','RDleft');
        drawnow
        set(hRDshowLRCheck,'Value',1);
        guidata(hMainFigure,NmrData);
    end
    function RDRight_function(~,~)
        NmrData=guidata(hMainFigure);
        hRDright=findobj(hAxes,'tag','RDright');
        delete(hRDright);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.RDrightxdata=[xpos xpos];
        NmrData.RDrightydata=get(hAxes,'ylim');
        NmrData.RDright=xpos;
        line(NmrData.RDrightxdata,NmrData.RDrightydata,...
            'color','green','linewidth', 1.0,...
            'tag','RDright');
        drawnow
        set(hRDshowLRCheck,'Value',1);
        guidata(hMainFigure,NmrData);
    end
    function RDCentre_function(~,~)
        NmrData=guidata(hMainFigure);
        hRDcentre=findobj(hAxes,'tag','RDcentre');
        delete(hRDcentre);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.RDcentrexdata=[xpos xpos];
        NmrData.RDcentreydata=get(hAxes,'ylim');
        NmrData.RDcentre=xpos;
        line(NmrData.RDcentrexdata,NmrData.RDcentreydata,...
            'color','black','linewidth', 1.0,...
            'tag','RDcentre');
        drawnow
        set(hRDshowCheck,'Value',1);
        guidata(hMainFigure,NmrData);
    end
    function DeltaLeft_function(~,~)
        NmrData=guidata(hMainFigure);
        hDeltaleft=findobj(hAxes,'tag','Deltaleft');
        delete(hDeltaleft);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.Deltaleftxdata=[xpos xpos];
        NmrData.Deltaleftydata=get(hAxes,'ylim');
        NmrData.Deltaleft=xpos;
        line(NmrData.Deltaleftxdata,NmrData.Deltaleftydata,...
            'color','red','linewidth', 1.0,...
            'tag','Deltaleft');
        drawnow
        set(hDeltashowLRCheck,'Value',1);
        guidata(hMainFigure,NmrData);
    end
    function DeltaRight_function(~,~)
        NmrData=guidata(hMainFigure);
        hDeltaright=findobj(hAxes,'tag','Deltaright');
        delete(hDeltaright);
        pt=get(gca,'currentpoint');
        xpos=pt(1,1);
        NmrData.Deltarightxdata=[xpos xpos];
        NmrData.Deltarightydata=get(hAxes,'ylim');
        NmrData.Deltaright=xpos;
        line(NmrData.Deltarightxdata,NmrData.Deltarightydata,...
            'color','green','linewidth', 1.0,...
            'tag','Deltaright');
        drawnow
        set(hDeltashowLRCheck,'Value',1);
        guidata(hMainFigure,NmrData);
    end
    function [ImportData]= ImportToolboxFormat(FileIdentifier)
        statfil=FileIdentifier;
        ImportData=[];
        k=1;
        while k
            ParmLine=fgetl(statfil);
            if ParmLine==-1;  break;  end
            StrName=[];%#ok<NASGU>
            StringOne=[];%#ok<NASGU>
            ParmName=[];%#ok<NASGU>
            ParmForm=[];%#ok<NASGU>
            ParmUnit=[];
            ParmComment=[];
            if strcmp(ParmLine(1:2),'##')
                %Only for Human eyes
                continue
            elseif strcmp(ParmLine(1),'#')
                %parse stings
                StringOne=ParmLine(2:end);
                %parse mandatory parethesis
                if ~contains(StringOne,')') || ~contains(StringOne,'(')
                    error('DOSY Toolbox: File import. Mandatory parenthesis (e.g. (double)) missing')
                else
                    ParmIndexOne=strfind(StringOne,'(');
                    ParmIndexTwo=strfind(StringOne,')');
                    ParmName=StringOne(ParmIndexOne+1:ParmIndexTwo-1);
                    SemiIdx=strfind(';',ParmName);
                    switch length(SemiIdx)
                        case 0
                            ParmForm=ParmName;
                            ParmForm(isspace(ParmForm))=[];
                            
                        case 1
                            ParmForm=ParmName(1: SemiIdx(1)-1)   ;
                            ParmForm(isspace(ParmForm))=[];
                            ParmUnit=ParmName(SemiIdx(1)+1:end );
                            ParmUnit(isspace(ParmUnit))=[];
                            
                        case 2
                            ParmForm=ParmName(1: SemiIdx(1)-1)  ;
                            ParmForm(isspace(ParmForm))=[];
                            ParmUnit=ParmName(SemiIdx(1)+1:SemiIdx(2)-1 );
                            ParmUnit(isspace(ParmUnit))=[];
                            ParmComment=ParmName(SemiIdx(2)+1:end );
                            
                        otherwise
                            error('GNAT: File import. Illegal format within parenthesis')
                    end
                end
                if contains(StringOne,'[')
                    %Check for array
                    sq_idx1=strfind(StringOne,'[');
                    if contains(StringOne,']')
                        sq_idx2=strfind(StringOne,']');
                    end
                    arrayval=str2double(StringOne(sq_idx1:sq_idx2)); 
                    if isempty(arrayval)
                        %Not intended as an array?)
                        error('GNAT: File import. No value in array brackets - aborting import')
                    else
                        %read in array in cell array
                        StrName=StringOne(1:sq_idx1-1);
                        StrName(~isletter(StrName))=[];
                        
                        
                        if strcmp(StrName,'DataPoints') && isfield(ImportData,'ComplexData')
                            %These are the actual data points
                            ImportData.(StrName).Value=zeros(1,arrayval);
                            if strcmpi(ImportData.ComplexData.Value,'Yes')
                                guidata(hMainFigure,NmrData); WriteLogDispInfo('complex data')
                                for m=1:arrayval
                                    ParmLine=fgetl(statfil);
                                    if ParmLine==-1;  break;  end
                                    TmpPoint=sscanf(ParmLine,'%e %e');
                                    ImportData.(StrName).Value(m)=complex(TmpPoint(1),TmpPoint(2));
                                end
                            else
                                for m=1:arrayval
                                    ParmLine=fgetl(statfil);
                                    if ParmLine==-1;  break;  end
                                    ImportData.(StrName).Value(m)= sscanf(ParmLine,'%e');
                                end
                            end
                        else
                            ImportData.(StrName).Value=cell(1,arrayval);
                            for m=1:arrayval
                                ParmLine=fgetl(statfil);
                                if ParmLine==-1;  break;  end
                                ImportData.(StrName).Value{1,m}=ParmLine;
                            end
                        end
                    end
                else
                    %parse non-arrayed data
                    StrName=StringOne(1:ParmIndexOne-1);
                    StrName(~isletter(StrName))=[];
                    ParmVal=StringOne(ParmIndexTwo+1:end);
                    %remove trailing white spaces
                    while  ~isempty(ParmVal) && isspace(ParmVal(1))
                        ParmVal(1)=[];
                    end
                    while ~isempty(ParmVal) && isspace(ParmVal(end))
                        ParmVal(end)=[];
                    end
                    %remove double quotes
                    while  ~isempty(ParmVal) && strcmp('"',ParmVal(1))
                        ParmVal(1)=[];
                    end
                    while ~isempty(ParmVal) && strcmp('"',ParmVal(end))
                        ParmVal(end)=[];
                    end
                    ImportData.(StrName).Value=[];
                    while ~isempty(ParmVal) && isspace(ParmVal(1))
                        ParmVal(1)=[];
                    end
                    if strcmp(ParmForm,'string')
                        ImportData.(StrName).Value=ParmVal;
                    elseif strcmp(ParmForm,'null')
                        ImportData.(StrName).Value='';
                    elseif isempty(ParmForm)
                        ImportData.(StrName).Value=ParmVal;
                        guidata(hMainFigure,NmrData); WriteLogDispInfo(['Warning: ' 'DOSY Toolbox: File import' 'missing data format. Importing as string'])
                    else
                        ImportData.(StrName).Value=str2num(ParmVal);
                    end
                    
                end
                ImportData.(StrName).ParmForm=ParmForm;
                ImportData.(StrName).ParmUnit=ParmUnit;
                ImportData.(StrName).ParmComment=ParmComment;
                %                 %ImportData.(StrName)
                % ImportData
            end
        end
        fclose(statfil);
        %ImportData.BinaryFileName
        
    end
    function ExportToolboxFormat(FileIdentifier, ExportType,DataFormat, FileName, PathName)
        statfil=FileIdentifier;
        %print out FID data to file
        if isunix()==1
            slashindex=find(NmrData.filename=='/');
        elseif NmrData.issynthetic==1      %AC
            slashindex=1;
        else
            slashindex=find(NmrData.filename=='\');
        end
        fprintf(statfil,'%-s  \n','## GNAT data file');
        
        fprintf(statfil,'%-s  \n','## ************ File and Data Information **********************');
        if DataFormat==1 %ASCII
            fprintf(statfil,'%-s\t\t\t\t\t\t  \n','#Binary File Name (null)');
        elseif DataFormat==2 %binary
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Binary File Name (string)','*.bin');
        else
            error('Unknown DataFormat')
        end
        switch ExportType
            case 1
                %complex FID
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', '"FID"');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"Yes"');
            case 2
                %complex spectra
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', '"Spectra"');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"Yes"');
            case 3
                %real spectra
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', '"Spectra"');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
            case 4
                % DOSY display
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', '"DOSY"');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
            case 5
                % SCORE residuals
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', '"Spectra"');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
            case 6
                % SCORE components
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Class (string) ', '"Spectra"');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
            otherwise
        end
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Origin (string) ', '"GNAT"');
        if  ExportType==1 || ExportType==2 ||ExportType==3
            %complex FID or complex spec or real spec
            if strcmpi(NmrData.DELTA,'non existing')==0 %DOSY DATA
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', '"DOSY data"');
            elseif isempty(NmrData.d2)==0 %relaxation data
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', '"Relaxation data"');
            else
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', '"NMR data"');
                
            end
        elseif  ExportType==4
            % DOSY display
            fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', '"DOSY plot"');
        elseif  ExportType==5
            % SCORE residuals
            fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', '"SCORE residuals"');
        elseif  ExportType==6
            % SCORE components
            fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', '"SCORE components"');
        elseif  ExportType==7
            % complex FID or complex spec or real spec of an array
            fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Data Type (string) ', '"DOSY data"');
        else
            error('File export: Unknown Data Class')
        end
        
        fprintf(statfil,'%-s\t\t\t\t\t\t\t %-s \n','#Date (string) ' ,['"' string(datetime) '"'] );
        fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#GNAT Format Version (string) ', '0.1');
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#GNAT Version (string) ', ['"' NmrData.version '"']);
        if  ExportType==1 || ExportType==2 ||ExportType==3
            %complex FID, complex spex or real spec
            if NmrData.arraydim==1
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Arrays (integer)', 0);
            elseif  NmrData.arraydim==NmrData.ngrad
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Arrays (integer)', 1);
            else
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Arrays (integer)', 2);
            end
        elseif  ExportType==4 || ExportType==5 ||  ExportType==6
            % DOSY display,  SCORE residuals, SCORE components
            fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Arrays (integer)', 1);
        elseif  ExportType==7
            % complex FID or complex spec or real spec of an array
            fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Arrays (integer)', 2);
        else
            error('File export: Unknown Data Class')
        end
        
        fprintf(statfil,'%-s\t\t\t\t %-s  \n','#Spectrometer/Data System (string)', ['"' NmrData.type '"']);
        fprintf(statfil,'%-s\t\t\t\t\t\t %-s \n','#Title (string) ' , ['"' NmrData.filename(slashindex(end)+1:end) '"'] );
        
        fprintf(statfil,'%-s  \n','## ************ Matrix Format **********************************');
        switch ExportType
            case 1
                %complex FID
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"Yes"');
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Rows (integer) ', NmrData.arraydim);
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Points Per Row (integer) ', NmrData.np);
                
            case 2
                %complex spectra
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"Yes"');
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Rows (integer) ', NmrData.arraydim);
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Points Per Row (integer) ', NmrData.fn);
                
            case 3
                %real spectra
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Rows (integer) ', NmrData.arraydim);
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Points Per Row (integer) ', NmrData.fn);
                
            case 4
                % DOSY display
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Rows (integer) ', length(NmrData.dosydata.Dscale));
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Points Per Row (integer) ', length(NmrData.dosydata.Spectrum));
            case 5
                % SCORE residuals
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Rows (integer) ', NmrData.scoredata.ngrad);
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Points Per Row (integer) ', NmrData.scoredata.np);
            case 6
                % SCORE components
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Complex Data (string)', '"No"');
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Number Of Rows (integer) ', NmrData.scoredata.ncomp);
                fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Points Per Row (integer) ', NmrData.scoredata.np);
            otherwise
                
        end
        if  ExportType==1 || ExportType==2 ||ExportType==3 || ExportType==5 || ExportType== 6
            %complex FID or complex spec or real spec, SCORE residuals,
            %SCORE components    
            if NmrData.arraydim==1 %1D data
            else
                fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Y Axis Definition (string)', '"Gradient Amplitude"');
                fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Y Label (null)', '');
            end
        elseif  ExportType==4
            % DOSY display
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Y Axis Definition (string)', '"Diffusion Scale"');
            fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Y Label (string)', '"Diffusion coefficient m^{2} s^{-1} \times 10^{-10}"');
        elseif  ExportType==7
            % complex FID or complex spec or real spec of an array
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Y Axis Definition (string)', '"Gradient Amplitude"');
            fprintf(statfil,'%-s\t\t\t\t\t\t %-s  \n','#Y Label (null)', '');
        else
            error('File export: Unknown Data Class')
        end
        
        fprintf(statfil,'%-s  \n','## ************ Acquisition Parameters *************************');
        fprintf(statfil,'%-s\t\t\t\t\t %-e  \n','#Acquisition Time (double; s) ', NmrData.at);
        fprintf(statfil,'%-s\t\t\t\t %-d  \n','#Complex Points Acquired (integer) ', NmrData.np);
        if  ExportType==1 || ExportType==2 ||ExportType==3||ExportType==7
            %complex FID, complex spex or real spec
            fprintf(statfil,'%-s\t\t\t\t %-e  \n','#Lowest Frequency (double ; ppm)', NmrData.sp);
            fprintf(statfil,'%-s\t\t\t\t %-e  \n','#Observe Frequency (double ; MHz) ', NmrData.sfrq);
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Observe Nucleus (string) ', '"1-H"');
            fprintf(statfil,'%-s\t\t\t\t\t %-e  \n','#Spectral Width (double ; ppm) ', NmrData.sw);
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Pulse Sequence Name (string) ', '"Unknown"');
            if ExportType==1
                fprintf(statfil,'%-s\t\t\t\t\t\t %-e  \n','#Left Rotation (double)', NmrData.lrfidOrg);
            else
                fprintf(statfil,'%-s\t\t\t\t\t\t %-e  \n','#Left Rotation (double)', NmrData.lrfid);
            end
        elseif  ExportType==4
            % DOSY display
            fprintf(statfil,'%-s\t\t\t\t %-f  \n','#Lowest Frequency (double ; ppm)', NmrData.dosydata.sp);
            fprintf(statfil,'%-s\t\t\t\t %-e  \n','#Observe Frequency (double ; MHz) ', NmrData.sfrq);
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Observe Nucleus (string) ', '"1-H"');
            fprintf(statfil,'%-s\t\t\t\t\t %-f  \n','#Spectral Width (double ; ppm) ', NmrData.dosydata.wp);
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Pulse Sequence Name (string) ', '"Unknown"');
        elseif  ExportType==5 || ExportType==6
            % DOSY display
            fprintf(statfil,'%-s\t\t\t\t %-f  \n','#Lowest Frequency (double ; ppm)', NmrData.scoredata.sp);
            fprintf(statfil,'%-s\t\t\t\t %-e  \n','#Observe Frequency (double ; MHz) ', NmrData.sfrq);
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Observe Nucleus (string) ', '"1-H"');
            fprintf(statfil,'%-s\t\t\t\t\t %-f  \n','#Spectral Width (double ; ppm) ', NmrData.scoredata.wp);
            fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Pulse Sequence Name (string) ', '"Unknown"');
        else
            error('File export: Unknown Data Class')
        end
        
        fprintf(statfil,'%-s  \n','## ************ Processing parameters ***************************');
        
        if  ExportType==1 ||  ExportType==2 ||  ExportType==3 ||  ExportType==4||  ExportType==7
            fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Fourier Number (integer) ', NmrData.fn);
        elseif  ExportType==5 || ExportType==6
            fprintf(statfil,'%-s\t\t\t\t\t %-d  \n','#Fourier Number (integer) ', NmrData.scoredata.np);
        else
            error('File export: Unknown Fourier Number')
        end
        if  ExportType==1
            %complex FID, complex spec or real spec
            fprintf(statfil,'%-s\t\t\t %-e  \n','#Left Phase (double; degree; First order) ', NmrData.lp);
            fprintf(statfil,'%-s\t\t\t %-e  \n','#Right Phase (double; degree; Zeroth order) ', NmrData.rp);
            fprintf(statfil,'%-s%-d%-s\t\t\t \n','#Left Phase Array [', NmrData.arraydim ,'] (double data 1 ; T m^-1)');
            for k=1:NmrData.arraydim
                fprintf(statfil,'%-e  \n', NmrData.lpInd(k));
            end
            fprintf(statfil,'%-s%-d%-s\t\t\t \n','#Right Phase Array [', NmrData.arraydim ,'] (double data 1 ; T m^-1)');
            for k=1:NmrData.arraydim
                fprintf(statfil,'%-e  \n', NmrData.rpInd(k));
            end
        elseif  ExportType==2 ||ExportType==3 || ExportType==5 ||ExportType==6
            fprintf(statfil,'%-s\t\t\t %-e  \n','#Left Phase (double; degree; First order) ', 0);
            fprintf(statfil,'%-s\t\t\t %-e  \n','#Right Phase (double; degree; Zeroth order) ', 0);
        elseif  ExportType==4||ExportType==7
            %phase parameters not relevant
        else
            error('File export: Unknown Data Class')
        end
        
        
        if  ExportType==1 || ExportType==2 ||ExportType==3 || ExportType==5 ||ExportType==6||ExportType==7
            %complex FID or complex spec or real spec
            if NmrData.arraydim==1 %1D data
            elseif strcmpi(NmrData.DELTA,'non existing')==0 %DOSY DATA
                fprintf(statfil,'%-s  \n','## ************ Diffusion Parameters ****************************');
                fprintf(statfil,'%-s\t\t\t\t %-e  \n','#Diffusion Delay (double ; s ; DELTA) ', NmrData.DELTA);
                fprintf(statfil,'%-s\t\t\t %-e  \n','#Diffusion Encoding Time (double ; s ; delta) ', NmrData.delta);
                fprintf(statfil,'%-s\t\t\t\t\t\t %-e  \n','#Dosygamma (double) ', NmrData.gamma);
                fprintf(statfil,'%-s\t\t\t\t\t %-e  \n','#Dosytimecubed (double) ', NmrData.dosyconstant/NmrData.gamma.^2);
                fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Gradient Shape (string) ', '"Square"');
                fprintf(statfil,'%-s\t\t\t\t\t %-s  \n','#Pulse Sequence Type (string)', '"Other"');
            elseif isempty(NmrData.d2)==0 %relaxation data
                fprintf(statfil,'%-s  \n','## ************ Relaxation Parameters ****************************');
            else %general array
            end
            %fprintf(statfil,'%-s\t\t\t\t\t   \n','#Tau (null)');
        elseif  ExportType==4
            % DOSY display
        else
            error('File export: Unknown Data Class')
        end
        fprintf(statfil,'%-s  \n','## ************ Arrays *****************************************');
        if  NmrData.arraydim==1 %1D data
            
        else
            if strcmpi(NmrData.DELTA,'non existing')==0 %DOSY DATA
                if  ExportType==1 || ExportType==2 ||ExportType==3||ExportType==7
                    %complex FID or complex spec or real spec
                    fprintf(statfil,'%-s%-d%-s\t\t\t \n','#Gradient Amplitude [', NmrData.ngrad ,'] (double data 1 ; T m^-1)');
%                     for k=1:NmrData.ngrad
%                         fprintf(statfil,'%-e  \n', NmrData.Gzlvl(k));
%                     end
                    
                elseif  ExportType==4
                    % DOSY display
                    fprintf(statfil,'%-s%-d%-s\t\t\t \n','#Diffusion Scale [', length(NmrData.dosydata.Dscale) ,'] (double data 1 ; m^2 s^-1 * 10^-10)');
                    for k=1:length(NmrData.dosydata.Dscale)
                        fprintf(statfil,'%-f  \n', NmrData.dosydata.Dscale(k));
                    end
                elseif  ExportType==5
                    %SCORE Residuals
                    fprintf(statfil,'%-s%-d%-s\t\t\t \n','#Gradient Amplitude [', NmrData.scoredata.ngrad ,'] (double data 1 ; T m^-1)');
                    for k=1:NmrData.scoredata.ngrad
                        fprintf(statfil,'%-e  \n', NmrData.scoredata.Gzlvl(k));
                    end
                elseif  ExportType==6
                    % SCORE components
                    fprintf(statfil,'%-s%-d%-s\t\t\t \n','#Component Number [', NmrData.scoredata.ncomp ,'] (double data 1 ; m^2 s^-1 * 10^-10)');
                    for k=1:NmrData.scoredata.ncomp
                        fprintf(statfil,'%-f  \n', k);
                    end
                else
                    error('File export: Unknown Data Class')
                end
            elseif isempty(NmrData.d2)==0 %relaxation data
                    fprintf(statfil,'%-s%-d%-s\t\t\t \n','#Delays [', numel(NmrData.d2) ,'] (double data 1 ; T m^-1)');
                    for k=1:numel(NmrData.d2)
                        fprintf(statfil,'%-e  \n', NmrData.d2(k));
                    end
            else %general array
            end
        end
        if NmrData.issynthetic==1
            fprintf(statfil,'%-s  \n','## ************ Synthetic Parameters *************************');
            fprintf(statfil,'%-s\t\t\t\t %-d  \n','#Number of Synthetic Peaks (integer) ', str2double(get(hEditnpeaks,'string'))); 
            fprintf(statfil,'%-s\t\t\t %-e  \n','#Lowest Gradient Strength (double ; T m-1) ', str2double(get(hEditmingrad,'string'))); 
            fprintf(statfil,'%-s\t\t\t %-e  \n','#Highest Gradient Strength (double ; T m-1) ', str2double(get(hEditmaxgrad,'string'))); 
            fprintf(statfil,'%-s\t\t\t\t %-d  \n','#Number of DOSY Increments (integer) ', str2double(get(hEditni,'string'))); 
            fprintf(statfil,'%-s\t\t\t\t %-d  \n','#Signal to Noise Ratio (integer) 1/ ', str2double(get(hEditnoise,'string')));
            
            SynthTableData=get(hTableSynthPeaks,'Data');
            SynthData.Freqs=SynthTableData(:,1);
            SynthData.Dvals=SynthTableData(:,2);
            SynthData.Amps=SynthTableData(:,3);
            SynthData.lw=SynthTableData(:,4);
            SynthData.gw=SynthTableData(:,5);
            
            fprintf(statfil,'%-s\t\t\t \n','#Peak Frequencies (double data ; Hz)');
            for k=1:length(SynthData.Freqs)
                fprintf(statfil,'%-e  \n', SynthData.Freqs(k));
            end
            
            fprintf(statfil,'%-s\t\t\t \n','#Diffusion Coefficients (double data ; m^2 s^-1 * 10^-10)');
            for k=1:length(SynthData.Dvals)
                fprintf(statfil,'%-e  \n', SynthData.Dvals(k));
            end
            
            fprintf(statfil,'%-s\t\t\t \n','#Peak Amplitudes (double data;)');
            for k=1:length(SynthData.Amps)
                fprintf(statfil,'%-e  \n', SynthData.Amps(k));
            end
            
            fprintf(statfil,'%-s\t\t\t \n','#Line Widths Lorentzian (double data ; Hz)');
            for k=1:length(SynthData.lw)
                fprintf(statfil,'%-e  \n', SynthData.lw(k));
            end
            
            fprintf(statfil,'%-s\t\t\t \n','#Line Widths Gaussian (double data ; Hz)');
            for k=1:length(SynthData.gw)
                fprintf(statfil,'%-e  \n', SynthData.gw(k));
            end
        end
        
        fprintf(statfil,'%-s  \n','## ************ Actual Data Points *****************************');
        
        switch ExportType
            case 1
                %complex FID
                fprintf(statfil,'%-s%-d%-s\t\t\t\t \n','#Data Points [', NmrData.np*NmrData.arraydim ,'] (double)');
                
                
            case 2
                %complex spectra
                fprintf(statfil,'%-s%-d%-s\t\t\t\t \n','#Data Points [', NmrData.fn*NmrData.arraydim ,'] (double)');
                
            case 3
                %real spectra
                fprintf(statfil,'%-s%-d%-s\t\t\t\t \n','#Data Points [', NmrData.fn*NmrData.arraydim ,'] (double)');
                
                
            case 4
                % DOSY display
                fprintf(statfil,'%-s%-d%-s\t\t\t\t \n','#Data Points [', length(NmrData.dosydata.Dscale).*length(NmrData.dosydata.Spectrum),'] (double)');
                
            case 5
                % SCORE residuals
                fprintf(statfil,'%-s%-d%-s\t\t\t\t \n','#Data Points [', NmrData.scoredata.np*NmrData.scoredata.ngrad,'] (double)');
                
            case 6
                % SCORE components
                fprintf(statfil,'%-s%-d%-s\t\t\t\t \n','#Data Points [', NmrData.scoredata.ncomp*NmrData.scoredata.np ,'] (double)');
                
            case 7
                %complex FID array
                fprintf(statfil,'%-s%-d%-s\t\t\t\t \n','#Data Points [', NmrData.np*NmrData.arraydim ,'] (double)');
                
            otherwise
                
        end
        
        
        if DataFormat==1 %ASCII
            
            switch ExportType
                case 1
                    %complex FID
                    hp=waitbar(0,'Exporting DOSY data (FID)');
                    
                    for k=1:NmrData.arraydim
                        waitbar(k/NmrData.arraydim);
                        for m=1:NmrData.np
                            fprintf(statfil,'%-e %e  \n', real(NmrData.FID(m,k)), imag(NmrData.FID(m,k)) );
                        end
                    end
                    
                    close(hp)
                    
                case 2
                    %complex spectra
                    hp=waitbar(0,'Exporting DOSY data (complex spectra)');
                    NmrData.SPECTRA=flipud(NmrData.SPECTRA);
                    for k=1:NmrData.ngrad
                        waitbar(k/NmrData.ngrad);
                        for m=1:NmrData.fn
                            fprintf(statfil,'%-e %e  \n', real(NmrData.SPECTRA(m,k)), imag(NmrData.SPECTRA(m,k)) );
                        end
                    end
                    close(hp)
                case 3
                    %real spectra
                    hp=waitbar(0,'Exporting DOSY data (real spectra)');
                    NmrData.SPECTRA=flipud(NmrData.SPECTRA);
                    for k=1:NmrData.ngrad
                        waitbar(k/NmrData.ngrad);
                        for m=1:NmrData.fn
                            fprintf(statfil,'%-e \n', real(NmrData.SPECTRA(m,k)) );
                        end
                    end
                    close(hp)
                    
                case 4
                    % DOSY display
                    hp=waitbar(0,'Exporting DOSY plot');
                    NmrData.dosydata.DOSY=rot90(NmrData.dosydata.DOSY,2);
                    for k=1:length(NmrData.dosydata.Dscale)
                        waitbar(k/length(NmrData.dosydata.Dscale));
                        for m=1:length(NmrData.dosydata.Spectrum)
                            fprintf(statfil,'%-e  \n', NmrData.dosydata.DOSY(m,k));
                        end
                    end
                    close(hp)
                case 5
                    % SCORE residuals
                    hp=waitbar(0,'Exporting SCORE residuals');
                    %size(NmrData.scoredata.RESIDUALS)
                    for k=1:NmrData.scoredata.ngrad
                        waitbar(k/NmrData.scoredata.ngrad);
                        for m=1:NmrData.scoredata.np
                            fprintf(statfil,'%-e \n', NmrData.scoredata.RESIDUALS(m,k) );
                        end
                    end
                    close(hp)
                case 6
                    % SCORE components
                    hp=waitbar(0,'Exporting SCORE components');
                    %Normalise components?
                    %size(NmrData.scoredata.COMPONENTS)
                    for k=1:NmrData.scoredata.ncomp
                        waitbar(k/NmrData.ngrad);
                        for m=1: NmrData.scoredata.np
                            fprintf(statfil,'%-e \n', NmrData.scoredata.COMPONENTS(k,m) );
                        end
                    end
                    close(hp)
                case 7
                    %complex FID array
                    hp=waitbar(0,'Exporting DOSY data (FID)');
                    
                    for k=1:NmrData.arraydim
                        waitbar(k/NmrData.arraydim);
                        for m=1:NmrData.np
                            fprintf(statfil,'%-e %e  \n', real(NmrData.FID(m,k)), imag(NmrData.FID(m,k)) );
                        end
                    end
                    
                    close(hp)
                otherwise
            end
            fclose(statfil);
            
        elseif DataFormat==2 %binary
            fclose(statfil);
            filepath=[PathName FileName];
            filepath=filepath(1:(end-4));
            filepath=[filepath '.bin'];
            binfile=fopen(filepath, 'w','b');
            switch ExportType
                case 1
                    %complex FID
                    hp=waitbar(0,'Exporting DOSY data (FID)');
                    fwrite(binfile,real(NmrData.FID),'int64',0,'b');
                    fwrite(binfile,imag(NmrData.FID),'int64',0,'b');
                    close(hp)
                    
                case 2
                    %complex spectra
                    hp=waitbar(0,'Exporting DOSY data (complex spectra)');
                    NmrData.SPECTRA=flipud(NmrData.SPECTRA);
                    fwrite(binfile,real(NmrData.SPECTRA),'int64',0,'b');
                    fwrite(binfile,imag(NmrData.SPECTRA),'int64',0,'b');
                    close(hp)
                case 3
                    %real spectra
                    hp=waitbar(0,'Exporting DOSY data (real spectra)');
                    NmrData.SPECTRA=flipud(NmrData.SPECTRA);
                    fwrite(binfile,real(NmrData.SPECTRA),'int64',0,'b');
                    close(hp)
                    
                case 4
                    % DOSY display
                    hp=waitbar(0,'Exporting DOSY plot');
                    NmrData.dosydata.DOSY=rot90(NmrData.dosydata.DOSY,2);
                    for k=1:length(NmrData.dosydata.Dscale)
                        waitbar(k/length(NmrData.dosydata.Dscale));
                        for m=1:length(NmrData.dosydata.Spectrum)
                            fprintf(statfil,'%-e  \n', NmrData.dosydata.DOSY(m,k));
                        end
                    end
                    close(hp)
                case 5
                    % SCORE residuals
                    hp=waitbar(0,'Exporting SCORE residuals');
                    %size(NmrData.scoredata.RESIDUALS)
                    for k=1:NmrData.scoredata.ngrad
                        waitbar(k/NmrData.scoredata.ngrad);
                        for m=1:NmrData.scoredata.np
                            fprintf(statfil,'%-e \n', NmrData.scoredata.RESIDUALS(m,k) );
                        end
                    end
                    close(hp)
                case 6
                    % SCORE components
                    hp=waitbar(0,'Exporting SCORE components');
                    %Normalise components?
                    %size(NmrData.scoredata.COMPONENTS)
                    for k=1:NmrData.scoredata.ncomp
                        waitbar(k/NmrData.ngrad);
                        for m=1: NmrData.scoredata.np
                            fprintf(statfil,'%-e \n', NmrData.scoredata.COMPONENTS(k,m) );
                        end
                    end
                    close(hp)
                otherwise
            end
            fclose(binfile);
        else
            fclose(statfil);
            error('unknown DataFormat')
        end
    end
    function fpeakclusters(~, ~)
        if NmrData.th==0
            errordlg('Please set a threshold before auto-segmenting.')
        else
            % Take the average y value for the spectrum and set the threshhold for peakfind
            % clustering as that, making sure this is above the noise.
            %   OR use a user defined threshold (current system).
            NmrData=guidata(hMainFigure);
            set(hLRWindowsShow,'Value',1)
            hIncludeline=findobj(hAxes,'tag','includeline');
            set(hIncludeline,'Visible','Off')
            if  get(hThreshButton,'Value') == 1
                hThresh=findobj(hAxes,'tag','threshold');
                if isempty(hThresh)
                    %do nothing
                else
                    set(hThresh,'Visible','on');
                end
            end
            %             hThresh=findobj(hAxes,'tag','threshold');
            %             delete(hThresh);  %(works even if hthresh==[])
            threshold=NmrData.thresydata(1,1);
            %     value=sum(sum(real(NmrData.SPECTRA)));
            %     threshold=(value/(NmrData.fn*NmrData.ngrad));
            %     RMSnoise=calcRMSnoise(NmrData.SPECTRA,NmrData.Specscale);
            %     if threshold<(RMSnoise*10)
            %         threshold=RMSnoise*10;
            %     end
            firstspect=real(NmrData.SPECTRA(:,1));
            sw=(max(abs(NmrData.Specscale))+min(abs(NmrData.Specscale)));
            leeway=round(25*(NmrData.fn/(sw*NmrData.sfrq)));
            currentpoint=0;
            numwin=0;
            %rows3=0;
            finished=0;
            winstartind=0;
            %winendin=0;
            while finished==0
                numwin=numwin+1;
                [rows2]=find((firstspect(currentpoint+1:end,1)>(threshold)),1);
                rows2=rows2+currentpoint+1;
                currentpoint=rows2;
                if rows2
                    [rows3]=find((firstspect(rows2+1:end,1)<(threshold)),1);
                    currentpoint=currentpoint+rows3;
                    winstartind(numwin)=rows2; %#ok<AGROW>
                    winendind(numwin)=currentpoint; %#ok<AGROW>
                else
                    finished=1;
                end
            end
            %numwin=numwin-1; %test is past numwin+1
            
            %count=0;
            peakline=ones(1,length(NmrData.Specscale));
            % code for ignoring very thin peaks and grouping close, narrow peaks
            
            % for m=1:length(winstartind)
            %     if (winendind(m)-winstartind(m))>(leeway/4)
            %         count=count+1;
            %         starttmp(count)=winstartind(m);
            %         endtmp(count)=winendind(m);
            %     end
            % end
            % winstartind=starttmp;
            % winendind=endtmp;
            for k=1:length(winstartind)
                winstartind(k)=winstartind(k)-leeway; %#ok<AGROW>
                winendind(k)=winendind(k)+leeway;
                peakline(winstartind(k):winendind(k))=NaN;
            end
            columns=peakline==1;
            peakline=ones(1,length(NmrData.include));
            peakline(1,columns)=NaN;
            %hPeakclustline=
            line(NmrData.Specscale,peakline*threshold,...
                'color',[0 0 0],'linewidth', 1.0,...
                'tag','peakclustline');
            NmrData.nwin=length(winstartind);
            NmrData.winstart=NmrData.Specscale(winstartind);
            NmrData.winend=NmrData.Specscale(winendind);
            NmrData.LRRegionData=ones(length(NmrData.winstart),1);
            set(hRegionsTable,'Data', NmrData.LRRegionData)
            guidata(hMainFigure,NmrData);
        end
    end
    function DrawIncludeline(~,~)
        NmrData=guidata(hMainFigure);
        ypos=get(hAxes,'ylim');
        ypos=(ypos(2)-ypos(1))/2;
        hIncludeline=findobj(hAxes,'tag','includeline');
        delete(hIncludeline)
        ydata=ypos.*NmrData.include;
        xlimits=get(hAxes,'xlim');
        %hIncludeline=
        line(NmrData.Specscale,ydata,...
            'color',[0 0 0],'linewidth', 1.0,...
            'tag','includeline');
        set(hAxes,'xlim',xlimits);
        guidata(hMainFigure,NmrData);
    end
    function Includeline_function(~,~)
        NmrData=guidata(hMainFigure);
        NmrData.xlim_spec=xlim(hAxes);
        NmrData.ylim_spec=ylim(hAxes);
        switch get(gcbf, 'SelectionType')
            case 'normal'
                %leftclick
                %add a new point
                pt=get(gca,'currentpoint');
                xpos=pt(1,1);
                ypos=pt(2,2);
                xl=xlim(hAxes);
                yl=ylim(hAxes);
                if xpos>xl(2) || xpos<xl(1) || ypos>yl(2) || ypos<yl(1)
                    %outside axis
                else
                    NmrData.IncludePoints=[NmrData.IncludePoints xpos];
                end
                
            case 'alt'
                %remove last point
                if ~isempty(NmrData.IncludePoints>0)
                    NmrData.IncludePoints(end)=[];
                end
            case 'extend'
                %middleclick
                %Stop taking new points
                set(hMainFigure,'WindowButtonDownFcn','')
            case 'open'
                %doubleclick
                %do nothing
                
            otherwise
                error('illegal choice')
        end
        NmrData.includelinepoints=unique(NmrData.IncludePoints);
        NmrData.includelinepoints=sort(NmrData.includelinepoints);
        NmrData.include=ones(1,NmrData.fn);
        inpoints=[1 NmrData.fn];
        for k=1:length(NmrData.includelinepoints)
            inpoints=[inpoints round(NmrData.fn*...
                (NmrData.includelinepoints(k)-NmrData.sp)/NmrData.sw)]; %#ok<AGROW>
        end
        inpoints=unique(inpoints);
        inpoints=sort(inpoints);
        inpoints1=inpoints(1:2:end);
        inpoints2=inpoints(2:2:end);
        for k=1:(length(inpoints1))
            if k<=length(inpoints2)
                NmrData.include(inpoints1(k):inpoints2(k))=NaN;
            end
        end
        
        % retrieving the number of components in the window.
        
        NmrData.winstart=NmrData.IncludePoints(1:2:end);
        NmrData.winend=NmrData.IncludePoints(2:2:end);
        NmrData.nwin=length(NmrData.winstart);
        NmrData.LRRegionData=ones(length(NmrData.winstart),1);
        set(hRegionsTable,'Data', NmrData.LRRegionData)
        
        guidata(hMainFigure,NmrData);
        PlotSpectrum();
        set(hAxes,'ButtonDownFcn',@Includeline_function);
    end
    function WriteLogDispInfo(Message)

       NmrData=guidata(hMainFigure);
       disp(Message)

        if iscell(Message)
            if isfield(NmrData,'MessageText')
                %No worries
            else
                NmrData.MessageText={''};
            end
            %NmrData.MessageText
            for k=1:numel(Message)
                NmrData.MessageText{end +1}=Message{k};
            end
        else
            if isfield(NmrData,'MessageText')
                NmrData.MessageText{end +1}=Message;
            else
                NmrData.MessageText={Message};
            end
        end
        set(hTextTest,'String',NmrData.MessageText)
        guidata(hMainFigure,NmrData);
    end
    function click_msgbox(Title,Message) 
    %Added by LC/GDP 21-09-2019 (copy from magnate)
        iconpath= mfilename('fullpath');
        iconname=mfilename;
        iconlength=numel(iconname);
        iconpath((end-iconlength):end)=[];
        iconpath=[iconpath '/gnat_msg.png'];
        rgbImage=imread(iconpath);
        
        clickok_fig=figure('Units','normalized',...
            'MenuBar','none',...
            'Toolbar','none',...
            'NumberTitle','Off',...
            'Name',Title,...
            'WindowStyle','modal',...
            'OuterPosition',[0.5 0.5 0.15 0.11],...
            'Visible', 'Off');
        uicontrol(...
            'Parent',clickok_fig,...
            'Style','text',...
            'Units','Normalized',...
            'String',Message,...
            'FontWeight','normal',...
            'Position',[0.35 0.3 0.5 0.5 ],...
            'horizontalalignment','c');
        uicontrol(...
            'Parent',clickok_fig,...
            'Style','PushButton',...
            'String','OK',...
            'Units','normalized',...
            'Position',[0.45 0.1 0.3 0.3],...
            'Callback',{@clickokButton_Callback})
        hfigAxes = axes(...
            'Parent',clickok_fig,...
            'Units','normalized',...
            'Box','off',...
            'LineWidth',0.1,...
            'Xcolor','none',...
            'Ycolor','none',...
            'Position',[0.1 0.14 0.2 0.66]);
        imshow(rgbImage,'Parent',hfigAxes)
        
        if strcmp(Title,'Error')
            set(clickok_fig,'OuterPosition',[0.5 0.5 0.31 0.16])
        elseif strcmp(Title,'Caution')      
            set(clickok_fig,'OuterPosition',[0.3 0.5 0.33 0.13])
        end
        
        set(clickok_fig,'Visible','On')
        
        function clickokButton_Callback(~,~)
            delete(clickok_fig)
        end
    end
%     function HelpButton(source,eventdata)
%         % Get the origin of the button pressed
%         button = get(source,'tag');
%         
%         %Select with manual page will be displayed
%         switch button
%             case 'PCA'
%                 PCApath = 'GNAT-Manual\docs\_build\html\Analysis Functionalities\Chemometrics\PCA.html';
%                 if (ispc) % Windows User
%                     winopen(PCApath)
%                 elseif ismac % Mac User
%                     PCApath = fileparts(which('PCA.html'));
%                     PCApath = [PCApath '/PCA.html'];
%                     PCApath = ['"' PCApath '"'];
%                     cmdToExecute = ['open ' PCApath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 else % Linux User
%                     % using xdg-open to open a file in Linux. Some Linux systems might not have
%                     % xdg-open .In that case displaying as error with the file path
%                     PCApath = fileparts(which('PCA.html'));
%                     PCApath = [PCApath '/PCA.html'];
%                     PCApath = ['"' PCApath '"'];
%                     cmdToExecute = ['xdg-open ' PCApath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 end   
%             case 'PLSDA'
%                 PLSDApath = 'GNAT-Manual\docs\_build\html\Analysis Functionalities\Chemometrics\PLS-DA.html';
%                 if (ispc) % Windows User
%                     winopen(PLSDApath)
%                 elseif ismac % Mac User
%                     PLSDApath = fileparts(which('PLS-DA.html'));
%                     PLSDApath = [PLSDApath '/PLS-DA.html'];
%                     PLSDApath = ['"' PLSDApath '"'];
%                     cmdToExecute = ['open ' PLSDApath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 else % Linux User
%                     % using xdg-open to open a file in Linux. Some Linux systems might not have
%                     % xdg-open .In that case displaying as error with the file path
%                     PLSDApath = fileparts(which('PLS-DA.html'));
%                     PLSDApath = [PLSDApath '/PLS-DA.html'];
%                     PLSDApath = ['"' PLSDApath '"'];
%                     cmdToExecute = ['xdg-open ' PLSDApath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 end   
%             case 'OPLSDA'
%                 OPLSDApath = 'GNAT-Manual\docs\_build\html\Analysis Functionalities\Chemometrics\OPLS-DA.html';
%                 if (ispc) % Windows User
%                     winopen(OPLSDApath)
%                 elseif ismac
%                     OPLSDApath = fileparts(which('OPLS-DA.html'));
%                     OPLSDApath = [OPLSDApath '/OPLS-DA.html'];
%                     OPLSDApath = ['"' OPLSDApath '"'];
%                     cmdToExecute = ['open ' OPLSDApath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 else
%                     % using xdg-open to open a file in Linux. Some Linux systems might not have
%                     % xdg-open .In that case displaying as error with the file path
%                     OPLSDApath = fileparts(which('OPLS-DA.html'));
%                     OPLSDApath = [OPLSDApath '/OPLS-DA.html'];
%                     OPLSDApath = ['"' OPLSDApath '"'];
%                     cmdToExecute = ['xdg-open ' OPLSDApath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 end   
%             case 'STOCSY'
%                 STOCSYpath = 'GNAT-Manual\docs\_build\html\Analysis Functionalities\Chemometrics\STOCSY.html';
%                 if (ispc) % Windows User
%                     winopen(STOCSYpath)
%                 elseif ismac
%                     STOCSYpath = fileparts(which('STOCSY.html'));
%                     STOCSYpath = [STOCSYpath '/STOCSY.html'];
%                     STOCSYpath = ['"' STOCSYpath '"'];
%                     cmdToExecute = ['open ' STOCSYpath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 else
%                     % using xdg-open to open a file in Linux. Some Linux systems might not have
%                     % xdg-open .In that case displaying as error with the file path
%                     STOCSYpath = fileparts(which('STOCSY.html'));
%                     STOCSYpath = [STOCSYpath '/STOCSY.html'];
%                     STOCSYpath = ['"' STOCSYpath '"'];
%                     cmdToExecute = ['xdg-open ' STOCSYpath];
%                     [status, path] = system(cmdToExecute); %#ok<ASGLU>
%                 end   
%         end
%     end

end