 function SimDOSY()
%% Simulated DOSY
%
%   --------------------------------INPUT-------------------------------------------------
%   
%   --------------------------------OUTPUT------------------------------------------------
%
%   --------------------------------REFERENCE---------------------------------------------
%
%   This is a part of the GNAT
%   Copyright  2024  <Mathias Nilsson>%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You should have received a copy of the GNU General Public License along
%   with this program; if not, write to the Free Software Foundation, Inc.,
%   51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
%
%   Dr. Mathias Nilsson
%   School of Chemistry, University of Manchester,
%   Oxford Road, Manchester M13 9PL, UK
%   Telephone: +44 (0) 161 306 4465
%   Fax: +44 (0)161 275 4598
%
%   Hugo da Silva Rocha, Undergrad Studant
%   Institute of Chemistry, Univeristy of Brasilia,
%   POBOX 70910-900, Asa Norte - Brasília (DF), Brazil
%   rocha.hugo@aluno.unb.br

%% Setup the GUI CONTROLS
SimDOSY.version='Simulation DOSY';
hSimFigure = figure(...
    'Units','normalized',...
    'MenuBar','none',...
    'Name',SimDOSY.version,... 
    'NumberTitle','Off',...
    'Toolbar','Figure',...
    'OuterPosition',[0.0 0.0 0.6 0.45],...
    'Tag','SinDOSY',...
    'Color','w',...
    'Visible','on');

SimDOSY.ForceCloseFlag = 1;
SimDOSY.hSimFigure = hSimFigure;
movegui(hSimFigure,'center')

%Clean up the Toolbar, removing things we don't need
    tmp = findall(hSimFigure,'ToolTipString','New Figure');
    set(tmp,'Visible','Off')
    tmp = findall(hSimFigure,'ToolTipString','Open File');
    set(tmp,'Visible','Off')
    tmp = findall(hSimFigure,'ToolTipString','Link Plot');
    set(tmp,'Visible','Off')
    tmp = findall(hSimFigure,'ToolTipString','Insert Legend');
    set(tmp,'Visible','Off')
    tmp = findall(hSimFigure,'ToolTipString','Rotate 3D');
    set(tmp,'Visible','Off')
    tmp = findall(hSimFigure,'ToolTipString','Brush/Select Data');
    set(tmp,'Visible','Off')
    tmp = findall(hSimFigure,'ToolTipString','Insert Colorbar');
    set(tmp,'Visible','Off')
guidata(hSimFigure,SimDOSY);

%% Setup the SimDOSY Painel
% pROCESS
hSimDOSYMajorPanel=uipanel(...
    'Parent',hSimFigure,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.0 0.0 0.99 0.99]);

% pROCESS
hSimDOSYProcessPanel=uipanel(...
    'Parent',hSimDOSYMajorPanel,...
    'Title','Process',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.5 0.3 0.45 ]);
%hRandomDOSYButton=
uicontrol(...
    'Parent',hSimDOSYProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Generate a DOSY dataset with random peaks',...
    'Position',[0.55 0.6 0.4 0.3],...
    'String','Random',...
    'CallBack', { @RandomDOSYButton_Callback});
%hUpdateSynthButton=
uicontrol(...
    'Parent',hSimDOSYProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Generate a DOSY dataset with the table parameters',...
    'Position',[0.05 0.59 0.41 0.32],...
    'String','Generate DOSY',...
    'CallBack', { @UpdateSynthButton_Callback});
%hUpdateTableButton=
uicontrol(...
    'Parent',hSimDOSYProcessPanel,...
    'Style','PushButton',...
    'Units','Normalized',...
    'TooltipString','Update the Table based on Spectral parameters',...
    'Position',[0.3 0.2 0.4 0.3],...
    'String','Update table',...
    'CallBack', { @UpdateTableButton_Callback});

% Options
hSpecOpt=uibuttongroup(...
    'Parent',hSimDOSYMajorPanel,...
    'Title','Options',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.02 0.05 0.3 0.45]);
%hText3Dplot=
uicontrol(...
    'Parent',hSpecOpt,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.0 0.18 0.3 0.3 ],...
    'horizontalalignment','r',...
    'String','3D plot:' );
hCheck3Dplot = uicontrol(...
    'Parent',hSpecOpt,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'Position',[0.33 0.3 0.3 0.2]);
%hTextUseNUG=
uicontrol(...
    'Parent',hSpecOpt,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.0 0.68 0.3 0.2 ],...
    'horizontalalignment','r',...
    'String','Add NUG:' );
hCheckUseNUG = uicontrol(...
    'Parent',hSpecOpt,...
    'Style','Checkbox',...
    'Units','normalized',...
    'horizontalalignment','l',...
    'TooltipString',...
    'Use the "Settings" menu to set Non Uniform Gradient (NUG) coefficients',...
    'Position',[0.33 0.7 0.3 0.2]);
%hTextnoise=
uicontrol(...
    'Parent',hSpecOpt,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.48 0.68 0.2 0.2 ],...
    'horizontalalignment','r',...
    'String','SNR: 1/',...
    'TooltipString',...
    'Desired Signal to Noise Ratio (SNR) in the spectrum');
hEditnoise=uicontrol(...
    'Parent',hSpecOpt,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The amount of random noise',...
    'Position',[0.7 0.7 0.2 0.24 ]);

% Spectral parameters
hSpecParam=uipanel(...
    'Parent',hSimDOSYMajorPanel,...
    'Title','Spectral parameters',...
    'TitlePosition','centertop',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.35 0.05 0.3 0.9 ]);
%hTextnpeaks=
uicontrol(...
    'Parent',hSpecParam,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.15 0.85 0.2 0.1 ],...
    'horizontalalignment','l',...
    'String','Peaks' );
hEditnpeaks=uicontrol(...
    'Parent',hSpecParam,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The number of peaks in the spectrum',...
    'Position',[0.5 0.85 0.3 0.12 ]);
%hTextsw=
uicontrol(...
    'Parent',hSpecParam,...
    'Style','text',...
    'String','Spectral width',...
    'Units','Normalized',...
    'Position',[0.15 0.70 0.4 0.1],...
    'horizontalalignment','l');
hEditsw=uicontrol(...
    'Parent',hSpecParam,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The spectral width (Hz)',...
    'Position',[0.5 0.7 0.3 0.12]);
%hTextnp=
uicontrol(...
    'Parent',hSpecParam,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.15 0.55 0.4 0.1],...
    'horizontalalignment','l',...
    'String','No. points' );
hEditnp2=uicontrol(...
    'Parent',hSpecParam,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The number of points representing the dataset',...
    'Position',[0.5 0.55 0.3 0.12]);
%hTextmingrad=
uicontrol(...
    'Parent',hSpecParam,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.15 0.40 0.4 0.1],...
    'horizontalalignment','l',...
    'String','Min. grad.' );
hEditmingrad=uicontrol(...
    'Parent',hSpecParam,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The minimum gradient in the diffusion experiment (T/m)',...
    'Position',[0.5 0.40 0.3 0.12]);
%hTextmaxgrad=
uicontrol(...
    'Parent',hSpecParam,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.15 0.25 0.4 0.1 ],...
    'horizontalalignment','l',...
    'String','Max. grad.' );
hEditmaxgrad=uicontrol(...
    'Parent',hSpecParam,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The maximum gradient in the iffusion experiment (T/m)',...
    'Position',[0.5 0.25 0.3 0.12 ]);
%hTextni=
uicontrol(...
    'Parent',hSpecParam,...
    'Style','text',...
    'Units','Normalized',...
    'Position',[0.15 0.10 0.4 0.1 ],...
    'horizontalalignment','l',...
    'String','No. grad. lev.' );
hEditni=uicontrol(...
    'Parent',hSpecParam,...
    'Style','edit',...
    'BackgroundColor','w',...
    'Units','Normalized',...
    'TooltipString','The number of increments/gradient levels of the DOSY',...
    'Position',[0.5 0.1 0.3 0.12 ]);

% Peak parameter
%hTextSynthGenDOSY=
uicontrol(...
    'Parent',hSimDOSYMajorPanel,...
    'Style','text',...
    'Units','Normalized',...
    'FontWeight','bold',...
    'Position',[0.78 0.85 0.3 0.1],...
    'horizontalalignment','l',...
    'String','Peak parameters' );
hTableSynthPeaks=uitable(...
    'parent',hSimDOSYMajorPanel,...
    'units','normalized',...
    'columneditable',[true true true true true],...
    'columnname',{'Freq.','D','Amp,','Lw','MP'},...
    'columnformat',{'numeric','numeric','numeric','numeric','numeric'},...
    'columnwidth',{'auto'},...
    'rowname',{'numbered'},...
    'position',[0.68 0.05 0.3 0.80 ],...
    'Data',zeros(10,5));


%% Main Callbacks
%----Synthesise DOSY------------------
    function RandomDOSYButton_Callback(source,eventdata)

        hMainFigure = findobj('Type','figure','Tag','MainFigure');
        if ~isempty(hMainFigure)
            NmrData = guidata(hMainFigure(1));
        
            % read parameters
            SynthData.sw=str2double(get(hEditsw,'string'));
            SynthData.np=str2double(get(hEditnp2,'string'));
            SynthData.mingrad=str2double(get(hEditmingrad,'string'));
            SynthData.maxgrad=str2double(get(hEditmaxgrad,'string'));
            SynthData.ni=str2double(get(hEditni,'string'));
            SynthData.npeaks=str2double(get(hEditnpeaks,'string'));
            SynthData.noise=str2double(get(hEditnoise,'string'));
            SynthData.meshplot=get(hCheck3Dplot,'Value');
            SynthData.multiplicity=ones(1,SynthData.npeaks);
            SynthData.lw=ones(1,SynthData.npeaks);
            SynthData.Amps=ones(1,SynthData.npeaks);
            if get(hCheckUseNUG,'value')==1
                SynthData.NUGs=NmrData.nug;
            else
                SynthData.NUGs=0;
            end
            RandSynthData=SyntheticDOSY(SynthData);
            
            NmrData.RandSynthData=RandSynthData;
            
            set(0,'CurrentFigure',hMainFigure)
            % Clear the current data structure
            Initiate_NmrData();
            
            % Copy in the relevant synthesised bits
            NmrData.FID=RandSynthData.FIDs;
            NmrData.sw=RandSynthData.sw;
            NmrData.np=RandSynthData.np;
            NmrData.fn=RandSynthData.np;
            NmrData.ngrad=RandSynthData.ngrad;
            NmrData.arraydim=RandSynthData.ngrad;
            NmrData.at=RandSynthData.at;
            NmrData.gamma=RandSynthData.gamma;
            NmrData.DELTA=RandSynthData.DELTA;
            NmrData.delta=RandSynthData.delta;
            NmrData.Gzlvl=RandSynthData.gradlvl;
            NmrData.dosyconstant=RandSynthData.dosyconstant;
            NmrData.issynthetic=1;
            NmrData.filename='SyntheticDOSY';
            NmrData.sp=-0.5*RandSynthData.sw;
            NmrData.lp=0;
            NmrData.rp=0;
            NmrData.sfrq=RandSynthData.sfrq;
            
            % Generate data structure and update table
            TableData(:,1)=RandSynthData.Freqs;
            TableData(:,2)=RandSynthData.Dvals*1e10;
            TableData(:,3)=RandSynthData.Amps;
            TableData(:,4)=SynthData.lw;
            TableData(:,5)=SynthData.multiplicity;
            
            set(hTableSynthPeaks,'Data',TableData)
            
            guidata(hMainFigure,NmrData);
            figure(hMainFigure)
            Setup_NmrData()
            % calcRMSnoise(NmrData.SPECTRA,NmrData.Specscale)
            
            PlotSpectrum()
        else
        end
    end
    function UpdateSynthButton_Callback(source,eventdata)

        hMainFigure = findobj('Type','figure','Tag','MainFigure');
        if ~isempty(hMainFigure)
            NmrData=guidata(hMainFigure);
            % read parameters
            SynthData.sw=str2double(get(hEditsw,'string'));
            SynthData.np=str2double(get(hEditnp,'string'));
            SynthData.mingrad=str2double(get(hEditmingrad,'string'));
            SynthData.maxgrad=str2double(get(hEditmaxgrad,'string'));
            SynthData.ni=str2double(get(hEditni,'string'));
            SynthData.npeaks=str2double(get(hEditnpeaks,'string'));
            SynthData.noise=str2double(get(hEditnoise,'string'));
            SynthData.meshplot=get(hCheck3Dplot,'Value');
            if get(hCheckUseNUG,'value')==true
                SynthData.NUGs=NmrData.nug;
                SynthData.probename=NmrData.probename;
                SynthData.nugcal=NmrData.gcal;
            else
                SynthData.NUGs=0;
                SynthData.probename='';
                SynthData.nugcal=0;
            end
            
            % Get table data
            SynthTableData=get(hTableSynthPeaks,'Data');
            SynthData.Freqs=SynthTableData(:,1);
            SynthData.Dvals=SynthTableData(:,2);
            SynthData.Amps=SynthTableData(:,3);
            SynthData.lw=SynthTableData(:,4);
            SynthData.multiplicity=SynthTableData(:,5);
            
            RandSynthData=SyntheticDOSY(SynthData);
            
            NmrData.RandSynthData=RandSynthData;
            
            set(0,'CurrentFigure',hMainFigure)
            
            % Clear the current data structure
            Initiate_NmrData();
            
            % Copy in the relevant synthesised bits
            % NmrData.SPECTRA=RandSynthData.SPECTRA;
            NmrData.FID=RandSynthData.FIDs;
            NmrData.sw=RandSynthData.sw;
            NmrData.np=RandSynthData.np;
            NmrData.fn=RandSynthData.np;
            NmrData.ngrad=RandSynthData.ngrad;
            NmrData.arraydim=RandSynthData.ngrad;
            NmrData.at=RandSynthData.at;
            NmrData.gamma=RandSynthData.gamma;
            NmrData.DELTA=RandSynthData.DELTA;
            NmrData.delta=RandSynthData.delta;
            NmrData.Gzlvl=RandSynthData.gradlvl;
            NmrData.dosyconstant=RandSynthData.dosyconstant;
            NmrData.issynthetic=1;
            NmrData.filename='SyntheticDOSY';
            NmrData.sp=-0.5*RandSynthData.sw;
            NmrData.lp=0;
            NmrData.rp=0;
            NmrData.sfrq=RandSynthData.sfrq;
            NmrData.nug= SynthData.NUGs;
            NmrData.probename=SynthData.probename;
            NmrData.gcal=SynthData.nugcal;
            
            % Generate data structure and update table
            TableData(:,1)=RandSynthData.Freqs;
            TableData(:,2)=RandSynthData.Dvals*1e10;
            TableData(:,3)=RandSynthData.Amps;
            TableData(:,4)=SynthData.lw;
            TableData(:,5)=SynthData.multiplicity;
            
            set(hTableSynthPeaks,'Data',TableData)
            
            guidata(hMainFigure,NmrData);
            
            Setup_NmrData()
            
            % plot
            PlotSpectrum()
        end
    end
    function UpdateTableButton_Callback(source,eventdata)
        SynthTableData=get(hTableSynthPeaks,'Data');
        if str2double(get(hEditnpeaks,'string')) > length(SynthTableData(:,1))
            diff=str2double(get(hEditnpeaks,'string'))-length(SynthTableData(:,1));
            SynthTableData(end+1:end+diff,1:5)=repmat([0 1 1 1 1]',1,diff)';
        elseif  str2double(get(hEditnpeaks,'string')) < length(SynthTableData(:,1))
            diff=abs(str2double(get(hEditnpeaks,'string'))-length(SynthTableData(:,1)));
            SynthTableData=SynthTableData(1:end-diff,:);
        else
            %the table is the right size
        end
        set(hTableSynthPeaks,'Data',SynthTableData)
    end

 end