function saturation_absorbtion
% exctraction automatique d'une courbe de saturation a partir des spectres
% d'un dossier, sur signal d'absorption, avec correction ligne de base.
% Ajustement possible des amplitudes trouvees automatiquement.
% sauvegarde de la courbe de saturation
% EE mai 2016
% EE janv 2021 selectionner un point de la courbe de sat
% EE juin2021 pas de menu
% EE jan2022: sauvegarde figure en tif plutot que bmp
% EE avr2023: pbl plage des sliders
% EE oct2025: compatibilite avec Matlab2025

clear;close;clc;

% linetype={'Derivative';'Positive';'Negative'}; 
% linetypeval=[]; %default

%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

hsatcurve=hinit; %handle courbe de saturation
hdiag=hinit; %handle ligne diagonale sur courbe de saturation
hcurrent=hinit; %handle du point rouge du point de la courbe de sat correspondant au spectre courant
hLF=hinit; %handle rectangle bruit bas champ
hHF=hinit; %handle rectangle bruit haut champ
hsig=hinit; %handle rectangle signal
h_linesup=hinit; %handle ligne superieure
h_lineinf=hinit; %handle ligne inferieure
hlinetype=hinit; %handle popup menu
hspec=hinit; %handle courbe absorption
hprimcorr=hinit; %handle courbe abs corrigee
hbaseline=hinit; %handle ligne de base
hblLF=hinit; %handle rectangle bl bas champ
hblHF=hinit; %handle rectangle bl haut champ

polydeginit=3; %degre du polynome pour ligne de base




%% chargement des donnees
chemin=pwd;%uigetdir(pwd); % chemin du repertoire contenant les fichiers des spectres
dir_struct_mat=dir(fullfile(chemin,'*.mat')); % structure contenant le nom de fichier.mat 
reload=false; %par defaut nouveau chargement
if ~isempty(dir_struct_mat) 
    choice = questdlg('Do you want to load existing saturation curve on absorption?','','Yes','No','Yes');          
    switch choice
      case 'Yes'
          if numel(dir_struct_mat)==1
              file2load=dir_struct_mat.name;
          else
              file2load=uigetfile(fullfile(chemin,'*.mat'),'Select saturation curve on absorption to Open');
          end
          if not(isnumeric(file2load)) %no cancel;
            load(file2load);
            reload=true;
            disp(['Load ',file2load]);
            nbspec=numel(data);
          end
    end
   
end
if ~reload    
        dir_struct=dir(fullfile(chemin,'*.DSC')); % structure contenant les noms de fichier.DSC  
        nbspec=numel(dir_struct);
        if nbspec>1
        for k=1:nbspec
            data(k).name=dir_struct(k,1).name;%nom du fichier
            [B,spec,par]=eprload(fullfile(chemin,data(k).name));
            data(k).B=B/10;%B en mT
            MA=par.B0MA;%amplitude de modulation (T)
            nbsc=par.AVGS;%nb de scan
            RG=par.RCAG; %gain recepteur (dB)
            data(k).spec0=spec/MA/nbsc/10^(RG/20);%normalisation du signal par nb de scan, amplitude de modulation, gain recepteur
            data(k).spec=cumtrapz(data(k).B,data(k).spec0); %signal d'absorbtion
            data(k).puissance=1e3*par.MWPW;% puissance en mW
            data(k).sqrtpuissance=sqrt(par.MWPW);%racine de la puissance (en W) => en W^1/2

            data(k).polydeg=polydeginit; %degre bl
           
            data(k).B1min=data(k).B(1);%floor(data(k).B(1))+1;%plage de champ pour tenir compte du bruit (bas champ)
            data(k).B1max=data(k).B(1);%floor(data(k).B(1))+1;
            [data(k).imin1,data(k).imax1]=getindex([data(k).B1min data(k).B1max],k); %indice pour plage bas champ 

            data(k).B1_bl_min=data(k).B(1);
            data(k).B1_bl_max=data(k).B(1)+0.2*par.XWID/10;
            [data(k).imin1_bl,data(k).imax1_bl]=getindex([data(k).B1_bl_min data(k).B1_bl_max],k); %indice pour plage bl bas champ 
            
            data(k).B2min=floor(data(k).B(end));%plage de champ pour tenir compte du bruit (haut champ)
            data(k).B2max=floor(data(k).B(end));
            [data(k).imin2,data(k).imax2]=getindex([data(k).B2min data(k).B2max],k); %indice pour plage haut champ 

            data(k).B2_bl_min=data(k).B(end)-0.2*par.XWID/10;%plage de champ pour bl (haut champ)
            data(k).B2_bl_max=data(k).B(end);
            [data(k).imin2_bl,data(k).imax2_bl]=getindex([data(k).B2_bl_min data(k).B2_bl_max],k); %indice pour plage haut champ 
            
            data(k).Bsmin=floor(data(k).B(1)+(data(k).B(end)-data(k).B(1))/4);%plage de champ du signal
            data(k).Bsmax=floor(data(k).B(1)+3*(data(k).B(end)-data(k).B(1))/4);
            [data(k).imins,data(k).imaxs]=getindex([data(k).Bsmin data(k).Bsmax],k); %indice pour plage du signal 

            data(k).baseline=extractbaseline(data(k));%zeros(1,numel(data2D(k).spec));
            data(k).primcorr=data(k).spec-data(k).baseline;
            
            
            
            data(k).ysup=posline(k,'sup'); %ordonnee ligne superieure
            data(k).yinf=posline(k,'inf'); %ordonnee ligne inferieure
            data(k).amp=data(k).ysup-data(k).yinf;
            
        %     if data(k).amp==0
        %         data(k).amp=max(spec)-min(spec);
        %     end
            clear B spec par MA nbsc
        end

        else
                error('No data...');

        end
        [~,order]=sort([data(:).puissance]); %ordonner selon puissance croissante
        data=data(order);
end

if not(isnumeric(chemin)) %no cancel;

%% figure 
hsatmain=figure(1);
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(hsatmain,'Units','pixels','Outerposition',...    
    [scrszpix(3)/3 0.2*scrszpix(4) 1000 scrszpix(4)*0.8],...
    'Name','Saturation on Absorption','Menubar', 'none', 'Toolbar','none',...%'resize','off',...
    'NumberTitle','off',...'DoubleBuffer','on',...'CloseRequestFcn',@closeSimLabel,...
    'color',get(0,'DefaultUicontrolBackgroundColor'));

%         %%%% pour ne garder que les outils zoomin, zoomout et main
% hToolbar = findall(hsatmain,'tag','FigureToolBar'); %handle toolbar
% halltoolbar=allchild(hToolbar);%tous les handles de la toolbar
% hzoomin=findall(halltoolbar,'TooltipString','Zoom In');
% hzoomout=findall(halltoolbar,'TooltipString','Zoom Out');
% hhand=findall(halltoolbar,'TooltipString','Pan');
% halltoolbar(halltoolbar==hzoomin)=[];%supprime 1 handle a conserver
% halltoolbar(halltoolbar==hzoomout)=[];%supprime 1 handle a conserver
% halltoolbar(halltoolbar==hhand)=[];%supprime 1 handle a conserver
% set(halltoolbar,'visible','off')

%%% graphes spectres exp %%%
hspecaxes=axes('parent',hsatmain,'Position',[0.01 0.33 0.58 0.64],...
                'Box','on');
hslidsup=uicontrol('Style','slider','Units','Normalized','pos',[0.595 0.84 0.02 0.13],'BackgroundColor',[0.9 0.9 0.9],...
    'parent',hsatmain,'String',num2str(0),'Callback', @slidsup,'TooltipString','Adjust up line for amplitude extraction','SliderStep',[0.1/40 1/40]);%'fontunits','pixels','fontsize',ftsz,...
   % 'Min',-20,'Max',+20);%,'Value',0,'SliderStep',[0.1/40 1/40]);
   
hslidinf=uicontrol('Style','slider','Units','Normalized','pos',[0.595 0.33 0.02 0.13],'BackgroundColor',[0.9 0.9 0.9],...
    'parent',hsatmain,'String',num2str(0),'Callback', @slidinf,'TooltipString','Adjust bottom line for amplitude extraction','SliderStep',[0.1/40 1/40]);

%%% graphes courbe de saturation %%%
hsataxes=axes('parent',hsatmain,'Position',[0.64 0.5 0.35 0.47],...
                'Ytick',tickNaN,'Box','on');%,'Xtick',tickNaN);
hslidalpha=uicontrol('Style','slider','Units','Normalized','pos',[0.965 0.505 0.02 0.13],'BackgroundColor',[0.9 0.9 0.9],...
    'parent',hsatmain,'String',num2str(0),'Callback', @slidalpha,'TooltipString','Adjust vertical position of the diagonal',...
    'max',3,'min',-3,'sliderstep',[5e-2/40 0.5/40]);
   
%%% liste des spectres experimentaux
hlist=uicontrol('Style','listbox','Units','Normalized','pos',[0.74 0.01 0.25 0.38],...
    'parent',hsatmain,'max',1,'min',0,'Callback',{@dispexp,'new'},'fontunits','pixels',...'fontsize',ftsz,...
    'backgroundcolor','w','string',{data(:).name},'value',1,'fontsize',13);
if reload
    str2disp=['Previously saved data = ',file2load];
else
    out=regexp(chemin,filesep,'split');%pour separer les disques et dossiers du chemin et n'afficher que le dernier
        str2disp=['Directory of data = ',out{end}];
end

hpath=uicontrol('Style','text','Units','Normalized','pos',[0.64 0.40 0.35 0.02],...
    'parent',hsatmain,'String',str2disp,'HorizontalAlignment','center','tooltipstring',chemin);

        
%%% panel noise
hpanelnoise = uipanel('Parent',hsatmain,'FontWeight','bold','Title','Noise',...
        'Position',[0.02 0.12 0.35 0.15],'Units','Normalized',...[0.02 0.15 0.35 0.12]
        'FontUnits','pixels','FontSize',16,'FontWeight','bold');
    %low field
uicontrol('Style','text','Units','Normalized','pos',[0.05 0.7 0.33 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','Low Field: from','HorizontalAlignment','center','fontsize',11);
hB1min=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.39 0.69 0.15 0.21],...
        'Style','edit',...
    'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.54 0.7 0.15 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hB1max=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.69 0.69 0.15 0.21],...
        'Style','edit',...
        'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.84 0.7 0.1 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT','HorizontalAlignment','center','fontsize',11);    

    %high field
uicontrol('Style','text','Units','Normalized','pos',[0.05 0.25 0.33 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','High Field: from','HorizontalAlignment','center','fontsize',11);
hB2min=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.39 0.24 0.15 0.21],...
        'Style','edit',...
    'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.54 0.25 0.15 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hB2max=uicontrol('Parent',hpanelnoise,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor','b',...
        'Position',[0.69 0.24 0.15 0.21],...
        'Style','edit',...
        'TooltipString','No noise in the considered range if min=max.');
uicontrol('Style','text','Units','Normalized','pos',[0.84 0.25 0.1 0.2],...'BackgroundColor','w',....
    'parent',hpanelnoise,'String','mT','HorizontalAlignment','center','fontsize',11);  


%%% panel signal
hpanelsignal = uipanel('Parent',hsatmain,'FontWeight','bold','Title','Signal',...
        'Position',[0.02 0.03 0.25 0.08],'Units','Normalized',...
        'FontUnits','pixels','FontSize',16,'FontWeight','bold');

uicontrol('Style','text','Units','Normalized','pos',[0.05 0.05 0.2 0.8],...'BackgroundColor','w',....
    'parent',hpanelsignal,'String','From','HorizontalAlignment','center','fontsize',11);
hBsmin=uicontrol('Parent',hpanelsignal,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor',[0 0.7 0],...
        'Position',[0.26 0.3 0.2 0.5],...
        'Style','edit');
uicontrol('Style','text','Units','Normalized','pos',[0.47 0.051 0.2 0.8],...'BackgroundColor','w',....
    'parent',hpanelsignal,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hBsmax=uicontrol('Parent',hpanelsignal,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispnoiserange,...
        'FontSize',13,'foregroundcolor',[0 0.7 0],...
        'Position',[0.68 0.3 0.2 0.5],...
        'Style','edit');
uicontrol('Style','text','Units','Normalized','pos',[0.89 0.05 0.1 0.8],...'BackgroundColor','w',....
    'parent',hpanelsignal,'String','mT','HorizontalAlignment','center','fontsize',11);    


% hlinetype=uicontrol(...
%         'Parent',hpanelsignal,...
%         'FontUnits','pixels',...
%         'FontSize',13,...
%         'BackgroundColor','w',...
%         'Units','normalized',...
%         'Callback',@setlinetype,...
%         'Position',[0.2 0.25 0.35 0.15],...
%         'String',linetype,...
%         'Style','popupmenu',...
%         'Value',1);
% 
% uicontrol('Style','text','Units','Normalized','pos',[0.55 0.19 0.1 0.2],...'BackgroundColor','w',....
%     'parent',hpanelsignal,'String','line','HorizontalAlignment','center','fontsize',11);    

uicontrol('Style','pushbutton','String','Send to all spectra','Units','Normalized','HorizontalAlignment','center',...
    'pos',[0.35 0.02 0.1 0.05],'parent',hsatmain,'Callback', @sent,...[0.3 0.02 0.1 0.05]
    'fontunits','pixels','fontsize',11);

uicontrol('Style','pushbutton','String','Send to next spectra','Units','Normalized','HorizontalAlignment','center',...
    'pos',[0.46 0.02 0.1 0.05],'parent',hsatmain,'Callback', @sentnext,...[0.41 0.02 0.1 0.05]
    'fontunits','pixels','fontsize',11);

uicontrol('Style','pushbutton','String','Save Sat. Curve','Units','Normalized','HorizontalAlignment','center',...
    'pos',[0.57 0.02 0.1 0.05],'parent',hsatmain,'Callback', @savesat,...[0.52 0.02 0.1 0.05]
    'fontunits','pixels','fontsize',11);


%%% + et -

uicontrol('Style', 'pushbutton', 'String', 'v','Units','Normalized','Position', [0.69 0.29 0.05 0.05],...
    'parent',hsatmain,'Callback',{@plus_or_minus_fctn,'+'},'tooltipstring','Change spectrum');
%     uicontrol(plusbutton);%set(plusbutton,'selected','off'); %focus par défaut sur bouton +
uicontrol('Style', 'pushbutton', 'String', '^','Units','Normalized','Position', [0.69 0.34 0.05 0.05],...
    'parent',hsatmain,'Callback', {@plus_or_minus_fctn,'-'},'tooltipstring','Change spectrum');


%%% panel baseline
% noisestrLF=sprintf('If min=max, noise at low field is not\nconsidered for amplitude extraction.');
% noisestrHF=sprintf('If min=max, noise at high field is not\nconsidered for amplitude extraction.');
hpanelbl = uipanel('Parent',hsatmain,'FontWeight','bold','Title','Baseline',...
        'Position',[0.38 0.12 0.35 0.15],'Units','Normalized',...
        'FontUnits','pixels','FontSize',16,'FontWeight','bold');
    %low field
uicontrol('Style','text','Units','Normalized','pos',[0.05 0.7 0.33 0.2],...'BackgroundColor','w',....
    'parent',hpanelbl,'String','Low Field: from','HorizontalAlignment','center','fontsize',11);
hB1_bl_min=uicontrol('Parent',hpanelbl,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispblrange,...
        'FontSize',13,'foregroundcolor',[1 0.6 0],...
        'Position',[0.39 0.69 0.15 0.21],...
        'Style','edit');%,...
    %'TooltipString',noisestrLF);
uicontrol('Style','text','Units','Normalized','pos',[0.54 0.7 0.15 0.2],...'BackgroundColor','w',....
    'parent',hpanelbl,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hB1_bl_max=uicontrol('Parent',hpanelbl,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispblrange,...
        'FontSize',13,'foregroundcolor',[1 0.6 0],...
        'Position',[0.69 0.69 0.15 0.21],...
        'Style','edit');%,...
        %'TooltipString',noisestrLF);
uicontrol('Style','text','Units','Normalized','pos',[0.84 0.7 0.1 0.2],...'BackgroundColor','w',....
    'parent',hpanelbl,'String','mT','HorizontalAlignment','center','fontsize',11);    

%     %high field
uicontrol('Style','text','Units','Normalized','pos',[0.05 0.35 0.33 0.2],...'BackgroundColor','w',....
    'parent',hpanelbl,'String','High Field: from','HorizontalAlignment','center','fontsize',11);
hB2_bl_min=uicontrol('Parent',hpanelbl,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispblrange,...
        'FontSize',13,'foregroundcolor',[1 0.6 0],...
        'Position',[0.39 0.34 0.15 0.21],...
        'Style','edit');%,...
    %'TooltipString',noisestrHF);
uicontrol('Style','text','Units','Normalized','pos',[0.54 0.35 0.15 0.2],...'BackgroundColor','w',....
    'parent',hpanelbl,'String','mT to','HorizontalAlignment','center','fontsize',11);    
hB2_bl_max=uicontrol('Parent',hpanelbl,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@dispblrange,...
        'FontSize',13,'foregroundcolor',[1 0.6 0],...
        'Position',[0.69 0.34 0.15 0.21],...
        'Style','edit');%,...
        %'TooltipString',noisestrHF);
uicontrol('Style','text','Units','Normalized','pos',[0.84 0.35 0.1 0.2],...'BackgroundColor','w',....
    'parent',hpanelbl,'String','mT','HorizontalAlignment','center','fontsize',11);  

% 
% %%% panel signal
% hpanelsignal = uipanel('Parent',hsatmain,'FontWeight','bold','Title','baseline degree',...
%         'Position',[0.38 0.12 0.25 0.15],'Units','Normalized',...
%         'FontUnits','pixels','FontSize',16,'FontWeight','bold');

uicontrol('Style','text','Units','Normalized','pos',[0.3 0.05 0.2 0.2],...'BackgroundColor','w',....
    'parent',hpanelbl,'String','degree =','HorizontalAlignment','center','fontsize',11);
hdegree=uicontrol('Parent',hpanelbl,...
        'Units','normalized',...
        'FontUnits','pixels',...
        'BackgroundColor','w',...
        'Callback',@setpolydeg,...
        'FontSize',13,'foregroundcolor',[1 0.6 0],...
        'Position',[0.51 0.06 0.11 0.21],...
        'Style','edit',...
        'string',num2str(polydeginit));








%init
if data(1).amp==0
    alpha1initnum=max(data(1).spec)-min(data(1).spec);
else
    alpha1initnum=data(1).amp;
end
alpha1=log10(alpha1initnum/data(1).sqrtpuissance); %init facteur de propportionalite pour diag sur sat curve
alpha2=0;
    set(hslidinf,'value',alpha2);
dispexp(hlist,[],'new')

end

%%
function dispexp(hobject,~,status) %affichage spectre  
    rang=get(hobject,'value'); %numero du spectre dans la liste

    if strcmp(status,'new')
        h2del=get(hspecaxes,'children');
        delete(h2del);
        hspec=plot(hspecaxes,data(rang).B,data(rang).spec,'color',[0.6 0.6 0.6],'linewidth',2);hold(hspecaxes,'on');

        set(hspecaxes,'xlim',[data(rang).B(1) data(rang).B(end)],'Ytick',tickNaN,...
        'ylim',1.1*[min([min(data(rang).spec) min(data(rang).primcorr)]) max(data(rang).spec)]);

        xlabel(hspecaxes,'Magnetic Field [mT]');
        set(hB1min,'string',num2str(data(rang).B1min));
        set(hB1max,'string',num2str(data(rang).B1max));
        set(hB2min,'string',num2str(data(rang).B2min));
        set(hB2max,'string',num2str(data(rang).B2max));
        set(hB1_bl_min,'string',num2str(data(rang).B1_bl_min));
        set(hB1_bl_max,'string',num2str(data(rang).B1_bl_max));
        set(hB2_bl_min,'string',num2str(data(rang).B2_bl_min));
        set(hB2_bl_max,'string',num2str(data(rang).B2_bl_max));
        set(hBsmin,'string',num2str(data(rang).Bsmin));
        set(hBsmax,'string',num2str(data(rang).Bsmax));
        set(hdegree,'string',num2str(data(rang).polydeg));
        %set(hlinetype,'value',data(rang).linetypeval);

        %rectangles pour bruit, bl et signal
        hLF=disprect('B1',rang,data(rang).primcorr); %noise low field
        hHF=disprect('B2',rang,data(rang).primcorr); %noise high field
        hblLF=disprect('B1_bl_',rang,data(rang).spec); %bl low field
        hblHF=disprect('B2_bl_',rang,data(rang).spec); %bl high field
        hsig=disprect('Bs',rang,data(rang).primcorr); %signal

        

        %init sliders
        [imins,imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang);
        maxrange=max(data(rang).spec(imins:imaxs));
        minrange=min(data(rang).spec(imins:imaxs));
        set(hslidsup,'value',data(rang).ysup,'max',maxrange+0.4*sign(maxrange)*maxrange,'min',minrange);
        set(hslidinf,'value',data(rang).yinf,'max',maxrange,'min',minrange-0.1*maxrange);
        title(hspecaxes,[num2str(data(rang).puissance),' mW / Amplitude = ',num2str(data(rang).amp,'%3.2e')]);

    % correction ligne de base
        data(rang).baseline=extractbaseline(data(rang));
        x=data(rang).spec;
        y=data(rang).baseline;
        data(rang).primcorr=x-y;

        hprimcorr=plot(hspecaxes,data(rang).B,data(rang).primcorr,'k');%,'linewidth',2);
        
        hbaseline=plot(hspecaxes,data(rang).B,data(rang).baseline,'color',[1 0.6 0]);
        
        legend(hspecaxes,[hspec,hprimcorr,hbaseline],'exp. absorp.','corr. absorp.','baseline','AutoUpdate','off')
    
        %lines pour extraction amplitude
        [imins,imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang);
        h_linesup=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).ysup*[1 1],'color','m','parent',hspecaxes);
        h_lineinf=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).yinf*[1 1],'color','m','parent',hspecaxes);
    
    else %status=old
         delete([h_linesup,h_lineinf]); %hLF,hHF,hsig

        %lines pour extraction amplitude
        [imins,imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang);
        h_linesup=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).ysup*[1 1],'color','m','parent',hspecaxes);
        h_lineinf=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).yinf*[1 1],'color','m','parent',hspecaxes);
        title(hspecaxes,[num2str(data(rang).puissance),' mW / Amplitude = ',num2str(data(rang).amp,'%3.2e')]);
    end
    
    dispsat() %affichage courbe de saturation 
end

function baseline=extractbaseline(data)
    x=data.B([data.imin1_bl:data.imax1_bl,data.imin2_bl:data.imax2_bl]);
    y=data.spec([data.imin1_bl:data.imax1_bl,data.imin2_bl:data.imax2_bl]);
        [pol,S,MU]=polyfit(x,y,data.polydeg);
    baseline=polyval(pol,data.B,S,MU);
end


function dispsat() %affichage courbe de saturation 
    if ishandle(hsatcurve)
        delete(hsatcurve)
    end
    if ishandle(hcurrent)
        delete(hcurrent)
    end
    if ishandle(hdiag)
        delete(hdiag)
    end
    
    hsatcurve=loglog([data.sqrtpuissance],[data.amp],'ob','parent',hsataxes);hold on
    set(hsatcurve,'ButtonDownFcn',@MouseleftclicksatCllbck);
    xlabel(hsataxes,'sqrt(P) [W^{1/2}]');
    ylabel(hsataxes,'EPR amplitude [a.u.]');
    title(hsataxes,'Saturation Curve on Absorption');    
    % point du spectre courant en rouge
    rang=get(hlist,'value');
    hcurrent=plot(data(rang).sqrtpuissance,data(rang).amp,'ob','MarkerFaceColor','m','parent',hsataxes);
    
    %ligne diag

    hdiag=plot([data(:).sqrtpuissance],[data(:).sqrtpuissance]*10^alpha1*10^alpha2,':k','parent',hsataxes);

end

function [imin,imax]=getindex(rangeB,rang) %recherche des indices de la plage de champ à considérer 
    i=1;

    while data(rang).B(i)<rangeB(1)
        i=i+1;
    end
    imin=i;
    while data(rang).B(i)<rangeB(2)
        i=i+1;
    end
    imax=i;
end

function dispnoiserange(~,~) %callback des edit des plages de champ pour bruit et signal
    if ishandle(hLF)
        delete(hLF)
    end
    if ishandle(hHF)
        delete(hHF)
    end
    if ishandle(hsig)
        delete(hsig)
    end
    if ishandle(h_linesup)
        delete(h_linesup)
    end
    if ishandle(h_lineinf)
        delete(h_lineinf)
    end
    rang=get(hlist,'value');
    data(rang).B1_bl_min=str2double(get(hB1_bl_min,'string'));%plage de champ pour tenir compte du bruit (bas champ)
    data(rang).B1max=str2double(get(hB1max,'string'));
    [data(rang).imin1,data(rang).imax1]=getindex([data(rang).B1_bl_min data(rang).B1max],rang); %indice pour plage bas champ 

    data(rang).B2min=str2double(get(hB2min,'string'));%plage de champ pour tenir compte du bruit (haut champ)
    data(rang).B2max=str2double(get(hB2max,'string'));
    [data(rang).imin2,data(rang).imax2]=getindex([data(rang).B2min data(rang).B2max],rang); %indice pour plage haut champ 
   
    data(rang).Bsmin=str2double(get(hBsmin,'string'));%plage de champ du signal
    data(rang).Bsmax=str2double(get(hBsmax,'string'));
   [data(rang).imins,data(rang).imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang); %indice pour plage du signal 

     %rectangles pour bruit et signal
    hLF=disprect('B1',rang,data(rang).primcorr); %noise low field
    hHF=disprect('B2',rang,data(rang).primcorr); %noise high field
    hsig=disprect('Bs',rang,data(rang).primcorr); %signal

    
    %maj
    data(rang).ysup=posline(rang,'sup'); %ordonnee ligne superieure
    data(rang).yinf=posline(rang,'inf'); %ordonnee ligne inferieure
    data(rang).amp=data(rang).ysup-data(rang).yinf;
        
    %lines pour extraction amplitude
    [imins,imaxs]=getindex([data(rang).Bsmin data(rang).Bsmax],rang);
    h_linesup=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).ysup*[1 1],'color','m','parent',hspecaxes);
    h_lineinf=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).yinf*[1 1],'color','m','parent',hspecaxes);
    % maj sliders
    set(hslidsup,'value',data(rang).ysup);
    set(hslidinf,'value',data(rang).yinf);
    
    dispexp(hlist,[],'old')
    %dispsat() %affichage courbe de saturation
end

function dispblrange(~,~) %callback des edit des plages de champ pour bruit et signal
    if ishandle(hblLF)
        delete(hblLF)
    end
    if ishandle(hblHF)
        delete(hblHF)
    end

    rang=get(hlist,'value');
    data(rang).B1_bl_min=str2double(get(hB1_bl_min,'string'));%plage de champ pour tenir compte du bruit (bas champ)
    data(rang).B1_bl_max=str2double(get(hB1_bl_max,'string'));
    [data(rang).imin1_bl,data(rang).imax1_bl]=getindex([data(rang).B1_bl_min data(rang).B1_bl_max],rang); %indice pour plage bas champ 

    data(rang).B2_bl_min=str2double(get(hB2_bl_min,'string'));%plage de champ pour tenir compte du bruit (haut champ)
    data(rang).B2_bl_max=str2double(get(hB2_bl_max,'string'));
    [data(rang).imin2_bl,data(rang).imax2_bl]=getindex([data(rang).B2_bl_min data(rang).B2_bl_max],rang); %indice pour plage haut champ 
   


     %rectangles pour bl
    hblLF=disprect('B1_bl_',rang,data(rang).spec); %low field
    hblHF=disprect('B2_bl_',rang,data(rang).spec); %high field



    %maj
    delete([hprimcorr,hbaseline]);
    data(rang).baseline=extractbaseline(data(rang));
        x=data(rang).spec;
        y=data(rang).baseline;
        data(rang).primcorr=x-y;
       
        hprimcorr=plot(hspecaxes,data(rang).B,data(rang).primcorr,'k');hold(hspecaxes,'on');
        hbaseline=plot(hspecaxes,data(rang).B,data(rang).baseline,'color',[1 0.6 0],'linewidth',2);hold(hspecaxes,'on');
    
    
    
    
    
    
    
%     data(rang).ysup=posline(data(rang),'sup'); %ordonnee ligne superieure
%     data(rang).yinf=posline(data(rang),'inf'); %ordonnee ligne inferieure
%     data(rang).amp=data(rang).ysup-data(rang).yinf;
        
    %lines pour extraction amplitude
%     [imins,imaxs]=getindex(data(rang).B,[data(rang).Bsmin data(rang).Bsmax]);
%     h_linesup=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).ysup*[1 1],'color','m','parent',hspecaxes);
%     h_lineinf=line([data(rang).B(imins) data(rang).B(imaxs)],data(rang).yinf*[1 1],'color','m','parent',hspecaxes);
%     % maj sliders
%     set(hslidsup,'value',data(rang).ysup);
%     set(hslidinf,'value',data(rang).yinf);
    
    dispexp(hlist,[],'old')
    %dispsat() %affichage courbe de saturation => cinetique
end

function setpolydeg(~,~)
    rang=get(hlist,'value');
    data(rang).polydeg=int8(str2double(get(hdegree,'string')));
    set(hdegree,'string',num2str(data(rang).polydeg));
    dispexp(hlist,[],'new')
end


function h=disprect(fieldB,rang,datay) %affichage des rectangles pour visu des plages
    [imin,imax]=getindex([data(rang).([fieldB,'min']) data(rang).([fieldB,'max'])],rang);
    limy=get(hspecaxes,'ylim');
    if imin==imax
        amp=max(datay)-min(datay);
        pos=[data(rang).([fieldB,'min']) -amp/10  0.01 amp/5];
    else
        amp=max(datay(imin:imax))-min(datay(imin:imax));
        pos=[data(rang).([fieldB,'min']) min(datay(imin:imax))...
             data(rang).([fieldB,'max'])-data(rang).([fieldB,'min'])...
             amp];
    end
    switch fieldB
        case 'B1'
            color='b';
        case 'B2'
            color='b';
        case 'B1_bl_'
            color=[1 0.6 0];
        case 'B2_bl_'
            color=[1 0.6 0];   
     
        case 'Bs'
            color=[0 0.7 0];
            graphe_lim=get(hspecaxes,'Ylim');
            pos([2 4])= [0.95*graphe_lim(1) 0.95*(graphe_lim(2)-graphe_lim(1))];
        
    end
    
    h=rectangle('parent',hspecaxes,'position',pos,'Edgecolor',color);
end

function y=posline(rang,arg) %ordonnee de  line arg='sup' ou 'inf'
        amp_bruit1=NaN; %amplitude bruit bas champ
        std1=NaN; %deviation standard bruit bas champ
        amp_bruit2=NaN; %amplitude bruit haut champ
        std2=NaN; %deviation standard bruit haut champ
        if data(rang).B1min~=data(rang).B1max %noise a bas champ
            maxbruit1=max(data(rang).primcorr(data(rang).imin1:data(rang).imax1));
            minbruit1=min(data(rang).primcorr(data(rang).imin1:data(rang).imax1));
            amp_bruit1=maxbruit1-minbruit1;
            std1=std(data(rang).primcorr(data(rang).imin1:data(rang).imax1));
        end
        if data(rang).B2min~=data(rang).B2max %noise a haut champ
            maxbruit2=max(data(rang).primcorr(data(rang).imin2:data(rang).imax2));
            minbruit2=min(data(rang).primcorr(data(rang).imin2:data(rang).imax2));
            amp_bruit2=maxbruit2-minbruit2;
            std2=std(data(rang).primcorr(data(rang).imin2:data(rang).imax2));
        end
%         if ishandle(hlinetype)
%             linetypeval=get(hlinetype,'value');
%         else 
            linetypeval=1; %par defaut derivative line
%         end
        switch arg
            case 'sup' %ordonnee superieur
                if linetypeval==3 %raie negative
                    y=0;
                else
                    maxspec=max(data(rang).primcorr(data(rang).imins:data(rang).imaxs));
                    % amplitude moyenne bruit
                    amp_bruit_all=[amp_bruit1 amp_bruit2];
                    amp_bruit_all(isnan(amp_bruit_all))=[]; %supprime les NaN
                    amp_bruit=mean(amp_bruit_all); %NaN si isempty(amp_bruit)
                    if isnan(amp_bruit) 
                        amp_bruit=0;
                    end
                    % deviation standard moyenne bruit
                    std_bruit_all=[std1 std2];
                    std_bruit_all(isnan(std_bruit_all))=[]; %supprime les NaN
                    std_bruit=mean(std_bruit_all); %NaN si isempty(std_bruit)
                    if isnan(std_bruit)
                        std_bruit=0;
                    end
                     y=maxspec-mean([amp_bruit/2 std_bruit]);
                end
                
            case 'inf' %ordonnee inferieur
                if linetypeval==2 %raie positive
                    y=0;
                else
                    minspec=0;%min(data(rang).primcorr(data(rang).imins:data(rang).imaxs));
                    % amplitude moyenne bruit
                    amp_bruit_all=[amp_bruit1 amp_bruit2];
                    amp_bruit_all(isnan(amp_bruit_all))=[]; %supprime les NaN
                    amp_bruit=mean(amp_bruit_all); %NaN si isempty(amp_bruit)
                    if isnan(amp_bruit) 
                        amp_bruit=0;
                    end
                    % deviation standard moyenne bruit
                    std_bruit_all=[std1 std2];
                    std_bruit_all(isnan(std_bruit_all))=[]; %supprime les NaN
                    std_bruit=mean(std_bruit_all); %NaN si isempty(std_bruit)
                    if isnan(std_bruit)
                        std_bruit=0;
                    end
                     y=minspec+mean([amp_bruit/2 std_bruit]);
               
                end
                
        end
                
end

function slidsup(hObject,~)
    rang=get(hlist,'value');
    data(rang).ysup=get(hObject,'value');
    data(rang).amp=abs(data(rang).ysup-data(rang).yinf);
    dispexp(hlist,[],'old')
end

function slidinf(hObject,~)
    rang=get(hlist,'value');
    data(rang).yinf=get(hObject,'value');
    data(rang).amp=abs(data(rang).ysup-data(rang).yinf);
    dispexp(hlist,[],'old')
end

function slidalpha(~,~)
    alpha2=get(hslidalpha,'value');
    dispexp(hlist,[],'old')%dispsat()
end

function sent(~,~)
    rang=get(hlist,'value');
    for n=1:nbspec
        data(n).B1min=data(rang).B1min;%plage de champ pour tenir compte du bruit (bas champ)
        data(n).B1max=data(rang).B1max;
        data(n).imin1=data(rang).imin1;
        data(n).imax1=data(rang).imax1; %indice pour plage bas champ 

        data(n).B2min=data(rang).B2min;%plage de champ pour tenir compte du bruit (haut champ)
        data(n).B2max=data(rang).B2max;
        data(n).imin2=data(rang).imin2;
        data(n).imax2=data(rang).imax2; %indice pour plage haut champ 

        data(n).B1_bl_min=data(rang).B1_bl_min;%plage de champ pour bl (bas champ)
        data(n).B1_bl_max=data(rang).B1_bl_max;
        data(n).imin1_bl=data(rang).imin1_bl;
        data(n).imax1_bl=data(rang).imax1_bl; %indice pour plage bas champ 

        data(n).B2_bl_min=data(rang).B2_bl_min;%plage de champ pour bl (haut champ)
        data(n).B2_bl_max=data(rang).B2_bl_max;
        data(n).imin2_bl=data(rang).imin2_bl;
        data(n).imax2_bl=data(rang).imax2_bl; %indice pour plage haut champ 
        
        data(n).Bsmin=data(rang).Bsmin;%plage de champ du signal
        data(n).Bsmax=data(rang).Bsmax;
        data(n).imins=data(rang).imins;
        data(n).imaxs=data(rang).imaxs; %indice pour plage du signal 

        data(n).ysup=posline(n,'sup'); %ordonnee ligne superieure
        data(n).yinf=posline(n,'inf'); %ordonnee ligne inferieure
        data(n).amp=data(n).ysup-data(n).yinf;
        data(n).polydeg=data(rang).polydeg;
    end
    
    %dispsat()
    dispexp(hlist,[],'old')
end

function sentnext(~,~)
    rang=get(hlist,'value');
    if rang<nbspec
    for n=rang+1:nbspec
        data(n).B1min=data(rang).B1min;%plage de champ pour tenir compte du bruit (bas champ)
        data(n).B1max=data(rang).B1max;
        data(n).imin1=data(rang).imin1;
        data(n).imax1=data(rang).imax1; %indice pour plage bas champ 

        data(n).B2min=data(rang).B2min;%plage de champ pour tenir compte du bruit (haut champ)
        data(n).B2max=data(rang).B2max;
        data(n).imin2=data(rang).imin2;
        data(n).imax2=data(rang).imax2; %indice pour plage haut champ 

        data(n).B1_bl_min=data(rang).B1_bl_min;%plage de champ pour bl (bas champ)
        data(n).B1_bl_max=data(rang).B1_bl_max;
        data(n).imin1_bl=data(rang).imin1_bl;
        data(n).imax1_bl=data(rang).imax1_bl; %indice pour plage bas champ 

        data(n).B2_bl_min=data(rang).B2_bl_min;%plage de champ pour bl (haut champ)
        data(n).B2_bl_max=data(rang).B2_bl_max;
        data(n).imin2_bl=data(rang).imin2_bl;
        data(n).imax2_bl=data(rang).imax2_bl; %indice pour plage haut champ 
        
        data(n).Bsmin=data(rang).Bsmin;%plage de champ du signal
        data(n).Bsmax=data(rang).Bsmax;
        data(n).imins=data(rang).imins;
        data(n).imaxs=data(rang).imaxs; %indice pour plage du signal 

        data(n).ysup=posline(n,'sup'); %ordonnee ligne superieure
        data(n).yinf=posline(n,'inf'); %ordonnee ligne inferieure
        data(n).amp=data(n).ysup-data(n).yinf;
        data(n).polydeg=data(rang).polydeg;
    end
    end
    %dispsat()
    dispexp(hlist,[],'old')
end


function savesat(~,~)
    %%% sauvegarde fichier txt
    [fnametxt,path2save]=uiputfile(fullfile(chemin,'*.txt'));
  if ~isnumeric(fnametxt) %no cancel
    fid=fopen(fullfile(path2save,fnametxt),'w');
    fprintf(fid,'%12s\t','Power');
    fprintf(fid,'%12s\t','sqrtPower');
    fprintf(fid,'%12s\t','Amplitude');
    fprintf(fid,'%12s\n','File name');
    fprintf(fid,'%12s\t','[mW]');
    fprintf(fid,'%12s\t','[W^1/2]');
    fprintf(fid,'%12s\t','[ ]');
    fprintf(fid,'%12s\n','[ ]');
    for i=1:nbspec
        taillename(i)=numel(data(i).name);
    end
    maxname=max(taillename);
    for i=1:nbspec
        fprintf(fid,'%12.4f\t',data(i).puissance); %power mW
        fprintf(fid,'%12.5e\t',data(i).sqrtpuissance); %sqrt(power) W^1/2
        fprintf(fid,'%12.5e\t',data(i).amp);
        fprintf(fid,['%',num2str(maxname),'s\n'],data(i).name);
    end
    fclose(fid);
    
    % save plot
    figure2save=figure;%(max(findobj('type','figure'))+1); %pour ne pas superposer des figures 
    set(figure2save,'Units','pixels','Name','Saturation curve','NumberTitle','on','visible','on',...
            'Position',[300 300 400 400],'Menubar', 'figure','Toolbar', 'figure');
    hnew=copyobj(hsataxes,figure2save);%graphe(=axes)+legend copier dans nouvelle figure
    set(hnew,'units','normalized','position',[0.15 0.12 0.8 0.8])%,...
    title(hnew,['Saturation curve: ',fnametxt(1:end-4)],'interpreter','none');
    
    set(findobj(hnew,'MarkerFaceColor','m'),'MarkerFaceColor','none');
    set(figure2save,'visible','on');
    saveas(figure2save,fullfile(path2save,[fnametxt(1:end-3),'tif']));
    saveas(figure2save,fullfile(path2save,[fnametxt(1:end-3),'fig']));
    delete(figure2save);
    
    %save data
    save(fullfile(path2save,[fnametxt(1:end-3),'mat']),'data');
  end
end

% function setlinetype(~,~)
%       for n=1:nbspec
%           data(n).ysup=posline(n,'sup'); %ordonnee ligne superieure
%           data(n).yinf=posline(n,'inf'); %ordonnee ligne inferieure
%           data(n).amp=data(n).ysup-data(n).yinf;
%       end
%       dispexp(hlist,[],'old');
% 
% end


function plus_or_minus_fctn(~,~,strsign) %strsign='+' ou '-'
    rang=get(hlist,'value');
   switch strsign
       case '+'
           if rang~=nbspec
               rang=rang+1;
           end         
           
       case '-'
           if rang~=1
               rang=rang-1;
           end   
   end
   set(hlist,'value',rang);
   dispexp(hlist,[],'new');    

end
function MouseleftclicksatCllbck(~,~)
    delete(hcurrent)
    p = get(hsataxes,'CurrentPoint');
    p = p(1,1:2);
%     if isempty(find(p)) %p ne contient pas de zero
        minsearch=[abs(([data.sqrtpuissance]-p(1))./[data.sqrtpuissance]);abs(([data.amp]-p(2))./[data.amp])];
%     else
%         minsearch=[abs([data.sqrtpuissance]-p(1));abs([data.amp]-p(2))];
%     end
    [~,rang]=min(sum(minsearch,1));%min(abs([data.time]+tdelay-p(1)));%recherche du rang avec valeur de temps la plus proche
    hcurrent=plot(data(rang).sqrtpuissance,data(rang).amp,'ob','MarkerFaceColor','m','parent',hsataxes);
    set(hlist,'value',rang);
    dispexp(hlist,[],'new');

end

end