function mat2dcorr(action,CBlockNo)

% mat2dcorr - a MATLAB Toolbox for Performing 2D Correlation Analysis
% last revision: Apr 02, 2023 (Peter Lasch)
% Copyright Peter Lasch 2000-2023. CC-BY-NC license
%
% version 1.00 - Jan 2020
%
% version 1.01 - May 2021
%   *   button for starting the calculation greys out after changing pulldown menu selections 
%       (type of 2D spectrum, type of reference spectrum, etc.)
%   *   bug of the "MouseOver" function of the main window fixed
%   *   standard size of the main window changed
% 
% version 1.02 - May 2021
%   *   fixed a critical error reported by Z. Xinchang - wrong treatment of spectra with non-equidistant 
%       point spacing (function import data in the Matlab trace format)
%
% version 1.03 - Aug 2021
%   *   resizing of the 2D-COS window (main window) possible
%
% version 1.04 - Aug 2023
%   *   import spectral data from MS Excel *.xlsx files
%

%#ok<*NASGU>
%#ok<*NODEF>
%#ok<*COMPNOP>
%#ok<*ASGLU>
%#ok<*ST2NM>    

%%
h.scrsz                             = get(0,'ScreenSize');
h.Cen.All                           = round([h.scrsz(3)/2 h.scrsz(4)/2 0 0]);
h.NumberOfColors                    = 8192;
h.Figure.CorrMat                    = findobj('Tag','CorrMatrixWindow');

if nargin == 0 && isempty(h.Figure.CorrMat) == 0 
    disp('mat2dcorr - another instance of ''mat2dcorr'' is already running ') 
    return
elseif nargin == 0 && isempty(h.Figure.CorrMat) == 1
   action = 'initcorr';
end

if strcmp(action,'initcorr') == 1 && isempty(h.Figure.CorrMat) == 0 
    disp('mat2dcorr - another instance of ''mat2dcorr'' is already running ') 
    return
end

switch action

%% ************************************************************************
case 'initcorr' % initializing the main gui for 2D-COS
% *************************************************************************

initcorplotwin(h);
initcorrcontrolwin;
mat2dcorr('mod2dtype')

%% ************************************************************************
case 'loadx'  % load the x-data for 2D-COS analysis
% *************************************************************************

try
 
h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Button.PlotCM                     = findobj('Tag','plotcorrmatbutton');
h.UIMenu.Xdata                      = findobj('Tag','loadxuimenu');
h.Ctxt.PltCorr                      = findobj('Tag','CMVPlt2Dspec');
h.Ctxt.PltDrx                       = findobj('Tag','CMVPltDerx');
h.Ctxt.PltNdx                       = findobj('Tag','CMVPltNdAttx');
h.Edit.CMY1                         = findobj('Tag','CorrMatYlwnEdit');

if nargin == 2 && CBlockNo < 5
    % loading imaging data in CytoSpec's Matlab format
    [fname,pname]                   = uigetfile('*.mat','load x-Matlab imaging data');
    if isequal(fname,0)
       return
    end
    cd(pname)
    load(fname,'-mat','C','Minfo');
    if exist('C','var') ~= 1 || exist('Minfo','var') ~= 1 
        error('Could not find required information in the file. Check if this is a Matlab file that contains a matrix ''C'' (3D) and a structure array ''Minfo''');
    end
    [xdim, ydim, zdim, dim]         = size(C); 
    if dim >= CBlockNo
        tmp                         = reshape(C(:,:,:,CBlockNo),xdim*ydim,zdim);
        if sum(sum(tmp)) ~= 0
           C                        = squeeze(C(:,:,:,CBlockNo));
        else 
           error('unable to find the requested data block')
        end  
    else    
        error('unable to find the requested data block')
    end
    if isfield(Minfo.File,'TOS') == 1
        tmp                         = Minfo.File.TOS; 
        ind                         = min(strfind(tmp,' '))-1;
        data.tos                    = tmp(1:ind);
        if isempty(ind) == 1
            data.tos                = tmp;
        else   
            data.tos                = tmp(1:ind);
        end
    else   
        data.tos                    = 'unknown';
    end    
    data.xdi                        = str2double(Minfo.File.XDI);
    data.ydi                        = str2double(Minfo.File.YDI);
    data.zdi                        = str2double(Minfo.File.NOD);
    data.lwn                        = str2double(Minfo.File.LWN);
    data.uwn                        = str2double(Minfo.File.UWN);
    data.wvs                        = str2double(Minfo.File.WVS);
    data.wav                        = (data.lwn:data.wvs:(data.uwn+data.wvs/2));
    data.spc                        = reshape(C,[data.xdi*data.ydi data.zdi]);
    data.war                        = '';            
    data.vst                        = 'spatial dimension';
    
elseif nargin == 2 && CBlockNo == 9
    
    % loading trace data in a Matlab data format   
    % in this data format the following variables are assumed:
    % spc - the spectral data, a 2D array of single precision floating point values. Columns indicate individual spectra of absorbance, intensity,
    %       transmittance or other values, the column length indicates the number of data points, number of columns indicates the number of spectra
    % wav - the "wavenumber" vector, or more general the vector of y-values (frequencies, wavenumbers, and others) of the spectra,
    %       should have the same length as size(spec,1), should be increasing, equidistancy is not required
    % tos - type of spectra: a string indicating the type of spectra (transmission, fluoresence, etc)
    % war - the variable in the experiment: temperature, time, voltage. Usually a single precision floating point values of the length size(spc,2). 
    % vst - the variable string such as 'temperature', 'time', 'voltage'      
            
    [fname,pname]                   = uigetfile('*.mat','load x-Excel trace data');
    if isequal(fname,0)
       return
    end
    cd(pname)
    load(fname,'-mat','wav','spc','tos','war','vst')
    if exist('spc','var') ~= 1 || exist('wav','var') ~=1 || exist('tos','var') ~=1 || exist('war','var') ~=1 || exist('vst','var') ~=1 
        error('Could not find required information in the file. Check if this is a Matlab file that contains a matrix ''C'' (3D) and a structure array ''Minfo''');
    end
    % analyzing wav
    lgth                            = length(wav);
    wvrg                            = wav;
    % wav must be a vector of length 'lgth' and increasing 
    if wvrg(1) > wvrg(lgth)
        wvrg                        = flipud(wvrg);
        spc                         = flipud(spc);
    end
    
    % making wav vector equidistant
    wvs                             = (wvrg(lgth)-wvrg(1))/(lgth-1);
    wav                             = wvrg(1):wvs:wvrg(lgth)+wvs/2;
    
    % 1D-interpolation of the spectral intensity data vectors
    spc                             = interp1(wvrg,spc,wav,'linear');

    % flipping dimensions in spc 
    spc                             = permute(spc,[2,1]);
    data.tos                        = tos;
    data.xdi                        = '1';
    data.ydi                        = size(spc,1);
    data.zdi                        = size(spc,2);
    data.lwn                        = wav(1);
    data.uwn                        = wav(lgth);
    data.wvs                        = wvs;
    data.wav                        = wav;
    data.spc                        = spc;
    data.war                        = war;    
    data.vst                        = vst;    

elseif nargin == 2 && CBlockNo == 10

    % loading trace data in an MS Excel data format   
    % MS Excel data contain the spectral data (spc), the wavelength (wav) and the vector with the perturbing variable
    % (war), tos and vst are not contained in MS Excel data files 
    % spc - the spectral data, a 2D array of double precision floating point values. Columns indicate individual spectra of absorbance, intensity,
    %       transmittance or other values, the column length indicates the number of data points, number of columns indicates the number of spectra
    %       In the MS Excel file the spc data are located in columns 2:nspec+1 with nspec being the number of spectra 
    % wav - the "wavenumber" vector, or more general the vector of y-values (frequencies, wavenumbers, and others) of the spectra,
    %       should have the same length as size(spec,1), should be increasing, equidistancy is not required
    %       In the MS Excel file the wav vector is located in the first column
    % tos - not contained in the MS Excel file! Type of spectra: a string indicating the type of spectra (transmission, fluoresence, etc), 
    % war - the variable in the experiment: temperature, time, voltage. Usually a single precision floating point values of the length size(spc,2). 
    %       In the MS Excel file the war vector is located in the first row at positions 2:nspec
    % vst - not contained in the MS Excel file! the variable string such as 'temperature', 'time', 'voltage'

    [fname,pname]                   = uigetfile('*.xlsx','load y-Excel data');
    if isequal(fname,0)
       return
    end
    cd(pname)

    spcdata                         = readtable(fname);
    spcdata                         = table2array(spcdata);
    xdlgth                          = size(spcdata,2);
    ydlgth                          = size(spcdata,1);

    % extract spc from spcdata
    spc                             = spcdata(2:ydlgth,2:xdlgth);

    % extract war from spcdata
    war                             = spcdata(2,2:xdlgth);

    % analyzing wave data (first column of data)
    wavtmp                          = spcdata(2:ydlgth,1);
    lgth                            = length(wavtmp)-1;
    wvrg                            = wavtmp;
    % wav must be a vector of length 'lgth' and increasing 
    if wvrg(1) > wvrg(lgth)
        wvrg                        = flipud(wvrg);
        spc                         = flipud(spc);
    end
    
    % making wav vector equidistant
    wvs                             = (wvrg(lgth)-wvrg(1))/(lgth-1);
    wav                             = wvrg(1):wvs:wvrg(lgth)+wvs/2;
    
    % 1D-interpolation of the spectral intensity data vectors
    spc                             = interp1(wvrg,spc,wav,'linear');

    % flipping dimensions in spc 
    spc                             = permute(spc,[2,1]);
    data.tos                        = 'unknown';
    data.xdi                        = '1';
    data.ydi                        = size(spc,1);
    data.zdi                        = size(spc,2);
    data.lwn                        = wav(1);
    data.uwn                        = wav(lgth);
    data.wvs                        = wvs;
    data.wav                        = wav;
    data.spc                        = spc;
    data.war                        = war;    
    data.vst                        = 'unknown';
   
end

set(h.UIMenu.Xdata,'UserData',data);
rmaxiselements;
actax                               = 'x';
plotavspec(data,actax);

set(h.Ctxt.PltDrx,'Enable','on')
set(h.Ctxt.PltNdx,'Enable','on')

if strcmp(get(h.Edit.CMY1,'Enable'),'on') == 1
    set(h.Button.PlotCM,'Enable','on')
    set(h.Ctxt.PltCorr,'Enable','on')
end

catch
    set(h.UIMenu.Xdata,'UserData',[]);
    rmaxiselements;
    disp('Error in function corrmatrix (corrmatrix(''loadx'') - type ''s = lasterror'' to get more information about this error');
end

%% ************************************************************************
case 'loady' % load the y-data for 2D-COS analysis
% *************************************************************************

try
    
h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Button.PlotCM                     = findobj('Tag','plotcorrmatbutton');
h.UIMenu.Ydata                      = findobj('Tag','loadyuimenu');
h.Ctxt.PltCorr                      = findobj('Tag','CMVPlt2Dspec');
h.Ctxt.PltDry                       = findobj('Tag','CMVPltDery');
h.Ctxt.PltNdy                       = findobj('Tag','CMVPltNdAtty');
h.Edit.CMX1                         = findobj('Tag','CorrMatXlwnEdit');

if nargin == 2 && CBlockNo < 5
    % loading imaging data in CytoSpec's Matlab format
    % Note the equidistant point spacing of the x-vector in CytoSpec's imaging format
    [fname,pname]                   = uigetfile('*.mat','load y-Matlab imaging data');
    if isequal(fname,0)
       return
    end
    cd(pname)
    load(fname,'-mat','C','Minfo');
    if exist('C','var') ~= 1 || exist('Minfo','var') ~= 1 
        error('Could not find required information in the file. Check if this is a Matlab file that contains a matrix ''C'' (3D) and a structure array ''Minfo''');
    end
    [xdim, ydim, zdim, dim] = size(C);
    if dim >= CBlockNo
        tmp                         = reshape(C(:,:,:,CBlockNo),xdim*ydim,zdim);
        if sum(sum(tmp)) ~= 0
           C                        = squeeze(C(:,:,:,CBlockNo));
        else 
           error('unable to find the requested data block')
        end  
    else    
        error('unable to find the requested data block')
    end    
    if isfield(Minfo.File,'TOS') == 1
        tmp                         = Minfo.File.TOS; 
        ind                         = min(strfind(tmp,' '))-1;
        data.tos                    = tmp(1:ind);
        if isempty(ind) == 1
            data.tos                = tmp;
        else   
            data.tos                = tmp(1:ind);
        end
    else   
        data.tos                    = 'unknown';
    end    
    data.xdi                        = str2double(Minfo.File.XDI);
    data.ydi                        = str2double(Minfo.File.YDI);
    data.zdi                        = str2double(Minfo.File.NOD);
    data.lwn                        = str2double(Minfo.File.LWN);
    data.uwn                        = str2double(Minfo.File.UWN);
    data.wvs                        = str2double(Minfo.File.WVS);
    data.wav                        = (data.lwn:data.wvs:(data.uwn+data.wvs/2));
    data.spc                        = reshape(C,[data.xdi*data.ydi data.zdi]);
    data.war                        = '';            
    data.vst                        = 'spatial dimension';
    
elseif nargin == 2 && CBlockNo == 9    
    % loading trace data in a Matlab data format   
    % in this data format the following variables are assumed:
    % spc - the spectral data, a 2D array of single precision floating point values. Columns indicate individual spectra of absorbance, intensity,
    %       transmittance or other values, the column length indicates the number of data points, number of columns indicates the number of spectra
    % wav - the "wavenumber" vector, or more general the vector of y-values (frequencies, wavenumbers, and others) of the spectra,
    %       should have the same length as size(spec,1), should be increasing, equidistancy is not required
    % tos - type of spectra: a string indicating the type of spectra (transmission, fluoresence, etc)
    % war - the variable in the experiment: temperature, time, voltage. Usually a single precision floating point values of the length size(spc,2). 
    % vst - the variable string such as 'temperature', 'time', 'voltage'      
            
    [fname,pname]                   = uigetfile('*.mat','load y-Matlab trace data');
    if isequal(fname,0)
       return
    end
    cd(pname)
    load(fname,'-mat','wav','spc','tos','war','vst')
    if exist('spc','var') ~= 1 || exist('wav','var') ~=1 || exist('tos','var') ~=1 || exist('war','var') ~=1 || exist('vst','var') ~=1 
        error('Could not find required information in the file. Check if this is a Matlab file that contains a matrix ''C'' (3D) and a structure array ''Minfo''');
    end
    % analyzing wav
    lgth                            = length(wav);
    wvrg                            = wav;
    % wav must be a vector of length 'lgth' and increasing 
    if wvrg(1) > wvrg(lgth)
        wvrg                        = flipud(wvrg);
        spc                         = flipud(spc);
    end
    
    % making wav vector equidistant
    wvs                             = (wvrg(lgth)-wvrg(1))/(lgth-1);
    wav                             = wvrg(1):wvs:wvrg(lgth)+wvs/2;
    
    % 1D-interpolation of the spectral intensity data vectors
    spc                             = interp1(wvrg,spc,wav,'linear');

    % flipping dimensions in spc 
    spc                             = permute(spc,[2,1]);

    data.tos                        = tos;
    data.xdi                        = '1';
    data.ydi                        = size(spc,1);
    data.zdi                        = size(spc,2);
    data.lwn                        = wav(1);
    data.uwn                        = wav(lgth);
    data.wvs                        = wvs;
    data.wav                        = wav;
    data.spc                        = spc;
    data.war                        = war;    
    data.vst                        = vst;

elseif nargin == 2 && CBlockNo == 10

    % loading trace data in an MS Excel data format   
    % MS Excel data contain the spectral data (spc), the wavelength (wav) and the vector with the perturbing variable
    % (war), tos and vst are not contained in MS Excel data files 
    % spc - the spectral data, a 2D array of double precision floating point values. Columns indicate individual spectra of absorbance, intensity,
    %       transmittance or other values, the column length indicates the number of data points, number of columns indicates the number of spectra
    %       In the MS Excel file the spc data are located in columns 2:nspec+1 with nspec being the number of spectra 
    % wav - the "wavenumber" vector, or more general the vector of y-values (frequencies, wavenumbers, and others) of the spectra,
    %       should have the same length as size(spec,1), should be increasing, equidistancy is not required
    %       In the MS Excel file the wav vector is located in the first column
    % tos - not contained in the MS Excel file! Type of spectra: a string indicating the type of spectra (transmission, fluoresence, etc), 
    % war - the variable in the experiment: temperature, time, voltage. Usually a single precision floating point values of the length size(spc,2). 
    %       In the MS Excel file the war vector is located in the first row at positions 2:nspec
    % vst - not contained in the MS Excel file! the variable string such as 'temperature', 'time', 'voltage'

    [fname,pname]                   = uigetfile('*.xlsx','load y-Matlab data');
    if isequal(fname,0)
       return
    end
    cd(pname)

    spcdata                         = readtable(fname);
    spcdata                         = table2array(spcdata);
    xdlgth                          = size(spcdata,2);
    ydlgth                          = size(spcdata,1);

    % extract spc from spcdata
    spc                             = spcdata(2:ydlgth,2:xdlgth);

    % extract war from spcdata
    war                             = spcdata(2,2:xdlgth);

    % analyzing wave data (first column of data)
    wavtmp                          = spcdata(2:ydlgth,1);
    lgth                            = length(wavtmp)-1;
    wvrg                            = wavtmp;
    % wav must be a vector of length 'lgth' and increasing 
    if wvrg(1) > wvrg(lgth)
        wvrg                        = flipud(wvrg);
        spc                         = flipud(spc);
    end
    
    % making wav vector equidistant
    wvs                             = (wvrg(lgth)-wvrg(1))/(lgth-1);
    wav                             = wvrg(1):wvs:wvrg(lgth)+wvs/2;
    
    % 1D-interpolation of the spectral intensity data vectors
    spc                             = interp1(wvrg,spc,wav,'linear');

    % flipping dimensions in spc 
    spc                             = permute(spc,[2,1]);
    data.tos                        = 'unknown';
    data.xdi                        = '1';
    data.ydi                        = size(spc,1);
    data.zdi                        = size(spc,2);
    data.lwn                        = wav(1);
    data.uwn                        = wav(lgth);
    data.wvs                        = wvs;
    data.wav                        = wav;
    data.spc                        = spc;
    data.war                        = war;    
    data.vst                        = 'unknown';
   
end

set(h.UIMenu.Ydata,'UserData',data);
rmaxiselements
actax                               = 'y';
plotavspec(data,actax);

set(h.Ctxt.PltDry,'Enable','on');
set(h.Ctxt.PltNdy,'Enable','on')

if strcmp(get(h.Edit.CMX1,'Enable'),'on') == 1
    set(h.Button.PlotCM,'Enable','on')
    set(h.Ctxt.PltCorr,'Enable','on')
end

catch
    set(h.UIMenu.Ydata,'UserData',[]);
    rmaxiselements
    disp('Error in function corrmatrix (''corrmatrix(''loady'')'' - type ''s = lasterror'' to get more information about this error');
end

%% ************************************************************************
case 'do2danalysis' % do the 2D-COS: plot 2D spectrum  
% *************************************************************************

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Axis.specx                        = findobj('Tag','AxisXSpec');
h.Axis.specy                        = findobj('Tag','AxisYSpec');
h.Button.PlotCLim                   = findobj('Tag','setCLimbutton');
h.UIMenu.Xdata                      = findobj('Tag','loadxuimenu');
h.UIMenu.Ydata                      = findobj('Tag','loadyuimenu');
h.Button.PlotCM                     = findobj('Tag','plotcorrmatbutton');
h.Checkbox.CorrMContr               = findobj('Tag','CorrMatContourCheckbox');
h.Checkbox.FillContour              = findobj('Tag','CorrMatFillContourCheckbox');
h.Ctxt.GtImg                        = findobj('Tag','CMVgetImg');
h.Ctxt.GtColb                       = findobj('Tag','CMVColbar');
h.Ctxt.MaxCov                       = findobj('Tag','CMVdspmaxcov');
h.Ctxt.PltCorr                      = findobj('Tag','CMVPlt2Dspec');
h.Menu.CMVgetxtrc                   = findobj('Tag','CMVgetxtrc');
h.Menu.CMVgetytrc                   = findobj('Tag','CMVgetytrc');
h.Menu.CMVgetcorr                   = findobj('Tag','CMVgetcorr');
h.Menu.CMVupdplt                    = findobj('Tag','CMVupdplt');
h.Ctxt.invCmap                      = findobj('Tag','CMVinvCmap');
h.Edit.CMX1                         = findobj('Tag','CorrMatXlwnEdit');
h.Edit.CMX2                         = findobj('Tag','CorrMatXuwnEdit');
h.Edit.CMY1                         = findobj('Tag','CorrMatYlwnEdit');
h.Edit.CMY2                         = findobj('Tag','CorrMatYuwnEdit');
h.Edit.CLim1                        = findobj('Tag','CorrMatCLim1Edit');
h.Edit.CLim2                        = findobj('Tag','CorrMatCLim2Edit');
h.Edit.Xtrace                       = findobj('Tag','CorrMatXtraceEdit');
h.Edit.Ytrace                       = findobj('Tag','CorrMatYtraceEdit');
h.Figure.CorrMatrix                 = findobj('Tag','CorrMatrixWindow');
h.Figure.ControlWindow              = findobj('Tag','CorrmControlWindow');
h.Popup.Colormap2DCO                = findobj('Tag','Colormap2DCOSPopupmenu'); 
h.Popupmenu.Type2DCOS               = findobj('Tag','Type2DCOSPopupmenu');

% type of 2D spectrum to be produced
tp                                  = get(h.Popupmenu.Type2DCOS,'Value');   % tp - value of the type of the 2D-COS function to be generated
tpcmplstr                           = get(h.Popupmenu.Type2DCOS,'String');  % tp - full string of the type of the 2D-COS function to be generated
tpstr                               = tpcmplstr(tp,:);                      % tpstr - the extracted string of the 2D-COS function
pltctr                              = get(h.Checkbox.CorrMContr,'Value');   % pltctr = 1: plots a surface map, otherwise a contor map is produced

if tp == 1
    method                          = 'corr';
elseif tp == 2
    method                          = 'Pareto-0.75';
elseif tp == 3
    method                          = 'Pareto-0.50';
elseif tp == 4
    method                          = 'Pareto-0.25';
elseif tp == 5
    method                          = 'covar';
elseif tp == 6
    method                          = 'cvasyn';
elseif tp == 7
    method                          = 'disrel';
elseif tp == 8
    method                          = 'sync';
elseif tp == 9
    method                          = 'async';
else
    error('undefined value for ''tp'' (type of 2D spectrum)')
end    

x1                                  = str2double(get(h.Edit.CMX1,'String'));% start wvn value for spectral region x
x2                                  = str2double(get(h.Edit.CMX2,'String'));% end  wvn value for spectral region x
y1                                  = str2double(get(h.Edit.CMY1,'String'));% start wvn value for spectral region y
y2                                  = str2double(get(h.Edit.CMY2,'String'));% end wvn value for spectral region y
datax                               = get(h.UIMenu.Xdata,'UserData');       % datax - a structure array with the fields tos, xdi ydi, zdi, lwn, uwn, wvs, wav, spc, war, vst 
datax.xydim                         = datax.xdi * datax.ydi;                % number of spectra in x
datay                               = get(h.UIMenu.Ydata,'UserData');       % datay - a structure array with the fields tos, xdi ydi, zdi, lwn, uwn, wvs, wav, spc, war, vst  
datay.xydim                         = datay.xdi * datay.ydi;                % number of spectra in y 
cmapstr                             = get(h.Popup.Colormap2DCO,'String');
cmapval                             = get(h.Popup.Colormap2DCO,'Value');
cmap                                = strrep(cmapstr(cmapval,:),' ','');    % the colormap used (string) 
cmap                                = colormap(cmap);                       % the colormap used (numeric)

if isnumeric([x1 x2 y1 y2]) == 0 || any(isnan([x1 x2 y1 y2]))==1 || any(isinf([x1 x2 y1 y2]))== 1 
   error('Error: x1 (or y1) must not equal zero and cannot be NaN''s of Inf''s');
elseif x1 >= x2 || y1 >= y2
   error('Error: x1 (or y1) must not be larger than x2 (or y2) respectively');
elseif datax.xydim ~= datay.xydim 
   set(h.Ctxt.PltCorr,'Enable','off')
   set(h.Button.PlotCLim,'Enable','off')
   error('Error: the number of [x,y] pixel spectra in the hetero-hyperspectral maps must be equal');
end   

set(h.Figure.ControlWindow,'Pointer','watch');
set(h.Figure.CorrMatrix,'Pointer','watch','WindowStyle','modal','Colormap',cmap);
disp(['starting 2D-COS analysis (' method ') - this may take a while'])
xpts                                = round(([x1 x2]-datax.lwn)/datax.wvs + 1); % xpts - indices of x1 and x2 in x-wave
if xpts(1) < 1 
   xpts(1)                          = 1;
   set(h.Edit.CMX1,'String',num2str(datax.lwn));
end
if xpts(2) > datax.zdi
   xpts(2)                          = datax.zdi;
   set(h.Edit.CMX2,'String',num2str(datax.uwn));
end   
datax.red                           = datax.spc(:,xpts(1):xpts(2));         % the spectral data in x
datax.zdi                           = xpts(2)-xpts(1)+1;                    % number of spectral data points in x
datax.nwv                           = datax.wav(xpts(1):1:xpts(2));         % x-wave
ypts                                = round(([y1 y2]-datay.lwn)/datay.wvs + 1); % ypts - indices of y1 and y2 in y-wave
if ypts(1) < 1 
   ypts(1)                          = 1;
   set(h.Edit.CMY1,'String',num2str(datay.lwn));
end   
if ypts(2) > datay.zdi
   ypts(2)                          = datay.zdi;
   set(h.Edit.CMY2,'String',num2str(datay.uwn));
end
datay.red                           = datay.spc(:,ypts(1):ypts(2));         % the spectral data in x
datay.zdi                           = ypts(2)-ypts(1)+1;                    % number of spectral data points in x
datay.nwv                           = datay.wav(ypts(1):1:ypts(2));         % x-wave

% remove NaN's from datax.red --> spcx and datay.red --> spcy 
nanx                                = isnan(datax.red(:,1));
nany                                = isnan(datay.red(:,1));
nans                                = ~(nanx | nany);
spcx                                = datax.red(nans,:);
spcy                                = datay.red(nans,:);

% calling the real 2D COSY function (subfunction of mat2dcorr
CorrMat                             = twoDCOSY(spcx,spcy,method);

% obtaining min and max values from the 2D spectrum --> required for autoscaling
CLim1                               = min(min(CorrMat));
CLim2                               = max(max(CorrMat));

set(0,'currentfigure',h.Figure.CorrMatrix);
set(h.Axis.Corr,'XLim', datax.wav(xpts),'YLim', datay.wav(ypts),'CLim',[CLim1 CLim2]);

% the following lines are required for plotting the average spectra in x and y
h.xline                             = get(h.Axis.specx,'Children'); 
xspec                               = get(h.xline,'YData');
xspecmin                            = min(xspec(xpts(1):xpts(2)));
xspecmax                            = max(xspec(xpts(1):xpts(2)));
deltax                              = (xspecmax-xspecmin)/10;
h.yline                             = get(h.Axis.specy,'Children'); 
yspec                               = get(h.yline,'XData');
yspecmin                            = min(yspec(ypts(1):ypts(2)));
yspecmax                            = max(yspec(ypts(1):ypts(2)));
deltay                              = (yspecmax-yspecmin)/10;
cmenu2d                             = uicontextmenu;

set(h.Axis.specx,'XLim', datax.wav(xpts),'YLim',[xspecmin-deltax xspecmax+deltax]);
set(h.Axis.specy,'YLim', datay.wav(ypts),'XLim',[yspecmin-deltay yspecmax+deltay]);

CorrMatr.data                       = CorrMat;                              % the 2D-COS function
CorrMatr.xwv                        = datax.nwv;                            % x-wave
CorrMatr.ywv                        = datay.nwv;                            % y-wave
CorrMatr.spcx                       = spcx;                                 % x-spectral data
CorrMatr.spcy                       = spcy;                                 % y-spectral data
CorrMatr.info                       = tpstr;                                % type of the 2D-COS function (string: sync, async, etc.) 
CorrMatr.xpts                       = xpts;                                 % xpts - indices of x1 and x2 in x-wave
CorrMatr.ypts                       = ypts;                                 % xyts - indices of y1 and y2 in y-wave

set(h.Button.PlotCM,'UserData',CorrMatr);
set(h.Button.PlotCLim,'Enable','on');
set(h.Ctxt.GtImg,'Enable','on')
set(h.Ctxt.GtColb,'Enable','on')
set(h.Ctxt.MaxCov ,'Enable','on');
set(h.Checkbox.CorrMContr,'Enable','on');
set(h.Checkbox.FillContour,'Enable','on');
set(h.Menu.CMVgetxtrc,'Enable','on')
set(h.Menu.CMVgetytrc,'Enable','on')
set(h.Menu.CMVgetcorr,'Enable','on')
set(h.Menu.CMVupdplt,'Enable','on')
set(h.Ctxt.invCmap,'Enable','on')
set(h.Edit.CLim1,'String',num2str(CLim1),'Enable','on');
set(h.Edit.CLim2,'String',num2str(CLim2),'Enable','on');
set(h.Edit.Xtrace,'Enable','on','String',num2str(x1));
set(h.Edit.Ytrace,'Enable','on','String',num2str(y1));

if pltctr == 0 % internal function for plotting a surface map
    pltsrffun;
else           % internal function for plotting a contour map
    pltctrfun;
end

set(h.Figure.ControlWindow,'Pointer','arrow');
set(h.Figure.CorrMatrix,'Pointer','arrow','WindowStyle','normal');
set(h.Axis.Corr,'UIContextMenu',cmenu2d);
uimenu(cmenu2d,'label','plot x-slice','Tag','CMVgetytrc','Callback','mat2dcorr(''getxtrace'')');
uimenu(cmenu2d,'label','plot y-slice','Tag','CMVgetxtrc','Callback','mat2dcorr(''getytrace'')');
uimenu(cmenu2d,'label','plot [x,y] spectral features','Tag','CMVgetcorr','Callback','mat2dcorr(''getcorrdata'')');

%% ************************************************************************
case 'getextr2d' % get extreme (min/max) values and the respective [x,y] coordinates of the 2D-COS spectrum
% *************************************************************************

CorrMatr                                = get(findobj('Tag','plotcorrmatbutton'),'UserData');
numpks                                  = 15;

lgthx                                   = length(CorrMatr.xwv);
lgthy                                   = length(CorrMatr.ywv);
lgth                                    = lgthx*lgthy;
tmp                                     = reshape(CorrMatr.data,[lgth,1]);
[rmax,ind]                              = sort(tmp);

rplus                                   = rmax(lgth:-1:lgth-numpks);
indplus                                 = ind(lgth:-1:lgth-numpks);
rminus                                  = rmax(1:numpks);
indminus                                = ind(1:numpks);
  
xdimplus                                = floor((indplus-1)/lgthy)+1; 
ydimplus                                = round(((indplus-1)/lgthy -(xdimplus-1))*lgthy)+1;
xdimminus                               = floor((indminus-1)/lgthy)+1;
ydimminus                               = round(((indminus-1)/lgthy -(xdimminus-1))*lgthy)+1;

disp('*************************************************************')
disp('* max values and [x,y] coordinates of the 2D-COS spectrum:   *')
disp('*************************************************************')
for i=1:numpks
  disp(['#' num2str(i) ', 2D function value of ''' num2str(rplus(i))  ''' found at [x,y] wavenumber coordinates [' num2str(CorrMatr.xwv(xdimplus(i))) ', ' num2str(CorrMatr.ywv(round(ydimplus(i)))) ']' ])
end
disp('*************************************************************')
disp('* min values and [x,y] coordinates of the 2D-COS spectrum:   *')
disp('*************************************************************')
for i=1:numpks
    disp(['#' num2str(i) ', 2D function value of ''' num2str(rminus(i))  ''' found at [x,y] wavenumber coordinates [' num2str(CorrMatr.xwv(xdimminus(i))) ', ' num2str(CorrMatr.ywv(round(ydimminus(i)))) ']' ])
end

%% ************************************************************************
case 'getxtrace'
% *************************************************************************

h.Button.PltCmax                    = findobj('Tag','plotcorrmatbutton');
h.Edit.Xtrace                       = findobj('Tag','CorrMatXtraceEdit');
h.Edit.Ytrace                       = findobj('Tag','CorrMatYtraceEdit');
h.Edit.CMX1                         = findobj('Tag','CorrMatXlwnEdit');
h.Edit.CMX2                         = findobj('Tag','CorrMatXuwnEdit');

% load color definitions from function cols
[bg,bgf,bge,bgb,fgt,fgr,fgb,bgs]    = cols;

pos(3:4)                            = [800 500];
pos(1:2)                            = [h.Cen.All(1)-pos(3)/2 h.Cen.All(2)-pos(4)/2];
axpos                               = [30 30 pos(3)-40 pos(4)-55];
view                                = [0, 90];

CorrMatr                            = get(h.Button.PltCmax,'UserData');
y                                   = str2double(get(h.Edit.Ytrace,'String'));
x1                                  = str2double(get(h.Edit.CMX1,'String'));
x2                                  = str2double(get(h.Edit.CMX2,'String'));
distx                               = (x2-x1)/20;

% finding the most similar value to y in CorrMatr.ywv
ywvmin                              = abs(CorrMatr.ywv-y);
[tmp,ind]                           = min(ywvmin);
y                                   = CorrMatr.ywv(ind);

trace                               = CorrMatr.data(ind,:);
wave                                = CorrMatr.xwv;
y1                                  = min(trace);
y2                                  = max(trace);
disty                               = (y2-y1)/10;

h0                                  = figure('NumberTitle','off','Name',['x-trace @ y = [' num2str(y) '] - ' CorrMatr.info],'Units','pixel','Position',pos,'Color',bg, ...
                                             'MenuBar','non','Resize','off','CloseRequestFcn','delete(gcf)','Tag','1DtracePlot');
cmenuspc                            = uicontextmenu;
h1                                  = axes('Parent',h0,'Units','pixel','NextPlot','ReplaceChildren','HandleVisibility','on','Interruptible','off','Box','on','CameraUpVector',[0 1 0], ...
   	                                       'Position',axpos,'CameraUpVectorMode','manual','SelectionHighlight','off','Visible','on','UIContextMenu',cmenuspc,'Tag','AxisCspectra');
h2                                  = uicontrol('Parent',h0,'Units','pixel','String','wavenumber position: ','Position',[520,477,200 18],'Style','Text','Tag','TraceWvnPos');
setAxisFormat(h1,bge,[x1-distx x2+distx],[y1-disty y2+disty],view)
setTextFormat(h2,bg,fgt);
plot(wave,trace);

% context menu to store the spectra
item(1)                             = uimenu(cmenuspc,'label','store x-trace (ASCII)','Callback','mat2dcorr(''storespc'');','Tag','ContextCspc');
item(2)                             = uimenu(cmenuspc,'label','display wavenumber position');
item(3)                             = uimenu(item(2),'label','on','Callback','set(gcf,''WindowButtonMotionFcn'',''updcorrplt(10)'')');
item(4)                             = uimenu(item(2),'label','off','Callback','set(gcf,''WindowButtonMotionFcn'','''');set(findobj(''Tag'',''TraceWvnPos''),''String'',''wavenumber position: '')'); 

%% ************************************************************************
case 'getytrace'
% *************************************************************************

h.Button.PltCmax                    = findobj('Tag','plotcorrmatbutton');
h.Edit.Xtrace                       = findobj('Tag','CorrMatXtraceEdit');
h.Edit.Ytrace                       = findobj('Tag','CorrMatYtraceEdit');
h.Edit.CMY1                         = findobj('Tag','CorrMatYlwnEdit');
h.Edit.CMY2                         = findobj('Tag','CorrMatYuwnEdit');

% load color definitions from function cols
[bg,bgf,bge,bgb,fgt,fgr,fgb,bgs]    = cols;
pos(3:4)                            = [800 500];
% pos(3:4) = [400 250];
pos(1:2)                            = [h.Cen.All(1)-pos(3)/2 h.Cen.All(2)-pos(4)/2];
axpos                               = [30 30 pos(3)-40 pos(4)-55];
view                                = [0, 90];

CorrMatr                            = get(h.Button.PltCmax,'UserData');
x                                   = str2double(get(h.Edit.Xtrace,'String'));
x1                                  = str2double(get(h.Edit.CMY1,'String'));
x2                                  = str2double(get(h.Edit.CMY2,'String'));
distx                               = (x2-x1)/20;

% finding the most similar value to x in CorrMatr.xwv
xwvmin                              = abs(CorrMatr.xwv-x);
[tmp,ind]                           = min(xwvmin);
x                                   = CorrMatr.xwv(ind);

trace                               = CorrMatr.data(:,ind);
wave                                = CorrMatr.ywv;

y1                                  = min(trace);
y2                                  = max(trace);
disty                               = (y2-y1)/10;

h0                                  = figure('NumberTitle','off','Name',['y-trace @ [x = ' num2str(x) '] - ' CorrMatr.info],'Units','pixel','Position',pos,'Color',bg, ...
                                             'MenuBar','non','Resize','off','CloseRequestFcn','delete(gcf)','Tag','1DtracePlot');
cmenuspc                            = uicontextmenu;
h1                                  = axes('Parent',h0,'Units','pixel','NextPlot','add','HandleVisibility','on','Interruptible','off','Box','on','CameraUpVector',[0 1 0], ...
   	                                       'Position',axpos,'CameraUpVectorMode','manual','SelectionHighlight','off','Visible','on','UIContextMenu',cmenuspc,'Tag','AxisCspectra');
h2                                  = uicontrol('Parent',h0,'Units','pixel','String','wavenumber position: ','Position',[520,477,200 18],'Style','Text','Tag','TraceWvnPos');
setAxisFormat(h1,bge,[x1-distx x2+distx],[y1-disty y2+disty],view)
setTextFormat(h2,bg,fgt);
plot(wave,trace)

% context menu to store the spectra
item(1)                             = uimenu(cmenuspc,'label','store y-trace (ASCII)','Callback','mat2dcorr(''storespc'');','Tag','ContextCspc');
item(2)                             = uimenu(cmenuspc,'label','display wavenumber position');
item(3)                             = uimenu(item(2),'label','on','Callback','set(gcf,''WindowButtonMotionFcn'',''updcorrplt(10)'')');
item(4)                             = uimenu(item(2),'label','off','Callback','set(gcf,''WindowButtonMotionFcn'','''');set(findobj(''Tag'',''TraceWvnPos''),''String'',''wavenumber position: '')');

%% ************************************************************************
case 'storespc'
% *************************************************************************

h1                                  = get(gca,'Children');
h2                                  = findobj(h1,'Type','Line','-or','Type','hggroup');
data                                = get(h2,'XData');
data(2,:)                           = get(h2,'YData');

data                                = flipud(rot90(data));
[SaveFile,SavePath]                 = uiputfile('*.dat','storing 2D-COS spectra traces');
if ischar(SaveFile) == 1  
   cd(SavePath);
   if length(SaveFile) > 4 && strcmp(SaveFile(length(SaveFile)-3:length(SaveFile)),'.dat') == 1
      SaveFile = SaveFile(1:length(SaveFile)-4);
   end   
   fid                              = fopen([SaveFile '.dat'], 'wt');
   [~,W]                            = size(data);
   fprintf(fid,[repmat('%-16.12f\t',1,W) '\n'],data.');
   fclose(fid);
end

%% ************************************************************************
case 'storexmean'
% *************************************************************************

h.Axis.specx                        = findobj('Tag','AxisXSpec');
xspec                               = get(h.Axis.specx,'UserData')';

[SaveFile,SavePath]                 = uiputfile('*.dat','storing x-mean spectrum');
if ischar(SaveFile) == 1  
   cd(SavePath);
   if length(SaveFile) > 4 && strcmp(SaveFile(length(SaveFile)-3:length(SaveFile)),'.dat') == 1
      SaveFile                      = SaveFile(1:length(SaveFile)-4);
   end   
   fid                              = fopen([SaveFile '.dat'], 'wt');
   [~,W]                            = size(xspec);
   fprintf(fid,[repmat('%-16.12f\t',1,W) '\n'],xspec.');
   fclose(fid);
end

%% ************************************************************************
case 'storeymean'
% *************************************************************************

h.Axis.specy                        = findobj('Tag','AxisYSpec');
yspec                               = get(h.Axis.specy,'UserData')';

[SaveFile,SavePath]                 = uiputfile('*.dat','storing y-mean spectrum');
if ischar(SaveFile) == 1  
   cd(SavePath);
   if length(SaveFile) > 4 && strcmp(SaveFile(length(SaveFile)-3:length(SaveFile)),'.dat') == 1
      SaveFile                      = SaveFile(1:length(SaveFile)-4);
   end   
   fid                              = fopen([SaveFile '.dat'], 'wt');
   [~,W]                            = size(yspec);
   fprintf(fid,[repmat('%-16.12f\t',1,W) '\n'],yspec.');
   fclose(fid);
end

%% ************************************************************************
case 'getcorrdata' % extract & plot underlying spectral features 
% *************************************************************************

% obtain underlying spectral data to plot the correlation chart y = f(x)

% load color definitions from functions cols 
[bg,bgf,bge,bgb,fgt,fgr,fgb,bgs]    = cols;
pos(3:4)                            = [600 600];
pos(1:2)                            = [h.Cen.All(1)-pos(3)/2 h.Cen.All(2)-pos(4)/2];
axpos                               = [30 30 pos(3)-40 pos(4)-55];

h.Edit.Xtrace                       = findobj('Tag','CorrMatXtraceEdit');
h.Edit.Ytrace                       = findobj('Tag','CorrMatYtraceEdit');

x                                   = str2double(get(h.Edit.Xtrace,'String'));
y                                   = str2double(get(h.Edit.Ytrace,'String'));
%cmenuspc = uicontextmenu;

h.Button.PltCmax                    = findobj('Tag','plotcorrmatbutton');
CorrMatr                            = get(h.Button.PltCmax,'UserData');

% finding the most similar value to x in CorrMat.xwv
xwvmin                              = abs(CorrMatr.xwv-x);
[tmp,xind]                          = min(xwvmin);
x                                   = CorrMatr.xwv(xind);
% finding the most similar value to y in CorrMat.ywv
ywvmin                              = abs(CorrMatr.ywv-y);
[tmp,yind]                          = min(ywvmin);
y                                   = CorrMatr.ywv(yind);

trace                               = CorrMatr.spcx(:,xind);
trace(:,2)                          = CorrMatr.spcy(:,yind);

x1                                  = min(trace(:,1));
x2                                  = max(trace(:,1));
distx                               = (x2-x1)/10;

y1                                  = min(trace(:,2));
y2                                  = max(trace(:,2));
disty                               = (y2-y1)/10;

h0                                  = figure('NumberTitle','off','Name',['x @ [' num2str(x) '] vs. y @ [' num2str(y) ']'],'Units','pixel','Position',pos,'Color',bg, ...
                                             'MenuBar','non','Resize','off','CloseRequestFcn','delete(gcf)','Tag','PlotXYfeatures');
cmenusca                            = uicontextmenu;
h1                                  = axes('Parent',h0,'Units','pixel','NextPlot','ReplaceChildren','HandleVisibility','on','Interruptible','off','Box','on', ...
   	                                       'Position',axpos,'SelectionHighlight','off','UIContextMenu',cmenusca,'Tag','AxisCspectra');
setAxisFormat(h1,bge,[x1-distx x2+distx],[y1-disty y2+disty]);
set(h1,'View',[0 90]);
scatter(trace(:,1),trace(:,2),3);

% context menu to store the data
uimenu(cmenusca,'label','store data (ASCII)','Tag','ContextCspc','Callback','mat2dcorr(''storespc'');');

%% ************************************************************************
case 'setCLim' % re-set the colormap of the axis 'AxisCorrelation'
% *************************************************************************

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Edit.CLim1                        = findobj('Tag','CorrMatCLim1Edit');
h.Edit.CLim2                        = findobj('Tag','CorrMatCLim2Edit');
h.Figure.CorrMatrix                 = findobj('Tag','CorrMatrixWindow');
h.Popup.Colormap2DCO                = findobj('Tag','Colormap2DCOSPopupmenu'); 

CLim1                               = str2double(get(h.Edit.CLim1,'String'));
CLim2                               = str2double(get(h.Edit.CLim2,'String'));
cmapstr                             = get(h.Popup.Colormap2DCO,'String');
cmapval                             = get(h.Popup.Colormap2DCO,'Value');
cmap                                = strrep(cmapstr(cmapval,:),' ','');
cmap                                = colormap(cmap);

if isnumeric([CLim1 CLim2]) == 0 || any(isnan([CLim1 CLim2]))==1 || any(isinf([CLim1 CLim2]))== 1 
   error('Error in function corrmatrix: wrong CLim values for colormap');
elseif CLim1 == CLim2
   error('Error in function corrmatrix: wrong CLim values for colormap');
elseif CLim1 > CLim2
   set(h.Figure.CorrMatrix,'Colormap',flipud(cmap));
   set(h.Axis.Corr,'CLim',[CLim2 CLim1])
   set(h.Edit.CLim1,'String', num2str(CLim2));
   set(h.Edit.CLim2,'String', num2str(CLim1));
elseif CLim1 < CLim2
   set(h.Figure.CorrMatrix,'Colormap',cmap);
   set(h.Axis.Corr,'CLim',[CLim1 CLim2])
else
   error('Error in function corrmatrix: wrong CLim values for colormap');
end   

%% ************************************************************************
case 'invcmap' % invert the colormap of the current figure
% *************************************************************************

h.Figure.CorrMat                    = findobj('Tag','CorrMatrixWindow');
cmap                                = get(h.Figure.CorrMat,'Colormap');
cmap                                = flipud(cmap);
set(h.Figure.CorrMat,'Colormap',cmap);

%% ************************************************************************
case 'setxypos' % plot x- and y-trace positions into edit fields
% *************************************************************************

if strcmp(get(gcf,'SelectionType'),'normal') == 0
   % right mouse button was clicked
   return
end

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Edit.Xtrace                       = findobj('Tag','CorrMatXtraceEdit');
h.Edit.Ytrace                       = findobj('Tag','CorrMatYtraceEdit');
h.Figure.CorrMat                    = findobj('Tag','CorrmatrixWindow');
    
% get coordinates:
pts                                 = round(get(h.Axis.Corr,'CurrentPoint'));
XLim                                = get(h.Axis.Corr,'XLim');
YLim                                = get(h.Axis.Corr,'YLim');

if pts(1,1) >= XLim(1) && pts(1,1) <= XLim(2) &&  pts(2,2) >= YLim(1) && pts(2,2) <= YLim(2)
   set(h.Edit.Xtrace,'String',num2str(pts(1,1)));
   set(h.Edit.Ytrace,'String',num2str(pts(2,2)));
end
      
%% ************************************************************************
case 'mod2dtype' % modify the type of the gui used for 2D-COS
% *************************************************************************

gcbotagstr                          = get(gcbo,'Tag');
if strfind(gcbotagstr,'CMVupdplton') == 1
    dsplyint                        = 1;
elseif strfind(gcbotagstr,'CMVupdpltoff') == 1 % || strfind(gcbotagstr,'Type2DCOSPopupmenu') == 1 || strfind(gcbotagstr,'Refspec2DCOSPopupmenu') == 1
    dsplyint                        = 0;
    updcorrplt(0);
% elseif strfind(gcbotagstr,'Type2DCOSPopupmenu') == 1 % || strfind(gcbotagstr,'Refspec2DCOSPopupmenu') == 1
%     dsplyint = 0;
%     updcorrplt(0);
else
    dsplyint                        = 0;
    updcorrplt(0);
    rmaxiselements;    
end

h.Button.PlotCM                     = findobj('Tag','plotcorrmatbutton');
h.Figure.CorrMat                    = findobj('Tag','CorrMatrixWindow');
h.Popupmenu.Type2DCOS               = findobj('Tag','Type2DCOSPopupmenu');
tp                    = get(h.Popupmenu.Type2DCOS,'Value');

% prepare the 2D-COS figure to plot a correlation coefficient spectrum (Pearson scaling)
if tp == 1
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','Pearson 1.0');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(1)','Visible','on','Name','2D correlation analysis: Pearson scaling');
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: Pearson scaling');
    end

% prepare the 2D-COS figure to plot a Pareto 0.75 scaling spectrum
elseif tp == 2
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','Pareto 0.75');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(2)','Visible','on','Name','2D correlation analysis: Pareto scaling 0.75');
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: Pareto scaling 0.75');
    end
    
% prepare the 2D-COS figure to plot a Pareto 0.50 scaling spectrum
elseif tp == 3
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','Pareto 0.50');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(3)','Visible','on','Name','2D correlation analysis: Pareto scaling 0.50');
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: Pareto scaling 0.50');
    end
    
% prepare the 2D-COS figure to plot a Pareto 0.25 scaling spectrum
elseif tp == 4
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','Pareto 0.25');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(4)','Visible','on','Name','2D correlation analysis: Pareto scaling 0.25');
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: Pareto scaling 0.25');
    end
    
% prepare the 2D-COS figure to plot a covar 1.0 coefficient spectrum
elseif tp == 5
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','stat sync');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(5)','Visible','on','Name','2D correlation analysis: synchronous spectrum (statistical method)')
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: synchronous spectrum (statistical method)');
    end

% prepare the 2D-COS figure to plot a covar asynchronous spectrum
elseif tp == 6
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','stat async');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(6)','Visible','on','Name','2D correlation analysis: asynchronous spectrum (statistical method)')
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: asynchronous spectrum (statistical method)');
    end
    
% prepare the 2D-COS figure to plot a disrelation 2D spectrum
elseif tp == 7
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','disrelation');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(7)','Visible','on','Name','2D correlation analysis: disrelation spectrum')
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: disrelation spectrum');
    end
    
% prepare the 2D-COS figure to plot a synchronous 2D spectrum
elseif tp == 8
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','fft sync');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(8)','Visible','on','Name','2D correlation analysis: synchronous spectrum (fft method)')
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: synchronous spectrum (fft method)');
    end
    
% prepare the 2D-COS figure to plot an asynchronous 2D spectrum
elseif tp == 9
    set(h.Button.PlotCM,'Callback','mat2dcorr(''do2danalysis'')','String','fft async');
    if dsplyint == 1
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','figure(findobj(''Tag'',''CorrMatrixWindow''));updcorrplt(9)','Visible','on','Name','2D correlation analysis: asynchronous spectrum (fft method)')
    else
        set(h.Figure.CorrMat,'WindowButtonMotionFcn','','Visible','on','Name','2D correlation analysis: asynchronous spectrum (fft method)');
    end
   
end    
set(h.Figure.CorrMat,'WindowButtonDownFcn','mat2dcorr(''setxypos'')');

%% ************************************************************************
case 'tgglnlnspopup' % function to activate / inactivate popupmenu number of isolines
% *************************************************************************

h.Popupmenu.ContourNlines           = findobj('Tag','ContourNlinesPopupmenu');
h.Checkbox.CorrMatContour           = findobj('Tag','CorrMatContourCheckbox');
h.Checkbox.CorrMatFlContour         = findobj('Tag','CorrMatFillContourCheckbox');
h.Surface.SurfPlot                  = findobj('Tag','SurfPlot');
pltctrmap                           = get(h.Checkbox.CorrMatContour,'Value');

if pltctrmap == 1
    set(h.Popupmenu.ContourNlines,'Enable','on')
    set(h.Checkbox.CorrMatFlContour,'Enable','on')
    % if CorrMat present: plot contour map
    if isempty(h.Surface.SurfPlot) == 0
        pltctrfun
    end
else
    set(h.Popupmenu.ContourNlines,'Enable','off')
    set(h.Checkbox.CorrMatFlContour,'Enable','off','Value',0)
    % if CorrMat present: plot surface map
    if isempty(h.Surface.SurfPlot) == 0
        pltsrffun
    end
end

%% ************************************************************************
case 'pltctrcs' % plots a contour map --> goto function pltctrfun
% *************************************************************************

pltctrfun


%% ************************************************************************
case 'done_corrmap' % close all windows
% *************************************************************************

h.Figure.CorrMat                    = findobj('Tag','CorrMatrixWindow');
h.Figure.CorrCtrl                   = findobj('Tag','CorrmControlWindow');
h.Figure.TracePlot                  = findobj('Tag','1DtracePlot');
h.Figure.XYfetPlot                  = findobj('Tag','PlotXYfeatures');
delete(h.Figure.CorrMat);    
delete(h.Figure.CorrCtrl);
delete(h.Figure.TracePlot);
delete(h.Figure.XYfetPlot);

%% ************************************************************************
case 'capt' % store image of the 2D-COS spectrum
% *************************************************************************

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Figure.CorrMat                    = findobj('Tag','CorrMatrixWindow');
uiputdescript                       = 'saving correlation plot as a bitmap';
write2bmp(h.Axis.Corr,h.Figure.CorrMat,uiputdescript);


%% ************************************************************************
case 'clear' % clear data 
% *************************************************************************

h.Axis.specx                        = findobj('Tag','AxisXSpec');       
h.Axis.specy                        = findobj('Tag','AxisYSpec');
h.UIMenu.Xdata                      = findobj('Tag','loadxuimenu');
h.UIMenu.Ydata                      = findobj('Tag','loadyuimenu');

set(h.UIMenu.Xdata,'UserData',[]);
set(h.UIMenu.Ydata,'UserData',[]);
delete(get(h.Axis.specx,'Children'));
delete(get(h.Axis.specy,'Children'));
rmaxiselements

%% ************************************************************************
case 'save2Dspec' % store the actual 2D spectrum + metadata
% *************************************************************************

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Button.PlotCM                     = findobj('Tag','plotcorrmatbutton');
h.Figure.CorrMat                    = findobj('Tag','CorrMatrixWindow');
h.Surf.Plot                         = findobj('Tag','SurfPlot');

twoddata                            = get(h.Button.PlotCM,'UserData');

[SaveFile,SavePath] = uiputfile('*.mat','store 2D spectrum');
if ischar(SaveFile) == 1  
   cd(SavePath);
   if length(SaveFile) > 4 && strcmp(SaveFile(length(SaveFile)-3:length(SaveFile)),'.mat') == 1
      save(SaveFile, 'twoddata', '-mat');
   else	 
      save([SaveFile '.mat'], 'twoddata', '-mat');
   end
end
disp('storing actual 2D spectrum and metadata as a structure array')
    

%% ************************************************************************
otherwise
% *************************************************************************

disp('invalid action string')

end


%% ************************************************************************
function plotavspec(data,actax) % calculates and plots average spectra in the respective panels
% *************************************************************************

h.Axis.Corr                         = findobj('Tag','AxisCorrelation'); 
h.Axis.specx                        = findobj('Tag','AxisXSpec');       
h.Axis.specy                        = findobj('Tag','AxisYSpec');
h.Edit.CMX1                         = findobj('Tag','CorrMatXlwnEdit'); 
h.Edit.CMX2                         = findobj('Tag','CorrMatXuwnEdit'); 
h.Edit.CMY1                         = findobj('Tag','CorrMatYlwnEdit');
h.Edit.CMY2                         = findobj('Tag','CorrMatYuwnEdit');
h.Text.Xaxis                        = findobj('Tag','TextXaxis');       
h.Text.Yaxis                        = findobj('Tag','TextYaxis');
h.Text.VSTx                         = findobj('Tag','TextVSTx');        
h.Text.VSTy                         = findobj('Tag','TextVSTy');
h.Line.Xmspc                        = findobj('Tag','meanxspec');
h.Line.Ymspc                        = findobj('Tag','meanyspec');

delete(get(h.Axis.Corr,'Children'));

if strcmp(actax,'x') == 1   
    delete(h.Line.Xmspc);
    xcmenuspc                       = uicontextmenu;
    nanx                            = isnan(data.spc(:,1));
    avspec                          = mean(data.spc(~nanx,:));
    minx                            = min(avspec);
    maxx                            = max(avspec);
    delta                           = (maxx-minx)/10;
    YLim                            = [minx-delta maxx+delta];
    xspec(1,:)                      = data.wav;
    xspec(2,:)                      = avspec;
    set(h.Axis.Corr,'XLim',[data.lwn data.uwn]);
    set(h.Axis.specx,'XLim',[data.lwn data.uwn],'YLim',YLim,'UserData',xspec,'UIContextMenu',xcmenuspc);
    disp(['x-direction: ' data.tos])
    plot(data.wav,avspec,'Parent',h.Axis.specx,'Tag','meanxspec');
    set(h.Edit.CMX1,'Enable','on','String',num2str(data.lwn));
    set(h.Edit.CMX2,'Enable','on','String',num2str(data.uwn));
    set(h.Text.Xaxis,'String',['mean x-spectrum: ' data.tos]);
    set(h.Text.VSTx,'String',data.vst);
    rmaxiselements;
    uimenu(xcmenuspc,'label','store x-mean spectrum','Tag','StrXMean','Callback','mat2dcorr(''storexmean'')');
elseif strcmp(actax,'y') == 1
    delete(h.Line.Ymspc);
    ycmenuspc                       = uicontextmenu;
    nany                            = isnan(data.spc(:,1));
    avspec                          = mean(data.spc(~nany,:));
    miny                            = min(-1*avspec);
    maxy                            = max(-1*avspec);
    delta                           = (maxy-miny)/10;
    XLim                            = [miny-delta maxy+delta];
    yspec(1,:)                      = data.wav;
    yspec(2,:)                      = avspec;
    set(h.Axis.Corr,'YLim',[data.lwn data.uwn]);
    set(h.Axis.specy,'YLim',[data.lwn data.uwn],'XLim',XLim,'UserData',yspec,'UIContextMenu',ycmenuspc);
    plot(-1*avspec,data.wav,'Parent',h.Axis.specy,'Tag','meanyspec');
    set(h.Edit.CMY1,'Enable','on','String',num2str(data.lwn));
    set(h.Edit.CMY2,'Enable','on','String',num2str(data.uwn));
    set(h.Text.Yaxis,'String',['mean y-spectrum: ' data.tos]);
    set(h.Text.VSTy,'String',data.vst);
    disp(['y-direction: ' data.tos])
    rmaxiselements;
    uimenu(ycmenuspc,'label','store y-mean spectrum','Tag','StrYMean','Callback','mat2dcorr(''storeymean'')');
end    


%% ************************************************************************
function initcorplotwin(h) % generate the figure with the axis for displaying the 2D correlation spectra 
% *************************************************************************

% load color definitions from functions cols 
[bg,bgf,bge,bgb,fgt,fgr,fgb,bgs]    = cols;

% the next lines are for testing and documentation  - do not remove!
% h.scrsz = [1 1 1024 768];

% pos(3:4)                            = [h.scrsz(4)-80 h.scrsz(4)-90];
% pos(1:2)                            = [h.Cen.All(1)-pos(3)/2 h.Cen.All(2)-pos(4)/2-15];
% poscaxis                            = [140 25 pos(3)-200 pos(4)-190];       % axis for displaying the 2D correlation spectra 
% posxaxis                            = [140 pos(3)-170 pos(3)-200 130];      % axis for displaying the x-mean spectrum 
% posyaxis                            = [10 25 125 pos(4)-190];               % axis for displaying the y-mean spectrum 
% poshaxis                            = [10 pos(3)-175 130 130];              % hidden axis for displaying rotated text

pos(3:4)                            = [h.scrsz(4)-150 h.scrsz(4)-160];
pos(1:2)                            = [h.Cen.All(1)-pos(3)/2 h.Cen.All(2)-pos(4)/2-15];
poscaxis                            = [140 25 pos(3)-200 pos(4)-190];       % axis for displaying the 2D correlation spectra 
posxaxis                            = [140 pos(3)-170 pos(3)-200 130];      % axis for displaying the x-mean spectrum 
posyaxis                            = [10 25 125 pos(4)-190];               % axis for displaying the y-mean spectrum 
poshaxis                            = [10 pos(3)-175 130 130];              % hidden axis for displaying rotated text

h0 = figure('Units','pixel','Position',pos,'Color',bg,'MenuBar','none','Renderer','zbuffer','RendererMode','manual', ...
      'ResizeFcn','resiz2dfig','InvertHardcopy','off','PaperPositionMode','auto','Colormap',jet(h.NumberOfColors), ...
      'CloseRequestFcn','mat2dcorr(''done_corrmap'')','Visible','off','NumberTitle','off','Tag','CorrMatrixWindow');  

% call the subfunction setuimenu
setuimenu(h0);
 
% main axis for the correlation plot
h1(1) = axes('Parent',h0,'Units','pixel','Position',poscaxis,'XLim',[1000 4000],'YLim',[1000 4000],'CLim',[0.5 1], ...
      'NextPlot','ReplaceChildren','HandleVisibility','on','Interruptible','off','Box','on','CameraUpVector',[0 1 0],'YAxisLocation','right',  ...
   	  'CameraUpVectorMode','manual','Color',[1 1 1],'SelectionHighlight','off','Visible','on','TickDir','out','TickLength',[0.002 0],'Tag','AxisCorrelation');
% axis for showing the mean x-spectrum
h1(2) = axes('Parent',h0,'Units','pixel','Position',posxaxis,'XLim',[1000 4000],'YLim',[0 1],'NextPlot','ReplaceChildren','HandleVisibility','on','Interruptible','off','Box','on', ...
   	  'CameraUpVector',[0 1 0],'CameraUpVectorMode','manual','Color',[1 1 1],'SelectionHighlight','off','Visible','on', ...
      'TickLength',[0 0],'XTickLabel','','YTickLabel','','Tag','AxisXSpec');
% axis for showing the mean y-spectrum
h1(3) = axes('Parent',h0,'Units','pixel','Position',posyaxis,'XLim',[0 1],'YLim',[1000 4000],'NextPlot','ReplaceChildren','HandleVisibility','on','Interruptible','off','Box','on', ...
   	  'CameraUpVector',[0 1 0],'CameraUpVectorMode','manual','Color',[1 1 1],'SelectionHighlight','off','Visible','on', ...
      'TickLength',[0 0],'XTickLabel','','YTickLabel','','Tag','AxisYSpec');
% hidden axis for displaying a line and rotated text (-45°)
h1(4) = axes('Parent',h0,'Units','pixel','Position',poshaxis,'Visible','off','Tag','AxisHSpec');
h1(5) = line('XData',[0 1],'YData',[1 0],'Parent',h1(4),'LineWidth',2,'Color',[0 0 0],'Tag','BlackLine');
  
% Text for showing the actual cursor position (wavenumber / Raman shift / frequency / m/z positions)
h1(6) = uicontrol('Position',[poscaxis(1)+5 poscaxis(2)+poscaxis(3)+137 255 17],'Style','text','Tag','ActCursorPos');
% Text for showing the actual correlation / covariance / Pareto coefficient (i.e. the intensity of the 2D-COS spectrum)
h1(7) = uicontrol('Position',[poscaxis(1)+poscaxis(3)-190 poscaxis(2)+poscaxis(3)+137 180 17],'Style','text','Tag','ActCorrCoeff');  
% text: title of mean spectrum  (x)
h1(8) = uicontrol('Parent',h0,'Position',[(posxaxis(1)+posxaxis(3))-210 posxaxis(2)+posxaxis(4)-20 198 15],'String','mean x-spectrum','Style','text','Tag','TextXaxis');        
% text: title of mean spectrum  (y)
h1(9) = text('Parent',h1(4),'Position',[5 -140],'String','mean y-spectrum','Rotation',90,'Units','points','Tag','TextYaxis');        
% text: fixed text 'dynamic variable x:'
h1(10) = text('Parent',h1(4),'Position',[25 95],'String','dynamic variable x:','Rotation',-45,'Units','points','Tag','TextDynVarX');        
% text: fixed text 'dynamic variable y:'
h1(11) = text('Parent',h1(4),'Position',[5 75],'String','dynamic variable y:','Rotation',-45,'Units','points','Tag','TextDynVarY');
% text: type and unit of the dynamic variable x
h1(12) = text('Parent',h1(4),'Position',[45 95],'Rotation',-45,'Units','points','Tag','TextVSTx');
% text: type and unit of the dynamic variable y
h1(13) = text('Parent',h1(4),'Position',[5 55],'Rotation',-45,'Units','points','Tag','TextVSTy');        

set(h1(1:3),'Parent',h0','FontName','helvetica','FontWeight','bold','FontSize',8);
set(h1(9:11),'FontName','helvetica','FontWeight','bold','FontSize',8,'Color',[1 0 0])
set(h1([12 13]),'FontName','helvetica','FontWeight','bold','FontSize',8,'Color',[0 0 0])
setButtonFormat(findobj(h0,'Style','pushbutton'),bgb);
setEditFormat(findobj(h0,'Style','edit'),bge,fgt);
setTextFormat(h1([6 7]),bg,fgt);
setTextFormat(h1(8),bge,fgr);
set(h0,'Visible','on')


%% ************************************************************************
function initcorrcontrolwin % generate a window with control elements for producing 2D-COS spectra
% *************************************************************************

% load color definitions from functions cols 
[bg,bgf,bge,bgb,fgt,fgr,fgb,bgs]    = cols;

plotwin                             = get(findobj('Tag','CorrMatrixWindow'),'Position');
pos(3:4)                            = [180 475];
pos(1:2)                            = [plotwin(1)-pos(3)-30 plotwin(2)+plotwin(4)-pos(4)+10];
h0 = figure('Units','pixel','Position',pos,'Color',bg,'MenuBar','none','Renderer','zbuffer','RendererMode','manual','Visible','off', ...
      'Resize','off','InvertHardcopy','off','PaperPositionMode','auto','Colormap',jet, ...
      'CloseRequestFcn','mat2dcorr(''done_corrmap'')','Name','2D control','visible','on','NumberTitle','off','Tag','CorrmControlWindow');
 
% Button: plot mat2dcorr******************************************  
h1(1) = uicontrol('Enable','off','Position',[10 5 75 18],'Tag','plotcorrmatbutton');
% Button: cancel **************************************************  
h1(2) = uicontrol('Callback','mat2dcorr(''done_corrmap'')','Position',[110 5 60 18],'String','cancel','Tag','cnclbutton');

% UI group 1D slices
% Edit: x-position of the y-trace ***********************  
h1(3) = uicontrol('Position',[45 30 12 18],'String','x','Style','text','Tag','Text');
h1(4) = uicontrol('Position',[60 30 45 21],'Enable','off','String','','Style','edit','Tag','CorrMatXtraceEdit');
% Edit: y-position of the x-trace ***********************   
h1(5) = uicontrol('Position',[110 30 12 18],'String','y','Style','text','Tag','Text');
h1(6) = uicontrol('Position',[125 30 45 21],'Enable','off','String','','Style','edit','Tag','CorrMatYtraceEdit');
% Text: [x,y] slice coordinates:
h1(7) = uicontrol('Position',[10 53 165 17],'String','[x,y] slice coordinates','TooltipString',' [x,y] coordinates for 1D-COS slice extraction','Style','text','Tag','Text');

% UI group colormap
% Button: Apply color map
h1(8) = uicontrol('Position',[65  77 120 17],'String','apply scaling','TooltipString','scales the color between Clim1 and Clim2','Style','text','Tag','Text');
h1(9) = uicontrol('Position',[160 81 10 10],'Callback','mat2dcorr(''setCLim'')','Enable','off','Tag','setCLimbutton');
% Edit: colormap CLim1 value ***********************************************  
h1(11) = uicontrol('Position',[60 105 45 21],'Style','edit','String','-1','Tag','CorrMatCLim1Edit');
h1(10) = uicontrol('Position',[10 105 43 17],'String','scaling','Style','text','Tag','Text');
% Edit: colormap CLim2 value **********************************************  
h1(12) = uicontrol('Position',[125 105 45 21],'Style','edit','String','1','Tag','CorrMatCLim2Edit');
% Popupmenu: select the type of colormap  
h1(13) = uicontrol('Position',[60 130 110 21],'Callback','mat2dcorr(''setCLim'')','String',' jet | hsv | hot | cool | bone | winter | summer | autumn | copper ', ...
                   'Value',1,'Style','popupmenu','Tag','Colormap2DCOSPopupmenu');
% Text: [x,y] slice coordinates:
h1(14) = uicontrol('Position',[10 153 165 17],'String','select colormap','TooltipString','select a colormap for displaying the correlation spectrum','Style','text','Tag','Text');

% UI group plot surface map or contour map
% popupmenu: how many lines in contour map
h1(15) = uicontrol('Position',[10  180 130 17],'String','number of isolines','Style','text','Tag','Text');
h1(16) = uicontrol('Position',[130 180 40  21],'Callback','mat2dcorr(''pltctrcs'')','String','2 |3 |4 |5 |6 |8 |10 |12 |15 |18 |21 |25 |30 |35 |40', ...
                   'Value',8,'Enable','off','Style','Popupmenu','Tag','ContourNlinesPopupmenu');
% checkbox: plot filled contour map
h1(17) = uicontrol('Position',[10  205 130 17],'String','fill contour','Style','text','Tag','Text');
h1(18) = uicontrol('Position',[156 208 14  14],'Callback','mat2dcorr(''tgglnlnspopup'')','Style','checkbox','Value',0,'TooltipString','fill contour map', ...
                   'Enable','off','Tag','CorrMatFillContourCheckbox');
% checkbox: plot contour or surface map 
h1(19) = uicontrol('Position',[10  230 130 17],'String','plot contour map','Style','text','Tag','Text');
h1(20) = uicontrol('Position',[156 233 14  14],'Callback','mat2dcorr(''tgglnlnspopup'')','Style','checkbox','Value',0, ...
                   'TooltipString','creates a contour map, otherwise a surface map will be plotted','Tag','CorrMatContourCheckbox');

% Popupmenu: select reference spectrum to obtain the dynamic spectra
h1(21) = uicontrol('Position',[60 261 110 21],'Callback','mat2dcorr(''mod2dtype'')','String',' no reference | average spectrum | first spectrum | last spectrum ', ...
                   'Value',2,'Style','popupmenu','Tag','Refspec2DCOSPopupmenu');
% Text pupupmenu select reference spectrum
h1(22) = uicontrol('Position',[10 283 165 32],'String','type of reference spectrum for dynamic spectra','Style','text','Tag','Text');

% UI group 2D spectrum
% edit field lwn in y-axis *****************************************  
h1(23) = uicontrol('Position',[30  325 60 21],'Enable','off','String','1000','Style','edit','Tag','CorrMatYlwnEdit');
% edit field uwn in y-axis ***************************************  
h1(24) = uicontrol('Position',[110 325 60 21],'Enable','off','String','4000','Style','edit','Tag','CorrMatYuwnEdit');
% text for showing description of wavenumber edit fields (y)
h1(25) = uicontrol('Position',[10  325 12 18],'String','y','Style','text','Tag','Text');
% edit field lwn in x-axis ***************************************
h1(26) = uicontrol('Position',[30  350 60 21],'Enable','off','String','1000','Style','edit','Tag','CorrMatXlwnEdit');
% edit field uwn in x-axis ***************************************  
h1(27) = uicontrol('Position',[110 350 60 21],'Enable','off','String','4000','Style','edit','Tag','CorrMatXuwnEdit');
% text for showing description of wavenumber edit fields (x)
h1(28) = uicontrol('Position',[10  350 12 18],'String','x','Style','text','Tag','Text');
% Text: regions for 2D-COS analysis
h1(29) = uicontrol('Position',[10  375 130 28],'String','spectral regions for 2D-COS analysis','Style','text','Tag','TextDescr');

% Popupmenu: type of 2D spectrum  
h1(30) = uicontrol('Position',[60 415 110 21],'Callback','mat2dcorr(''mod2dtype'')','String', ...
                   ' Pearson scaling | Pareto scale 0.75 | Pareto scale 0.50 | Pareto scale 0.25 | stat synchronous | stat asynchronous | disrelation | fft synchronous | fft asynchronous ', ...
                   'Value',5,'Style','popupmenu','Tag','Type2DCOSPopupmenu');
% Text: type of 2D spectrum?
h1(31) = uicontrol('Position',[10 440 165 17],'String','type of 2D spectrum','TooltipString', ...
                   'Pearson scaling / Pareto scaling 0.75 / Pareto scaling 0.50 / Pareto scaling 0.25 / statist. sync  /  statist. async / disrelation / fft sync / fft async', ...
                   'Style','text','Tag','Text');

setButtonFormat(findobj(h0,'Style','pushbutton'),bgb);
setEditFormat(findobj(h0,'Style','edit'),bge,fgt);
setTextFormat(h1([3 5 8 10 15 17 25 28 29]),bg,fgt); % format of normal text elements
setTextFormat(h1([7 14 19 22 31]),bg,fgr); % red formatted text elements


%% ************************************************************************
function setuimenu(h0) % internal function set uimenu of the window    
% *************************************************************************


h1 = uimenu('Parent',h0, ...  
       'Label','&File', ...
       'Tag','File');
      uimenu('Parent',h1, ...
         'Label','&save 2D spectrum', ...
         'Enable','off', ...         
         'Callback','mat2dcorr(''save2Dspec'')', ...         
         'Tag','CMVSave');     
      uimenu('Parent',h1, ...
         'Callback','mat2dcorr(''clear'')', ...
         'Label','&clear', ...
         'Tag','CMVClear');
      uimenu('Parent',h1, ...
         'Callback','mat2dcorr(''done_corrmap'')', ...
         'Label','&exit', ...
         'Tag','CMVExit');
   h1 = uimenu('Parent',h0, ...
       'Label','&Load Data', ...
       'Tag','Data');  
     h2 = uimenu('Parent',h1, ...
         'Label','&Matlab imaging format', ...
         'Tag','LoadMatlabImaging');
        h3 = uimenu('Parent',h2, ...
            'Label','&x-data', ...
            'Tag','loadxuimenu');
            uimenu('Parent',h3, ...
                'Label','&original data', ...
                'Callback','mat2dcorr(''loadx'', 1)', ...
                'Tag','CMloadxdataorig');
            uimenu('Parent',h3, ...
                'Label','&preprocessed data', ...
                'Callback','mat2dcorr(''loadx'', 2)', ...
                'Tag','CMloadxdataprep');
            uimenu('Parent',h3, ...
                'Label','&derivative data', ...
                'Callback','mat2dcorr(''loadx'', 3)', ...
                'Tag','CMloadxdataderiv');
            uimenu('Parent',h3, ...
                'Label','&deconvolution data', ...
                'Callback','mat2dcorr(''loadx'', 4)', ...
                'Tag','CMloadxdatadeconv');
        h3 = uimenu('Parent',h2, ...
            'Label','&y-data', ...
            'Tag','loadyuimenu');
            uimenu('Parent',h3, ...
                'Label','&original data', ...
                'Callback','mat2dcorr(''loady'', 1)', ...
                'Tag','CMloadydataorig');
            uimenu('Parent',h3, ...
                'Label','&preprocessed data', ...
                'Callback','mat2dcorr(''loady'', 2)', ...
                'Tag','CMloadydataprep');
            uimenu('Parent',h3, ...
                'Label','&derivative data', ...
                'Callback','mat2dcorr(''loady'', 3)', ...
                'Tag','CMloadydataderiv');
            uimenu('Parent',h3, ...
                'Label','&deconvolution data', ...
                'Callback','mat2dcorr(''loady'', 4)', ...
                'Tag','CMloadydatadeconv');
     h2 = uimenu('Parent',h1, ...
         'Label','&Matlab trace format', ...
         'Tag','LoadMatlabTrace');
        uimenu('Parent',h2, ...
            'Label','&x-data', ...
            'Callback','mat2dcorr(''loadx'', 9)');
        uimenu('Parent',h2, ...
            'Label','&y-data', ...
            'Callback','mat2dcorr(''loady'', 9)');
     h2 = uimenu('Parent',h1, ...
         'Label','&Excel data format', ...
         'Tag','LoadExcel');
        uimenu('Parent',h2, ...
            'Label','&x-data', ...
            'Callback','mat2dcorr(''loadx'', 10)');
        uimenu('Parent',h2, ...
            'Label','&y-data', ...
            'Callback','mat2dcorr(''loady'', 10)');
    h1 = uimenu('Parent',h0, ...
       'Label','&Action', ...
       'Tag','Tools');
     uimenu('Parent',h1, ...          
         'Callback','mat2dcorr(''do2danalysis'')', ...
         'Label','&plot 2D spectrum', ...
         'Enable','off', ...
         'Tag','CMVPlt2Dspec');
     uimenu('Parent',h1, ...          
         'Callback','mat2dcorr(''getextr2d'')', ...
         'Label','&extrema of 2D fcn', ...
         'Enable','off', ...
         'Tag','CMVdspmaxcov');
     uimenu('Parent',h1, ...          
         'Callback','mat2dcorr(''getxtrace'')', ...
         'Label','&plot x-slice', ...
         'Enable','off', ...
         'Tag','CMVgetxtrc');
     uimenu('Parent',h1, ...          
         'Callback','mat2dcorr(''getytrace'')', ...
         'Label','&plot y-slice', ...
         'Enable','off', ...
         'Tag','CMVgetytrc');
     uimenu('Parent',h1, ...          
         'Callback','mat2dcorr(''getcorrdata'')', ...
         'Label','&plot [x,y] features', ...
         'Enable','off', ...
         'Tag','CMVgetcorr');
     uimenu('Parent',h1, ...          
         'Callback','mat2dcorr(''invcmap'')', ...
         'Label','&invert colormap', ...
         'Enable','off', ...
         'Tag','CMVinvCmap');
     uimenu('Parent',h1, ...          
         'Callback','mat2dcorr(''capt'')', ...
         'Label','&capture to bitmap', ...
         'Enable','off', ...
         'Tag','CMVgetImg');
     h2 = uimenu('Parent',h1, ...          
         'Label','&display 2D-COS intensity', ...
         'Enable','off', ...;
         'Tag','CMVupdplt');     
         uimenu('Parent',h2, ...          
             'Label','&on', ...
             'Callback','mat2dcorr(''mod2dtype'')', ...
             'Tag','CMVupdplton');
         uimenu('Parent',h2, ...          
             'Label','&off', ...
             'Callback','mat2dcorr(''mod2dtype'')', ...
             'Tag','CMVupdpltoff');     


%% ************************************************************************
 function CorrMat  = twoDCOSY(spcx,spcy,method)
% *************************************************************************

tic
verbose                             = 0;

h.Popup.Refspec2DCOS                = findobj('Tag','Refspec2DCOSPopupmenu');
refspectpe                          = get(h.Popup.Refspec2DCOS,'Value');

[lgthx, zdimx]                      = size(spcx);
[lgthy, zdimy]                      = size(spcy);

if refspectpe == 2     % ref spectrum mean spectrum 
    refspcx                         = mean(spcx,1);
    refspcy                         = mean(spcy,1);
    disp('reference spectrum - mean spectrum:')     
elseif refspectpe == 3 % ref spectrum: first spectrum
    refspcx                         = spcx(1,:);
    refspcy                         = spcy(1,:);
    disp('reference spectrum - first spectrum:')     
elseif refspectpe == 4 % ref spectrum: last spectrum
    refspcx                         = spcx(end,:);
    refspcy                         = spcy(end,:);
    disp('reference spectrum - last spectrum:')     
else
    refspcx                         = zeros(1,zdimx);
    refspcy                         = zeros(1,zdimy);
end

if lgthx ~= lgthy
    error('lgthx and lgthy must be of equal length')
end    

if verbose == 1
    disp(['    size of the x-data array [nspectra-x , nfeatures-x]: ' num2str(size(spcx))])
    disp(['    size of the y-data array [nspectra-y , nfeatures-y]: ' num2str(size(spcy))])
end

% mean centering the spectra
spcx                                = spcx-repmat(refspcx, [lgthx 1]);
spcy                                = spcy-repmat(refspcy, [lgthy 1]);   


%% methods 'covar','Pareto' and 'corr'
if strcmp(method,'covar') == 1 || strcmp(method,'Pareto-0.25') == 1 || strcmp(method,'Pareto-0.50') == 1 || strcmp(method,'Pareto-0.75') == 1 || strcmp(method,'corr') == 1
    
    smsqspx                         = sum(spcx.*spcx,1);
    smsqspy                         = sum(spcy.*spcy,1);
    CorrMat                         = zeros(zdimx,zdimy);
    
    if strcmp(method,'covar') == 1
        rtxstd                      = (smsqspx/lgthx).^0;
        rtystd                      = (smsqspy/lgthy).^0;
        nrmfct                      = lgthx-1; % definition by Noda
    elseif strcmp(method,'Pareto-0.25') == 1     
        rtxstd                      = (smsqspx/lgthx).^0.125;
        rtystd                      = (smsqspy/lgthy).^0.125;
        nrmfct                      = lgthx-1; % definition by Noda
    elseif strcmp(method,'Pareto-0.50') == 1 
        rtxstd                      =  (smsqspx/lgthx).^0.250;
        rtystd                      = (smsqspy/lgthy).^0.250;
        nrmfct                      = lgthx-1; % definition by Noda
    elseif strcmp(method,'Pareto-0.75') == 1 
        rtxstd                      = (smsqspx/lgthx).^0.375;
        rtystd                      = (smsqspy/lgthy).^0.375;
        nrmfct                      = lgthx-1; % definition by Noda
    elseif strcmp(method,'corr') == 1 
        rtxstd                      = (smsqspx/lgthx).^0.500;
        rtystd                      = (smsqspy/lgthy).^0.500;
        nrmfct                      = lgthx; % definition by Noda cannot be applied (r must not be larger than 1!)
    else
        error('error in function updcorrplt/twoDCOSY')
    end
    for i=1:zdimx
        for j=1:zdimy
             CorrMat(i,j)           = sum(spcx(:,i).* spcy(:,j))/(rtxstd(i)*rtystd(j));
        end
    end
    CorrMat                         = CorrMat'/nrmfct;        
end


%% method 'covar asynchronous'
if strcmp(method,'cvasyn') == 1 
    disp('covar asynchronous')
    CorrMat                         = zeros(zdimx,zdimy);
    N                               = zeros(lgthx,lgthy);
    
    % get the Hilbert-Noda transformation matrix N(i,j) first
    for i=1:lgthx
        for j=1:lgthy
            if i~=j
                N(i,j)              = 1/(pi*(j-i));
            end
        end
    end
     
    fact2                           = zeros(lgthx,zdimy);
    for nju2 = 1:zdimy % spectral coordinate in y
        for i=1:lgthx % number of spectra in x
            fact2(i,nju2)           =  sum(N(i,:).* spcy(:,nju2)');
        end   
    end
    
    for nju1 = 1:zdimx % spectral coordinate in x
        for nju2                    = 1:zdimy % spectral coordinate in y
            CorrMat(nju1,nju2)      = sum(spcx(:,nju1).*fact2(:,nju2));
        end
    end 
    CorrMat                         = CorrMat'/(lgthx-1);  
end


%% 2D disrelation coefficient method
if strcmp(method,'disrel') == 1 
    
    disp('disrelation')
    CorrMat                         = zeros(zdimx,zdimy);
    
    % the disrelation spectrum can be computed only from symmetric regions 
    % i.e. zdimx must be equal to zdimy
    zdim                            = min(zdimx,zdimy);
    valii                           = zeros(1,zdim);
    for k=1:zdim
        valii(k)                    = sum(spcx(:,k).*spcy(:,k));
    end
    for i=1:zdim
        for j=1:zdim
             valij                  = sum(spcx(:,i).*spcy(:,j));
             CorrMat(i,j)           = sqrt(valii(i)*valii(j) - valij^2);
        end
    end
    CorrMat                         = real(CorrMat)'/(lgthx-1);
end

%% methods 'syn','asyn' and 'phase' - these are fft-based methods
if strcmp(method,'sync') == 1 || strcmp(method,'async') == 1 || strcmp(method,'phase') == 1
    
    corr2d                          = zeros(zdimx,zdimy);
    CorrMat                         = zeros(zdimx,zdimy);    
    lgthx2                          = floor(lgthx/2)+1; 
    lgthy2                          = floor(lgthy/2)+1; 
    Xfft                            = fft(spcx)/sqrt(lgthx); 
    Yfft                            = fft(spcy)/sqrt(lgthy); 

    % this is the 'inner' 2D COSY function 
    for i = 1:zdimx
        for j = 1:zdimy
            corr2d(i,j)             = sum(Xfft(1:lgthx2,i).*conj(Yfft(1:lgthy2,j)));
        end
    end
    % obtaining corr2d, syn2d and asyn2d
    corr2d                          = 2*corr2d/lgthx;
    syn2d                           = real(corr2d);
    asyn2d                          = imag(corr2d);

    % now setting the phase (not used in the current implementation)
    phase                           = zeros(zdimx,zdimy);
    for i = 1:zdimx
        for j = 1:zdimy
            if (syn2d(i,j) == 0)
                phase(i,j)          = 0;
            else
                phase(i,j)          = atan(asyn2d(i,j)/syn2d(i,j));
            end
        end
    end
    
    if strcmp(method,'sync') == 1
        CorrMat                     = syn2d;
    elseif strcmp(method,'async') == 1    
        CorrMat                     = asyn2d;
    elseif strcmp(method,'phase') == 1    
        CorrMat                     = phase;
    end
    CorrMat                         = CorrMat';
end
toc

%% ************************************************************************
function pltsrffun  % function for plotting a surface map of the 2D function
% *************************************************************************

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Button.PltCorrMat                 = findobj('Tag','plotcorrmatbutton');
h.Ctxt.Save                         = findobj('Tag','CMVSave');
h.Surf.Plot                         = findobj('Tag','SurfPlot');

delete(h.Surf.Plot);

% get the structure array 'CorrMatr' 
CorrMatr                            = get(h.Button.PltCorrMat,'UserData');
CorrMat                             = CorrMatr.data;
datax.nwv                           = CorrMatr.xwv;
datay.nwv                           = CorrMatr.ywv;
[x,y]                               = meshgrid(datax.nwv,datay.nwv); 

surface(x,y,CorrMat,'Parent',h.Axis.Corr, ...
                     'EdgeColor','none', ...
                     'FaceColor','interp', ...
                     'HitTest','off', ...
                     'Clipping','on', ...
                     'CDataMapping','scaled', ...
                     'Tag','SurfPlot');
set(h.Ctxt.Save,'Enable','on');


%% ************************************************************************
function pltctrfun % function for plotting a contour map of the 2D function
%-----------------------------------------------------------

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Checkbox.FillContour              = findobj('Tag','CorrMatFillContourCheckbox');
h.Button.PltCorrMat                 = findobj('Tag','plotcorrmatbutton');
h.Popupmenu.ContourNlns             = findobj('Tag','ContourNlinesPopupmenu');
h.Ctxt.Save                         = findobj('Tag','CMVSave');
h.Surf.Plot                         = findobj('Tag','SurfPlot');

delete(h.Surf.Plot);

nlinesstr                           = get(h.Popupmenu.ContourNlns,'String');
nlinesval                           = get(h.Popupmenu.ContourNlns,'Value');
nlines                              = str2num(nlinesstr(nlinesval,:));       % number of isolines used for the contour map
fillcontour                         = get(h.Checkbox.FillContour,'Value');

% get the structure array 'CorrMatr' 
CorrMatr                            = get(h.Button.PltCorrMat,'UserData');
CorrMat                             = CorrMatr.data;
datax.nwv                           = CorrMatr.xwv;
datay.nwv                           = CorrMatr.ywv;

[x,y]                               = meshgrid(datax.nwv,datay.nwv);

if fillcontour == 0
    contour(x,y,CorrMat,nlines,'Parent',h.Axis.Corr,'Tag','SurfPlot');
else
    contourf(x,y,CorrMat,nlines,'Parent',h.Axis.Corr,'Tag','SurfPlot');
    % the standard contextmenu is missing if contourf is used (unlike contour) 
    % --> perhaps this is because contourf creates line objects which do not have 
    % a contextmenu property --> a workaround is required (see 
    % https://undocumentedmatlab.com/blog/customizing-contour-plots
end

% Workaround for missing 'MouseOver' functionality: create an invisible
% surface  object over the contour map
surface(x,y,CorrMat,'Parent',h.Axis.Corr, ...
                     'Visible','off', ...
                     'HitTest','off', ...
                     'Clipping','on', ...
                     'CDataMapping','scaled', ...
                     'Tag','SurfPlot');
set(h.Ctxt.Save,'Enable','on');

%% ************************************************************************
 function rmaxiselements % clear the axis with the surface or contour plots includings all asscociated data
% *************************************************************************

h.Axis.Corr                         = findobj('Tag','AxisCorrelation');
h.Button.PlotCM                     = findobj('Tag','plotcorrmatbutton');
h.Button.setCLim                    = findobj('Tag','setCLimbutton');
h.Checkbox.CorrMContr               = findobj('Tag','CorrMatContourCheckbox');
h.Checkbox.FillContour              = findobj('Tag','CorrMatFillContourCheckbox');
h.Ctxt.Save                         = findobj('Tag','CMVSave');
h.Edit.CorrMatXtrace                = findobj('Tag','CorrMatXtraceEdit');
h.Edit.CorrMatYtrac                 = findobj('Tag','CorrMatYtraceEdit');
h.Edit.CorrMatCLim1                 = findobj('Tag','CorrMatCLim1Edit');
h.Edit.CorrMatCLim2                 = findobj('Tag','CorrMatCLim2Edit');
h.Edit.CMX1                         = findobj('Tag','CorrMatXlwnEdit');
h.Edit.CMX2                         = findobj('Tag','CorrMatXuwnEdit');
h.Edit.CMY1                         = findobj('Tag','CorrMatYlwnEdit');
h.Edit.CMY2                         = findobj('Tag','CorrMatYuwnEdit');
h.Figure.CorrMat                    = findobj('Tag','CorrMatrixWindow');
h.Menu.CMVPlt2Dspec                 = findobj('Tag','CMVPlt2Dspec');
h.Menu.CMVdspmaxcov                 = findobj('Tag','CMVdspmaxcov');
h.Menu.CMVgetxtrc                   = findobj('Tag','CMVgetytrc');
h.Menu.CMVgetytrc                   = findobj('Tag','CMVgetxtrc');
h.Menu.CMVgetcorr                   = findobj('Tag','CMVgetcorr');
h.Menu.CMVinvCmap                   = findobj('Tag','CMVinvCmap');
h.Menu.CMVgetImg                    = findobj('Tag','CMVgetImg');
h.Menu.CMVColbar                    = findobj('Tag','CMVColbar');
h.Menu.CMVupdplt                    = findobj('Tag','CMVupdplt');
h.Popupmenu.Type2DCOS               = findobj('Tag','Type2DCOSPopupmenu');
h.Popupmenu.ContrNlns               = findobj('Tag','ContourNlinesPopupmenu');
h.UIMenu.Xdata                      = findobj('Tag','loadxuimenu');
h.UIMenu.Ydata                      = findobj('Tag','loadyuimenu');

if isempty(get(h.UIMenu.Xdata,'UserData')) == 1
    set(h.Edit.CMX1,'Enable','off');
    set(h.Edit.CMX2,'Enable','off');
    xdata                           = 0;
else
    xdata                           = 1;
end

if isempty(get(h.UIMenu.Ydata,'UserData')) == 1
    set(h.Edit.CMY1,'Enable','off');
    set(h.Edit.CMY2,'Enable','off');
    ydata                           = 0;
else
    ydata                           = 1;
end

% deactivate UImenu and button "create 2D spectrum" in case of no x-, or y-data
if xdata == 0 || ydata == 0
    set(h.Menu.CMVPlt2Dspec,'Enable','off');
    set(h.Button.PlotCM,'UserData',[],'Enable','off');    
end

delete(get(h.Axis.Corr,'Children'));
set(h.Button.setCLim,'Enable','off');

set(h.Edit.CorrMatXtrace,'Enable','off');
set(h.Edit.CorrMatYtrac,'Enable','off');
set(h.Edit.CorrMatCLim1,'Enable','off');
set(h.Edit.CorrMatCLim2,'Enable','off');
set(h.Ctxt.Save,'Enable','off');
set(h.Checkbox.CorrMContr,'Value',0,'Enable','off');
set(h.Checkbox.FillContour,'Value',0,'Enable','off');
set(h.Menu.CMVdspmaxcov,'Enable','off');
set(h.Menu.CMVgetxtrc,'Enable','off');
set(h.Menu.CMVgetytrc,'Enable','off');
set(h.Menu.CMVgetcorr,'Enable','off');
set(h.Menu.CMVinvCmap,'Enable','off');
set(h.Menu.CMVgetImg,'Enable','off');
set(h.Menu.CMVColbar,'Enable','off');
set(h.Menu.CMVupdplt,'Enable','off');
set(h.Popupmenu.ContrNlns,'Enable','off');
set(h.Figure.CorrMat,'WindowButtonMotionFcn','');

%% ************************************************************************
function write2bmp(AxisHandle,FigureHandle,uiputdescript)
% *************************************************************************

if isempty(AxisHandle) == 0
  Pos                               = get(AxisHandle,'Position');
else
  Pos                               = get(FigureHandle,'Position');
  Pos(1:2)                          = [1 1];
end

F                                   = getframe(FigureHandle,Pos);
[X,~]                               = frame2im(F);
[SaveFile,SavePath]                 = uiputfile('*.bmp',uiputdescript);
if ischar(SaveFile) == 1  
   cd(SavePath);
   if length(SaveFile) > 4 && strcmp(SaveFile(length(SaveFile)-3:length(SaveFile)),'.bmp') == 1
      imwrite(X,SaveFile,'bmp');
   else	 
      imwrite(X,[SaveFile '.bmp'],'bmp');
   end
end

%% ************************************************************************
function [bg,bgf,bge,bgb,fgt,fgr,fgb,bgs,mrl] = cols
% *************************************************************************

bg                                  = [215 220 240]/255;                    % standard background color for figures, etc.
bgf                                 = [185 209 240]/255;                    % standard color of frame uicontrols
bgb                                 = [225 235 255]/255;                    % color of button uicontrols
bgs                                 = [158 191 227]/255;                    % color of table elements in the main gui
bge                                 = [250 250 250]/255;                    % background color of edit uicontrols
fgt                                 = [0   0   0  ]/255;                    % foregroundcolor text
fgr                                 = [255 0   0  ]/255;                    % red foregroundcolor for some text elements
fgb                                 = [0   0   255]/255;                    % blue text color in main gui
mrl                                 = [220 200 248]/255;                    % color of margin of the main gui 

%% ************************************************************************
function setButtonFormat(handle,bg)
% *************************************************************************

if nargin == 1
    bg                              = [0.752941 0.752941 0.752941];
end    
set(handle,'Units','pixel','BackgroundColor',bg,'FontSize',8,'FontWeight','bold','FontName','Arial');


%% ************************************************************************
function setTextFormat(handle,bg,fg)
% *************************************************************************

if nargin == 1
    bg                              = [0.8 0.8 0.8];
    fg                              = [0 0 0];
end    
set(handle,'Units','pixel','ForegroundColor',fg,'BackgroundColor',bg,'FontName','Arial','FontWeight','bold','FontSize',8,'Style','text','HorizontalAlignment','left');


%% ************************************************************************
function setEditFormat(handle,bg,fg)
% *************************************************************************

if nargin == 1
    fg                              = [1 1 1];
end    
set(handle,'FontName','Arial','FontSize',8,'HorizontalAlignment','left','Units','pixel','BackgroundColor',bg,'ForegroundColor',fg);

%% ************************************************************************
function setAxisFormat(handle,bg,XLim,YLim,view)
% *************************************************************************

if nargin == 1
    bg                              = [0.8 0.8 0.8];
    XLim                            = [0 1];
    YLim                            = [0 1];
    view                            = [180, 270];
elseif nargin == 4
    view                            = [180, 270];
end    

set(handle,'Units','pixel','Color',bg,'Box','on','FontName','Arial','FontWeight','bold','FontSize',8,'XDir','normal','YDir','normal','XMinorTick','off','YMinorTick','off', ...                
           'TickDir','out','TickLength',[0.002 0],'XAxisLocation','bottom','YAxisLocation','left','XGrid','off','YGrid','off','XLim',XLim,'YLim',YLim,'XLimMode','manual','YLimMode','manual','View',view);