function deltaB_gmarker
 
% determine the magnetic field shift for the calibration of a spectrum without any gmarker from a spectrum with g-marker
% normalisation par le nb de scan 
% gmarker in corrige en frequence pour frequece gmarker out
% june 2023
% EE: nouvelle valeur Bruker marker accessory
%EE oct2025 compatibilite avec Matlab2025

clear;
close;
clc;

versionyear=version('-release');
versionyear=str2double(versionyear(1:4)); %annee version matlab
if versionyear>2014
        hinit=gobjects; %handle=structure
elseif versionyear==2014 && strcmp('b',versionletter)
        hinit=gobjects; %handle=structure a partir de 2014b
else
        hinit=NaN; %handle=double
end

if versionyear>=2025
    tickNaN=[];
else
    tickNaN=NaN;
end

hplotdiff=hinit; %handle spectre difference
hplotdiffsmooth=hinit; %handle spectre difference smooth

kolor= [0.8500, 0.3250, 0.0980; %1  pour les differentes composantes
        0, 0.4470, 0.7410]; %2


inout={'in','out'};
ftsz=12;%fontsize
standard={'Bruker Marker',1.9800;
          'weak pitch',2.0028;
          'DPPH',2.0036}; %'Cr',1.979896;
 
Bg=[];% init champ correspondant a la valeur de g du marqueur pour la freq ref (2 = out)  
hplot={hinit,hinit};% init handles spectres exp
hline=hinit; % init handle ligne verticale g marker
hrect=hinit;%init handle rectangle encadrant signal marker
Bexpinit=cell(1,2); %init champs magnetiques non corriges
filename=cell(1,2);
path2exp=cell(1,2);
spec={}; % init spectres exp
expfreq=[]; % freq experimentales

jjmin=[]; %indice encadrant signal du gmarker
jjmax=[];

Bg=[];%champ magnetque g-marker a la frequence g out

%% figure
hdeltaBmain=figure();

scrszpix = get(0,'ScreenSize'); %taille ecran [left, bottom, width, height] en pixels
%scrszcm=scrszpix/get(0,'screenpixelsperinch')*2.54; %1inch=2.54cm  taille ecran en cm

set(hdeltaBmain,'Units','pixels',...
    'Outerposition',[scrszpix(3)/7 0.1*scrszpix(4) 700 scrszpix(4)*0.9],...
    'Name','dellaB from g-marker',...
    'Menubar', 'none', 'Toolbar', 'none',...%'resize','off',...
    'NumberTitle','off','DoubleBuffer','on',...'CloseRequestFcn',@closeSimLabel,...
    'color',get(0,'DefaultUicontrolBackgroundColor'));


%% panel IN =>1
hgin = uipanel(...
        'Parent',hdeltaBmain,...
        'Title','g-marker in',...
        'foreground',kolor(1,:),...
        'fontweight','bold',...
        'fontsize',1.1*ftsz,...
        'Position',[0.025 0.01 0.3 0.25]);


    uicontrol('Style','pushbutton',...
        'String','Load (in)',...
        'backgroundcolor',[102 255 204]/255,...
        'Units','Normalized',...
        'pos',[0.3 0.75 0.40 0.2],...
        'parent',hgin,...
        'Callback', {@loadspec,1},...
        'TooltipString',sprintf('Load new experimental spectrum with g-marker.\nIf available, the magnetic field of ''in'' is corrected by the frequency of ''out''.'),...
        'fontunits','pixels',...
        'fontsize',ftsz);
    
    hfilename{1}=uicontrol('Style','text',...
        'Units','Normalized',...
        'pos',[0.02 0.5 0.95 0.15],...
        'parent',hgin,...
        'String','No loaded spectrum',...
        'HorizontalAlignment','center',...'BackgroundColor','w',...
         'fontunits','pixels',...
         'fontsize',ftsz);
     
     %%%%% delatB in
    %storedeltaBinstatus='off';
    
    uicontrol('Style','text','Units','Normalized',...
        'pos',[0.1 0.2 0.30 0.2],...
        'parent',hgin,...
        'String',{'deltaB =';'(real-read)'},...
        'HorizontalAlignment','center',...'backgroundcolor','c',...
        'fontunits','pixels',...
        'fontsize',ftsz,...
        'TooltipString',sprintf('Experimental offset of magnetic field (g-marker in)'));
    
    hdeltaBval{1}=uicontrol('Style','edit',...
        'Units','Normalized',...
        'pos',[0.4 0.25 0.30 0.2],'BackgroundColor','w',...
        'parent',hgin,...
        'Callback', {@setdeltaB,1},...
        'enable','off',...
        'fontunits','pixels','fontsize',ftsz,...
        'TooltipString',sprintf('Experimental offset of magnetic field (g-marker in)'));
   
   uicontrol('Style','text',...
       'Units','Normalized',...
       'pos',[0.73 0.25 0.12 0.15],...
        'parent',hgin,...
        'String','mT',...'backgroundcolor','w',...
        'HorizontalAlignment','left',...
        'fontunits','pixels',...
        'fontsize',ftsz);

%     hstoredeltaBin=uicontrol('Style','pushbutton',...
%         'Units','Normalized',...
%         'pos',[0.27 0.02 0.30 0.15],...'BackgroundColor','w',...
%         'parent',hgin,...
%         'String','Store',...
%         'Callback', {@storedeltaB,1},...
%         'fontunits','pixels',...
%         'fontsize',ftsz,...
%         'TooltipString','Store deltaB (g-marker in) in memory');
    
    hsamedeltaB=uicontrol('Style','checkbox',...
        'Parent',hgin,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'Callback',@cllbckchk,...'backgroundcolor','w',...
        'FontSize',ftsz,...
        'Position',[0.6 0.01 0.4 0.15],...
        'String','same deltaB',...
        'TooltipString','If checked, same deltaB for both spectra',...
        'Value',1);


%% panel OUT =>2
hgout = uipanel(...
        'Parent',hdeltaBmain,...
        'Title','g-marker out = ref.',...
        'foreground',kolor(2,:),...
        'fontweight','bold',...
        'fontsize',1.1*ftsz,...
        'Position',[0.35 0.01 0.3 0.25]);

    uicontrol('Style','pushbutton',...
        'String','Load (out)',...
        'backgroundcolor',[102 255 204]/255,...
        'Units','Normalized',...
        'pos',[0.3 0.75 0.40 0.2],...
        'parent',hgout,...
        'Callback', {@loadspec,2},...
        'TooltipString',sprintf('Load new experimental spectrum without g-marker\n *.DSC and *.DTA file must be present in the same folder'),...
        'fontunits','pixels',...
        'fontsize',ftsz);
    
    hfilename{2}=uicontrol('Style','text',...
        'Units','Normalized',...
        'pos',[0.02 0.5 0.95 0.15],...
        'parent',hgout,...
        'String','No loaded spectrum',...
        'HorizontalAlignment','center',...'BackgroundColor','w',...
         'fontunits','pixels',...
         'fontsize',ftsz);
     
     %%%%% delatB out
    storedeltaBoutstatus='off';
    
    uicontrol('Style','text','Units','Normalized',...
        'pos',[0.1 0.2 0.30 0.2],...
        'parent',hgout,...
        'String',{'deltaB =';'(real-read)'},...
        'HorizontalAlignment','center',...'backgroundcolor','c',...
        'fontunits','pixels',...
        'fontsize',ftsz,...
        'TooltipString','Experimental offset of magnetic field (g-marker out)');
    
    hdeltaBval{2}=uicontrol('Style','edit',...
        'Units','Normalized',...
        'pos',[0.41 0.25 0.30 0.2],'BackgroundColor','y',...
        'parent',hgout,...
        'Callback', {@setdeltaB,2},...
        'fontunits','pixels','fontsize',ftsz,...
        'TooltipString','Experimental offset of magnetic field (g-marker out)');
   
   uicontrol('Style','text',...
       'Units','Normalized',...
       'pos',[0.73 0.25 0.3 0.15],...
        'parent',hgout,...
        'String','mT',...
        'HorizontalAlignment','left',...
        'fontunits','pixels',...
        'fontsize',ftsz);

    hstoredeltaB=uicontrol('Style','pushbutton',...
        'Units','Normalized',...
        'pos',[0.35 0.02 0.30 0.15],...'BackgroundColor','w',...
        'parent',hgout,...
        'String','Store',...
        'Callback', @storedeltaB,...
        'fontunits','pixels',...
        'fontsize',ftsz,...
        'TooltipString','Store deltaB in memory for loaded spectra');

%% panel settings
hsettings = uipanel(...
        'Parent',hdeltaBmain,...
        'Title','settings',...
        'fontsize',ftsz,...
        'Position',[0.675 0.01 0.3 0.21]);
    
    hslidone = uicontrol(...
        'Parent',hsettings,...
        'Units','normalized',...
        'BackgroundColor',[0.9 0.9 0.9],...
        'Callback',@cllbckslidone,...
        'enable','off',...
        'Position',[0.36 0.58 0.62 0.15],...
        'TooltipString','Shift horizontally only one spectrum (g-marker in)',...        'Min',gmin,...2.00000        'Max',gmax,...2.0100,... 'SliderStep',[minstepg maxstepg],...[1e-5/2 50e-5/2],...
        'Min',-5,...
        'Max',5,...
        'SliderStep',[5e-4 5e-3],...    
        'Style','slider');    
     
    hslidoneinfo=uicontrol(...
        'Parent',hsettings,...
        'Units','normalized',...
        'FontUnits','pixels',...'BackgroundColor','w',...
        'FontSize',ftsz,...
        'Position',[0.02 0.56 0.32 0.15],...
        'TooltipString','Shift horizontally only one spectrum (g-marker in)',...
        'string','Shift one',...
        'enable','off',...
        'Style','text');

     hslidboth = uicontrol(...
        'Parent',hsettings,...
        'Units','normalized',...
        'BackgroundColor',[0.9 0.9 0.9],...
        'Callback',@cllbckslidboth,...
        'Position',[0.36 0.8 0.62 0.15],...
        'TooltipString','Shift horizontally both spectra',...        
        'Min',-5,...
        'Max',5,...
        'SliderStep',[5e-4 5e-3],...
        'Style','slider');    
    
     uicontrol(...
        'Parent',hsettings,...
        'Units','normalized',...
        'FontUnits','pixels',...'BackgroundColor','w',...
        'FontSize',ftsz,...
        'Position',[0.02 0.78 0.32 0.15],...
        'TooltipString','Shift horizontally both spectra',...
        'string','Shift both',...
        'Style','text');
   
    %%%% g-marker type %%%%%%%%%
    uicontrol('Style','text',...
        'Units','Normalized',...
        'pos',[0.02 0.38 0.3 0.12],...'backgroundcolor','w',...
        'parent',hsettings,...
        'Units','Normalized',...
        'String','g-marker :',...
        'fontsize',0.8*ftsz,...
        'horizontalalignment','right');

    hstandardchoice=uicontrol('Style','popupmenu',...
        'Units','Normalized',...
        'pos',[0.34 0.39 0.5 0.16],...
        'parent',hsettings,...
        'BackgroundColor','w',...
        'Callback',@select_standard,...
        'string',standard(:,1),...
        'fontsize',0.7*ftsz,...
        'value',1,...
        'horizontalalignment','center');

    hgreel=uicontrol('Style','text',...
        'Units','Normalized',...
        'pos',[0.5 0.22 0.5 0.12],...
        'parent',hsettings,...
        'Units','Normalized',...'backgroundcolor','w',...
        'String',['g_real=',num2str(standard{1,2},'%5.4f')],...
        'fontsize',0.7*ftsz,...
        'horizontalalignment','left');
    
    
    %%%% signal g-marker%%%%  
    uicontrol('Style','text',...
        'Units','Normalized',...
        'pos',[0.01 0.02 0.2 0.15],...'BackgroundColor','w',....
        'parent',hsettings,...
        'String','From',...
        'HorizontalAlignment','right',...
        'tooltipstring','g-marker signal',...
        'fontsize',0.8*ftsz);
    
    hBgmin=uicontrol('Parent',hsettings,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor',[1 1 224/255],...
        'Callback',@dispgmarkerrange,...
        'FontSize',1.1*ftsz,...
        'Position',[0.22 0.04 0.25 0.15],...
        'Style','edit');
    
    uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.48 0.02 0.1 0.15],...'BackgroundColor','w',....
            'parent',hsettings,...
            'String','to',...
            'HorizontalAlignment','center',...
            'tooltipstring','g-marker signal',...
            'fontsize',0.8*ftsz);    
    
    hBgmax=uicontrol('Parent',hsettings,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor',[1 1 224/255],...
        'Callback',@dispgmarkerrange,...
        'FontSize',1.1*ftsz,...
        'Position',[0.60 0.04 0.25 0.15],...
        'Style','edit');
    
    uicontrol('Style','text',...
        'Units','Normalized',...
        'pos',[0.86 0.02 0.1 0.15],...'BackgroundColor','w',...
        'parent',hsettings,...
        'String','mT',...
        'tooltipstring','g-marker signal',...
        'HorizontalAlignment','left','fontsize',0.8*ftsz);    

%% graphes
    hspecaxes=axes('parent',hdeltaBmain,... axes avec spectres 
              'Position',[0.025 0.58 0.955 0.40],...
        'Ytick',tickNaN,'Box','on','Xtick',tickNaN);
    hold all
    hdiffaxes=axes('parent',hdeltaBmain,... axe avec difference
        'Position',[0.025 0.32 0.955 0.22],...
        'Ytick',tickNaN,'Box','on');
    hold all
    
title('out (ref) - in')
 xlabel(hdiffaxes,'Magnetic Field [mT]','fontsize',ftsz);   
%% info ecart entre champ(g reel) et champ(g exp)
 hinfo = uicontrol('Style','text',...
        'Units','Normalized',...
        'pos',[0.675 0.23 0.3 0.04],...'BackgroundColor','c',....
        'parent',hdeltaBmain,...
        'String','',...
        'HorizontalAlignment','right',...
        'tooltipstring','Gap between real g value and exp. g value of the g-marker',...
        'fontsize',1.2*ftsz,...
        'fontweight','bold');

%% functions

    function loadspec(~,~,n)
        
            % n=1=> in   / n=2 => out
          [filename{n},path2exp{n}]=uigetfile({'*.DSC;*.SPC','Bruker (*.DSC,*.SPC)';...
                                  '*.xml;*.spe','Magnettech (*.xml,*.spe)';'*.*','All Files (*.*)'},...
                                  ['Select Spectrum (g-marker ',inout{n},')']); %ouverture boite de dialogue dans repertoire courant (.DSC selectionnes)

         if not(isnumeric(filename{n})) %no cancel;
                [B,spec{n},param]=eprload(fullfile(path2exp{n},filename{n}));
                spec{n}=real(spec{n})/param.AVGS; %EMX: enregistrement sous forme complexe normaisation/nb scan

                if isfield(param,'MWFQ')
                    expfreq(n)=param.MWFQ*1e-9; %frequence exp en GHz from ELEXSYS
                    Bexpinit{n}=B/10;% B en G Bexpinit en mT
                elseif isfield(param,'MF')
                    expfreq(n)=param.MF; %en GHz from ESP
                    Bexpinit{n}=B/10;% B en G Bexpinit en mT
                elseif isfield(param,'MwFreq')
                    expfreq(n)=param.MwFreq; %en GHz from Magnettech (.xml)
                    Bexpinit{n}=B;% B et Bexpinit en mT
                elseif isfield(param,'mwFreq')
                    expfreq(n)=param.mwFreq; %en GHz from Magnettech (.spe)
                    Bexpinit{n}=B;% B et Bexpinit en mT    
                else
                    disp('No experimental frequency...')
                end
                
                expdeltaBf=[filename{n}(1:end-3),'mat']; %fichier contenant le deltaB s'il existe
                if exist(fullfile(path2exp{n},expdeltaBf), 'file')
                    load(fullfile(path2exp{n},expdeltaBf)); %definition de deltaB
                else
                    deltaB=0;
                end
                set(hdeltaBval{n},'String',num2str(deltaB,'%3.2f'));
                set(hfilename{n},'string',filename{n},'tooltipstring',path2exp{n}); %affichage nom de fichier
                
                
                %%%%%% deltaB differents? %%%%%%
                deltaB1=str2double(get(hdeltaBval{1},'String'));
                deltaB2=str2double(get(hdeltaBval{2},'String'));
                
                if ~isnan(deltaB1) && ~isnan(deltaB2)
                set(hslidboth,'value',deltaB2);
                if deltaB1==deltaB2
                    set(hsamedeltaB,'value',1)
                    set([hdeltaBval{1} hslidone hslidoneinfo],'enable','off') %in
                else
                    set(hsamedeltaB,'value',0)
                    set(hslidone,'value',deltaB1-deltaB2)
                    set([hdeltaBval{1} hslidone hslidoneinfo],'enable','on') %in
                end
                end
                
                %%%%%%% pour spectre difference %%%%%%%%
                if ~isempty(Bexpinit{2})
                    Bg=1e3*planck*expfreq(2)*1e9/bmagn/standard{get(hstandardchoice,'value'),2};%mT a la frequence g out
                    Bgmin=Bg-2;%mT
                    Bgmax=Bg+2;%mT
                    set(hBgmin,'string',num2str(Bgmin));
                    set(hBgmax,'string',num2str(Bgmax));
                    
                    nbel=numel(Bexpinit{2});
                    jj=1;
                    
                    if Bgmin<Bexpinit{2}(end) && Bgmax<=Bexpinit{2}(end)
                        while Bexpinit{2}(jj)<Bgmin
                         jj=jj+1;
                        end
                        jjmin=jj;
                        while Bexpinit{2}(jj)<Bgmax
                         jj=jj+1;
                        end     
                        jjmax=jj;
                    else
                        jjmin=1;
                        jjmax=nbel;
                    end
                end
                plotspec;
         end
    end

    function plotspec
        for i=1:2
            if ishandle(hplot{i})
                delete (hplot{i});
            end
        end
        
        alpha=1; %facteur correctif des freq a appliquer à gmarker in (gmarker out = ref)
        if ~isempty(Bexpinit{1}) %in
            if ~isempty(Bexpinit{2}) %spectre gmarker out (2) deja charge => correction g marker in(1)
                alpha=expfreq(2)/expfreq(1);
            end
            B1=alpha*Bexpinit{1}+str2double(get(hdeltaBval{1},'string'));
            hplot{1}=plot(hspecaxes,B1,spec{1},'linewidth',2,'color',kolor(1,:));
            
        else
            B1=[];
        end
        
        if ~isempty(Bexpinit{2}) %out = ref
            B2=Bexpinit{2}+str2double(get(hdeltaBval{2},'string'));
            hplot{2}=plot(hspecaxes,B2,spec{2},'linewidth',2,'color',kolor(2,:));
            
        else
            B2=[];
        end
        
        if ishandle(hplot{1}) || ishandle(hplot{2})
            set([hspecaxes,hdiffaxes],'xlim',[min(min([B1 B2])) max(max([B1 B2]))]);
           
        end
        
        %%%%%%%%%%%% spectre difference %%%%%%%%%%%%
        if ishandle(hplot{1}) && ishandle(hplot{2})
            if ishandle(hplotdiff)
                delete(hplotdiff)
            end
            if ishandle(hplotdiffsmooth)
                delete(hplotdiffsmooth)
            end
 
            %B2(1:20)'

            yin=interp1(B1,spec{1},B2,'spline'); %in sur grille du out B2
            yout_in=spec{2}-yin;
            hplotdiff=plot(hdiffaxes,B2,yout_in,'linewidth',2,'color',0.8*[1 1 1]);
            ysmooth=datasmooth(yout_in,10,'savgol');
            hplotdiffsmooth=plot(hdiffaxes,B2,ysmooth,'b');
            
            yscale=1.1*[min(yout_in(jjmin:jjmax)) max(yout_in(jjmin:jjmax))];
            set(hdiffaxes,'ylim',yscale);
            if ishandle(hline)
                delete(hline)
            end
            hline=plot(hdiffaxes,Bg*[1 1],yscale,'linewidth',2,'color','k');
            uistack(hline,'bottom');
            if ishandle(hrect)
                delete(hrect)
            end
            hrect=rectangle('parent',hdiffaxes,'position',...
                [B2(jjmin) 0.9*yscale(1) B2(jjmax)-B2(jjmin) 0.9*(yscale(2)-yscale(1))],'facecolor',[1 1 224/255],'edgecolor','none');
            uistack(hrect,'bottom');
                
            [~,indpicpos]=max(ysmooth(jjmin:jjmax)) ;%jjmax et jjmin pour plge du signal du marqueur 
            [~,indpicneg]=min(ysmooth(jjmin:jjmax)) ; %indpicpos et indpicneg = indices pics positif et negatif

            %%%% indication ecart entre B du greal et B du g exp
            if indpicpos>indpicneg
                ind1=indpicneg+jjmin-1;
                ind2=indpicpos+jjmin-1;
            else
                ind1=indpicpos+jjmin-1;
                ind2=indpicneg+jjmin-1;
            end
            Bzero=interp1(ysmooth(ind1:ind2),B2(ind1:ind2),0); % Champ de la raie exp du marqueur
            delta=abs(Bg-Bzero);
            set(hinfo,'string',[num2str(delta,'%4.3f'),' mT']);
            
        end
    end



    function setdeltaB(~,~,n)
        deltaB=str2double(get(hdeltaBval{n},'string'));
        if isnan(deltaB)
            deltaB=0;
        end
        set(hdeltaBval{n},'string',num2str(deltaB,'%3.2f'));
        
        if get(hsamedeltaB,'value') %si case checkee, seule deltaB out a pu etre change
            set(hdeltaBval{1},'string',num2str(deltaB,'%3.2f'));
        end
        
       % set(hdeltaBslid,'value',deltaB);
        plotspec        
    end

    function cllbckchk(~,~)
        if get(hsamedeltaB,'value')
            if ~isempty(get(hdeltaBval{2},'string'))
            set(hdeltaBval{1},'enable','off','string',num2str(get(hdeltaBval{2},'string'),'%3.2f'))
            end
            set([hslidone,hslidoneinfo],'enable','off')
        else
            set(hdeltaBval{1},'enable','on')
            set([hslidone,hslidoneinfo],'enable','on')
        end
        plotspec
    end

    function storedeltaB(~,~)
        deltaBin=str2double(get(hdeltaBval{1},'string'));
        deltaBout=str2double(get(hdeltaBval{2},'string'));
        done=0;
        if ~isempty(Bexpinit{2}) %deltaBin defini
           expdeltaBfin=[filename{2}(1:end-3),'mat']; %fichier contenant le deltaB 
           deltaB=deltaBin;
            save(fullfile(path2exp{2},expdeltaBfin),'deltaB');
            done=1;
        end
        if ~isempty(Bexpinit{1}) %deltaBout defini
            expdeltaBfout=[filename{1}(1:end-3),'mat'];
            deltaB=deltaBout;
             save(fullfile(path2exp{1},expdeltaBfout),'deltaB');
             done=1;
        end
        if done
            pause(0.2)
            set(hstoredeltaB,'string','Done!','foregroundcolor','r')
            pause(0.3)
            set(hstoredeltaB,'string','Store','foregroundcolor','k')
        end
    end

    function cllbckslidone(~,~)
       olddeltaB2=str2double(get(hdeltaBval{2},'string'));
       newdecal=get(hslidone,'value');
       
        set(hdeltaBval{1},'string',num2str(olddeltaB2+newdecal,'%3.2f'))
        plotspec
    end

    function cllbckslidboth(~,~)
        newdeltaB2=get(hslidboth,'value');
        olddeltaB2=str2double(get(hdeltaBval{2},'string'));
        decal=newdeltaB2-olddeltaB2;
        
        set(hdeltaBval{2},'string',num2str(newdeltaB2,'%3.2f'))
        if get(hsamedeltaB,'value')
            set(hdeltaBval{1},'string',num2str(newdeltaB2,'%3.2f'))
        else
            olddeltaB1=str2double(get(hdeltaBval{1},'string'));
            set(hdeltaBval{1},'string',num2str(decal+olddeltaB1,'%3.2f'))
                       
        end
        plotspec
    end

    function select_standard(~,~)
       %set(valdeltaB,'string','');
       ind=get(hstandardchoice,'value');
       greel=standard{ind,2};
       set(hgreel,'String',['g_real=',num2str(greel,'%5.4f')]);

        %%% pour spectre difference %%%
        if ~isempty(Bexpinit{2})
            Bg=1e3*planck*expfreq(2)*1e9/bmagn/standard{get(hstandardchoice,'value'),2};%mT a la frequence g out
            Bgmin=Bg-2;%mT
            Bgmax=Bg+2;%mT
            set(hBgmin,'string',num2str(Bgmin));
            set(hBgmax,'string',num2str(Bgmax));

            nbel=numel(Bexpinit{2});
            jj=1;

            if Bgmin<Bexpinit{2}(end) && Bgmax<=Bexpinit{2}(end)
                while Bexpinit{2}(jj)<Bgmin
                 jj=jj+1;
                end
                jjmin=jj;
                while Bexpinit{2}(jj)<Bgmax
                 jj=jj+1;
                end     
                jjmax=jj;
            else
                jjmin=1;
                jjmax=nbel;
            end
        end

       plotspec
    end

    function dispgmarkerrange(hobj,~)
        Brange=str2double(get(hobj,'string'));
        B2=get(hplotdiff,'xdata');
    
        if ~isnan(Brange) && Brange>=B2(1) && Brange<=B2(end)
            jj=1;
            while B2(jj)<Brange
                  jj=jj+1;  
            end
            if hobj==hBgmax
                jjmax=jj;
            else %hBgmin
                jjmin=jj;
            end
            set(hobj,'string',num2str(Brange));
        else
            if hobj==hBgmax
                Bg2=Bg+2;
                jj=1;
                while Bexpinit{2}(jj)<Bg2
                 jj=jj+1;
                end
                jjmin=jj;
            else %hBgmin
                Bg2=Bg-2;
                jj=1;
                while Bexpinit{2}(jj)<Bg2
                 jj=jj+1;
                end
                jjmin=jj;
            end
            set(hobj,'string',num2str(Bg2));
        end
        plotspec;
    end



    end
