function addgscale
%
%(Pour windows et linux?)
% utilitaire pour ajouter une échelle de g:
% dessin d'un rectangle blanc, aligne a la main avec sliders,
% trace des g
%  EE version sept-oct2013 
% EE version juillet 2020
close(findobj('type','figure','Name','Add g-scale'))

    warning('off','MATLAB:oldPfileVersion') % eviter warning: pcode file ...
    warning('off','MATLAB:hg:uicontrol:ParameterValuesMustBeValid') %eviter warning slider out of range

    ftsz=12;%fontsize en pixels
    ftsz2disp=12;%fontsize en pixels pour les valeurs de g affichees
    
    %handle d'initialisation
    versionyear=version('-date');
    versionyear=str2double(versionyear(end-4:end)); %annee version matlab
    if versionyear>=2014
            hinit=gobjects; %handle=structure
    else
            hinit=NaN; %handle=double
    end

    if versionyear>=2025
        tickNaN=[];
    else
        tickNaN=NaN;
    end
    
    defaultfreq=9.5;%GHz frequence par defaut
    usedfreq=defaultfreq; %frequence utilisee
    defaultname='Figure 1';
    hfigure2modify=str2double(defaultname(end));
    %hrect=hinit; %handle du rectangle blanc
    haxes2change=hinit; %handle de l'objet "axes" sur lequel le rectangle est trace
    %htext=hinit; %handle des affichages des valeurs de g
    %hline=hinit; %handle des "ticks" des valeurs de g
   % hlegend=hinit; %init handle d'1 eventuelle legende
    h2ndaxe=hinit; %init handle second axe
   % limitex=[0 1]; %=[min max] des x (init)
   % limitey=[0 1]; %=[min max] des y (init)
    
    %coeff pour positionner rectangle blc
    alphax=0;
    alphay=0;
    alphaw=1;
    alphah=0.05;
    
    gval=NaN; %init des valeurs de g
    
    formatstr='2'; %init format affichage des g nb de digit apres la virgule
    
% 
%     dispall();

    %% figure addgscale
%     if isempty(findobj('type','figure'))
%         haddgscale=figure(1);
%     else
       haddgscale=figure();%max(findobj('type','figure'))+1); %pour ne pas superposer des figures
%

    set(haddgscale,'Units','pixels','position',...    
        [500 500 400 260],...
        'Name','Add g-scale','Menubar', 'none', 'Toolbar','none','resize','off',...
        'NumberTitle','off','DoubleBuffer','on',...
        'color',get(0,'DefaultUicontrolBackgroundColor'));
%% Fig
    uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.1 0.89 0.2 0.08],...
            'parent',haddgscale,...
            'String','Figure X:',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'fontsize',ftsz,...
            'TooltipString','Figure name to modify');%,...
           % 'BackgroundColor','w');
    
     uicontrol(...
        'Parent',haddgscale,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@setmanfigname,...
        'FontSize',ftsz,...
        'Position',[0.32 0.9 0.32 0.08],...
        'TooltipString','Figure name to modify',...
        'Style','edit',...
        'string',defaultname);
    
    
 %% freq   
        uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.1 0.74 0.2 0.08],...
            'parent',haddgscale,...
            'String','Frequency:',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'fontsize',ftsz,...
            'TooltipString','Frequency to be considered in GHz');%,...
           % 'BackgroundColor','w');

         heditfreq = uicontrol(...
        'Parent',haddgscale,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@setmanfreq,...
        'FontSize',ftsz,...
        'Position',[0.32 0.75 0.32 0.08],...
        'TooltipString','Frequency to be considered in GHz',...
        'Style','edit',...
        'string',num2str(defaultfreq));

        uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.65 0.74 0.1 0.08],...
            'parent',haddgscale,...
            'String','GHz',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'fontsize',ftsz);%,...
           % 'TooltipString','Frequency to be considered in GHz');%,...
           % 'BackgroundColor','w');

            uicontrol(...
        'Parent',haddgscale,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'Callback',@getfreq,...
        'FontSize',ftsz,...
        'Position',[0.8 0.73 0.12 0.12],...
        'String','Get...',...
        'TooltipString','Get frequency from file...',...
        'enable','on',...
        'Style','pushbutton');
    
 %% axe position 
 sliderstep=[0.001 0.01]; %[0.001/0.1 0.01/0.1]
%          uicontrol('Style','text',...
%             'Units','Normalized',...
%             'pos',[0.08 0.36 0.15 0.03],...
%             'parent',haddgscale,...
%             'BackgroundColor','w');
        uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.03 0.35 0.2 0.18],'backgroundcolor',0.8*[1 1 1],...
            'parent',haddgscale,...
            'String',sprintf('  Position\nof the plot\nin the window'),...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'fontsize',ftsz);
        
        uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.25 0.57 0.1 0.08],...
            'parent',haddgscale,...
            'String','x',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'TooltipString','x-position of axe (bottom left corner)...',...
            'fontsize',ftsz);
        
         hxx=uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'BackgroundColor',[0.9 0.9 0.9],...
            'Callback',@cllbckslidx,...
            'Position',[0.35 0.57 0.48 0.08],...            'Min',0,...            'Max',0.1,...        'value',alphax,...
            'SliderStep',sliderstep,...
            'TooltipString','x-position of axe (bottom left corner)...',...
            'Style','slider');
        
         uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'FontUnits','pixels',...
            'Callback',@centerx,...
            'FontSize',ftsz,...
            'Position',[0.84 0.5 0.15 0.1],...
            'String','Center',...
            'TooltipString','Horizontally...',...
            'enable','on',...
            'Style','pushbutton');
        
         uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.25 0.31 0.1 0.08],...
            'parent',haddgscale,...
            'String','y',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'TooltipString','y-position of axe (bottom left corner)...',...
            'fontsize',ftsz);
        
         hyy=uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'BackgroundColor',[0.9 0.9 0.9],...
            'Callback',@cllbckslidy,...
            'Position',[0.35 0.31 0.48 0.08],...            'Min',-0.1,...            'Max',0,...            'value',alphay,...
            'SliderStep',sliderstep,...
            'TooltipString','y-position of axe (bottom left corner)...',...
            'Style','slider');
        
          uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'FontUnits','pixels',...
            'Callback',@centery,...
            'FontSize',ftsz,...
            'Position',[0.84 0.24 0.15 0.1],...
            'String','Center',...
            'TooltipString','Vertically...',...
            'enable','on',...
            'Style','pushbutton');
        
         uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.23 0.44 0.12 0.08],...
            'parent',haddgscale,...
            'String','width',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'TooltipString','axe width...',...
            'fontsize',ftsz);
        
         hwidth=uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'BackgroundColor',[0.9 0.9 0.9],...
            'Callback',@cllbckslidwidth,...
            'Position',[0.35 0.44 0.48 0.08],...            'Min',0.9,...            'Max',1,...            'value',alphaw,...
            'SliderStep',sliderstep,...
            'TooltipString','axe width...',...
            'Style','slider');
        
         uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.21 0.18 0.12 0.08],...
            'parent',haddgscale,...
            'String','height',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'TooltipString','axe height...',...
            'fontsize',ftsz);
        
         hheight=uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'BackgroundColor',[0.9 0.9 0.9],...
            'Callback',@cllbckslidheight,...
            'Position',[0.35 0.18 0.48 0.08],...'Min',0.001,...'Max',0.1,...            'value',alphah,...
            'SliderStep',sliderstep,...
            'TooltipString','axe height...',...
            'Style','slider');
        
%% g values
        uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.0 0.04 0.2 0.08],...
            'parent',haddgscale,...
            'String','g values:',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'fontsize',ftsz,...
            'TooltipString','g values to set (matlab vector, no [ ])');%,...
           % 'BackgroundColor','w');

         uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'FontUnits','pixels',...
            'BackgroundColor','w',...
            'Callback',@setgval,...
            'FontSize',ftsz,...
            'Position',[0.18 0.045 0.32 0.08],...
            'TooltipString','g values to set (matlab vector, no [ ])',...
            'HorizontalAlignment','left',...
            'Style','edit');
        
         uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'FontUnits','pixels',...
            'BackgroundColor','w',...
            'FontSize',ftsz,...
            'Position',[0.64 0.04 0.06 0.08],...
            'HorizontalAlignment','left',...
            'string',formatstr,...
            'Callback',@setformat,...
            'tooltipstring','Number of digits after the decimal point',...
            'Style','edit');
        
          uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.54 0.035 0.08 0.08],...
            'parent',haddgscale,...
            'String','X.XX',...
            'HorizontalAlignment','center',...
            'fontunits','pixels',...
            'fontsize',ftsz,...
            'TooltipString','Number of digits after the decimal point');%,...
           % 'BackgroundColor','w');
           
           
            uicontrol(...
            'Parent',haddgscale,...
            'Units','normalized',...
            'FontUnits','pixels',...
            'BackgroundColor','w',...
            'FontSize',ftsz,...
            'Position',[0.92 0.04 0.06 0.08],...
            'HorizontalAlignment','left',...
            'string',num2str(ftsz2disp),...
            'Callback',@setfontsize,...
            'tooltipstring','Fontsize of displayed g values',...
            'Style','edit');
        
          uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.77 0.035 0.13 0.08],...
            'parent',haddgscale,...
            'String','fontsize',...
            'HorizontalAlignment','right',...
            'fontunits','pixels',...
            'fontsize',ftsz,...'BackgroundColor','w',...
            'TooltipString','Fontsize of displayed g values');%,...
           
        
%% B units
          uicontrol('Style','text',...
            'Units','Normalized',...
            'pos',[0.65 0.89 0.18 0.08],...
            'parent',haddgscale,...
            'String','B units:',...
            'HorizontalAlignment','center',...'backgroundcolor','w',...
            'fontunits','pixels',...
            'fontsize',ftsz);
        
        Bunit={'mT';'G'};
%         Bunitstr='mT'; %par defaut
        multiplfactor=1e3;
        uicontrol(...
            'Parent',haddgscale,...
            'FontUnits','pixels',...
            'FontSize',ftsz,...
            'BackgroundColor','w',...
            'Units','normalized',...
            'Callback',@setBunit,...
            'Position',[0.805 0.88 0.13 0.1],...
            'String',Bunit,...
            'Style','popupmenu',...
            'Value',1);
        
        
%%        
      
dispall();

%% functions

    function setmanfigname(hobject,~)
        figname=get(hobject,'string');
        if isempty(strfind(figname,'Figure ')) %si le nom entre ne contient pas 'Figure '
            hfigure2modify=findobj('type','figure','Name','figname');
        else
            hfigure2modify=str2double(figname(strfind(figname,' '):end)); %handle de Figure 1 est 1 (ie apres espace)
        end
        h2ndaxe=hinit;
        dispall()
    end

    function setmanfreq(hobject,~)
       usedfreq=str2double(get(hobject,'string'));
       dispall()
    end

    function getfreq(~,~)
        [expspecf,path2expspec]=uigetfile(fullfile(pwd,'*.DSC;*.SPC'),'Select Spectrum'); %ouverture boite de dialogue dans repertoire courant (.DSC selectionnes)
        if expspecf~=0 %si non annule 
            [~,~,param]=eprload([path2expspec,expspecf]);
            if isfield(param,'MWFQ')
                usedfreq=param.MWFQ*1e-9; %frequence exp en GHz from ELEXSYS
            elseif isfield(param,'MF')
                usedfreq=param.MF; %en GHz from ESP
            else
                disp('No experimental frequency...')
                usedfreq=defaultfreq;
            end
            set(heditfreq,'string',num2str(usedfreq,'%7.6f'));
        end
        dispall()
    end

    function cllbckslidx(hobject,~)
        alphax=get(hobject,'value');
        dispall()
    end

    function cllbckslidy(hobject,~)
        alphay=get(hobject,'value');
        dispall()
    end


    function cllbckslidwidth(hobject,~)
        alphaw=get(hobject,'value');
        dispall()
    end

    function cllbckslidheight(hobject,~)
        alphah=get(hobject,'value');
        dispall()
    end

    function setgval(hobject,~)
       try
        eval(['gval=[',get(hobject,'string'),'];'])
       end
         dispall()
    end

    function setformat(hobject,~)
       formatstr=get(hobject,'string');
        dispall()
    end

    function setfontsize(hobject,~)
       ftsz2disp=str2double(get(hobject,'string'));
        dispall()
    end


    function setBunit(hobject,~)
        Bunitstr=Bunit{get(hobject,'value')};
        switch Bunitstr
            case 'mT'
                multiplfactor=1e3;
            case 'G'
                multiplfactor=1e4;
        end
        dispall()
    end

    function centerx(~,~)
        alphax=(1-alphaw)/2;
        set(hxx,'value',alphax)
        dispall()
    end

    function centery(~,~)
        alphay=(1-alphah)/2;
        set(hyy,'value',alphay)
        dispall()
    end


    function dispall()
        if ishandle(hfigure2modify) && ne(hfigure2modify,haddgscale) %si le nom de figure specifie est OK
                 
                 if ~ishandle(h2ndaxe)
                    
                     haxes2change=findobj(hfigure2modify,'type','axes','-not','Tag','legend','-not','Tag','Colorbar'); %handle du graphe
                     figure(hfigure2modify)
                  
                     set(haxes2change,'units','normalized','color','none');
                     axespos=get(haxes2change,'position');
                 
                     %init slider:
                     set(hxx,'value',axespos(1));
                     set(hyy,'value',axespos(2));
                     set(hwidth,'value',axespos(3));
                     set(hheight,'value',axespos(4));
                     alphax=axespos(1);alphay=axespos(2);alphaw=axespos(3);alphah=axespos(4);
                    
                     set(haxes2change,'box','off')


                     h2ndaxe=axes('position',get(haxes2change,'position'),'Xaxislocation','top','color','w',...
                         'Yaxislocation','right','ycolor',get(haxes2change,'ycolor'),'ytick',tickNaN,...
                         'xlim',get(haxes2change,'xlim'),'xtick',tickNaN,'xgrid','on','GridLineStyle',':','gridcolor','k');
                     xlabel('g value','parent',h2ndaxe,'fontsize',ftsz2disp)

                     htitle1=get(haxes2change,'title');
                     currenttitlestr=get(htitle1,'string');
                   
                     title(currenttitlestr,'Interpreter','none');
                     
                     
                     delete(htitle1)
                     
                    uistack(h2ndaxe,'bottom');

                 end


          set([haxes2change,h2ndaxe],'units','normalized','position',[alphax alphay alphaw alphah]);           

           if ~isnan(gval)

               Btick=multiplfactor*planck*usedfreq*1e9/bmagn./gval;
               [sortedBtick,itick]=sort(Btick);
               sortedgval=gval(itick);
               for k=1:numel(Btick)
                  tickcell{k}=num2str(sortedgval(k),['%2.',formatstr,'f']);
               end
               set(h2ndaxe,'xtick',sortedBtick,'xticklabel',tickcell,'fontsize',ftsz2disp)

           end

        end

 
    end
end